⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
feat: show what agents spend, for a team and for a workspace (#526)
Croffefdc8956de04
diff --git a/.env.example b/.env.exampleindex 79351fa3..aca1d4d8 100644--- a/.env.example+++ b/.env.example@@ -120,6 +120,7 @@ APP_ENCRYPTION_KEY=# AGENT_RUN_MAX_ATTEMPTS=3 # attempts before a run is marked failed# AGENT_RUN_LEASE_SECONDS=300 # claim lease for crash recovery# AUTO_ARCHIVE_INTERVAL_MS=3600000 # how often the auto-archive sweep runs (own loop)+# AGENT_TRACE_PRUNE_INTERVAL_MS=3600000 # how often traces past their retention are deleted (own loop)# ── Chat with an external agent (apps/api): the feed its runner drains ──# AGENT_CHAT_LEASE_SECONDS=300 # claim lease; an abandoned answer is served again after thisdiff --git a/apps/api/AGENTS.md b/apps/api/AGENTS.mdindex e0f30c91..ae4676c9 100644--- a/apps/api/AGENTS.md+++ b/apps/api/AGENTS.md@@ -117,8 +117,8 @@ Enforced declaratively through macros, never imperative calls in handlers.`getTeamAccess` in `shared/access.ts` merge the membership with the grant, and everyguard reads them. The lists that decide what the caller sees — `listProjects`, theteam list, `readRevs` — take the reached teams the same way, and answer `via:- 'workspace'` for what the caller reaches only through the workspace. Everything that- asks whether *someone else* is a member — assignees, mentions, watchers, notification+'workspace'` for what the caller reaches only through the workspace. Everything that+ asks whether _someone else_ is a member — assignees, mentions, watchers, notificationrecipients, seats, the last-owner check, SCIM — still reads the rows, so a workspacemanager is in none of the member lists, gets no notifications and takes no seat.- **`:projectKey` routes:** `.use(guards)` and set `permission: ["<resource>",@@ -129,7 +129,7 @@ Enforced declaratively through macros, never imperative calls in handlers.options (e.g. `workItem: "edit"`). `GET /issues/:issueId` instead asserts`assertPermission` on the fetched row, and spreads `requiresPermission([...])` into its`detail` so the MCP tool table still reports what it requires. `GET- /projects/:projectKey/issues/:sequenceNumber` does the same for an old number that+/projects/:projectKey/issues/:sequenceNumber` does the same for an old number thatresolved to an issue now in another project. `POST /issues/:issueId/move` checks thetarget project in the `moveTarget` macro, which reads `projectId` from the body.- Every guard publishes the pair it asserts as `x-permission` on the route's OpenAPI@@ -172,7 +172,7 @@ Enforced declaratively through macros, never imperative calls in handlers.`:userId` use `memberSelfOrAdmin` instead: that member acts on their own row —leaving the project, saying what they do in it — with no member permission at all.The one standing the member permission does not carry is `owner`: an owner bypasses- the matrix, so adding one, promoting to one and *inviting* one all go through the+ the matrix, so adding one, promoting to one and _inviting_ one all go through thesame rule — an owner of the project, or an owner or manager of the team that owns it(`assertProjectAdmin`, and `mayGrantInviteRanks` for the invite). The team rank isstricter still: only a team owner grants, takes or invites `owner` and `manager`@@ -203,11 +203,44 @@ Two decisions a reader would otherwise propose again:flag on the user. An agent is reachable through its team or not at all.- **The `ai_agents` permissions are administrative.** A role granting `create` or `edit`can make an agent, attach it to the projects the caller sees, and read its key — so- granting either is granting everything an agent of those projects can reach.+ granting either is granting everything an agent of those projects can reach. What the+ agents spent is a resource of its own, `agent_usage`, read only, so reading it+ administers nothing.- **An agent's role is its `project_member` row**, per project, set from the project'smember list like a person's. Attaching an agent joins it on the team's default role;`members/` refuses to make it an owner, since an owner bypasses the matrix.+Runs of an internal agent are traced. `runtime/observability.ts` holds the one Mastra+container of the process: an agent built for a run writes no spans on its own, so every+one is registered with it, and its exporter writes the spans into Mastra's own table on+the application database. A run names what it belongs to in the trace metadata — the+agent, the team, the project, the issue and the schedule, and either the queued run with+its trigger or, for a chat run, the person who asked — which is what `runtime/traces.ts`+filters on, since the spans carry no foreign keys of ours. How long they are kept is the+instance setting under god mode (`app_setting` key `agents`); `runtime/trace-retention.ts`+applies it from the api's background loop. The window applies to whole runs: the sweep+finds the root spans past it and deletes their traces whole, and the same sweep drops+the traces of a deleted team.++The same traces back the agent dashboard (`runtime/analytics.ts`) at+`GET /teams/:teamId/agent-analytics`: runs, tokens and cost by model, agent, project and+day, over a window and the same span before it. Its owner and managers read every project+of the team; anyone else the projects where their role grants `agent_usage` `read`+(`projectsWithPermission` in `shared/access.ts`), since a role is set per project and a+team-wide figure would show the others. The response names those projects+(`readableProjects`), and `projectId` narrows the dashboard to one of them.+`GET /workspaces/:workspaceId/agent-analytics` reads it over every team of a workspace,+with the teams compared, for its owner and its admins.++Cost is applied in the api, not read from a span. Mastra computes it in a metrics+pipeline that needs an analytics store its Postgres adapter does not implement, so the+spans arrive with raw token counts and `runtime/model-pricing.ts` prices them from the+table `@mastra/observability` bundles for that pipeline (`dist/metrics/pricing-data.jsonl`).+Its provider ids are the registry `AI_PROVIDERS` mirrors, so a credential's integration+key matches it directly. The file is outside the package's exports map: a release that+moves it leaves the table empty, an unpriced call reports no cost, and the dashboard shows+the tokens without an amount.+Over MCP the team is resolved from the API key rather than asked for (`mcp/server.ts`):an agent's key acts in its own team, a person with one team in theirs, and a person inseveral passes `teamId` after reading `list_teams`.@@ -233,12 +266,29 @@ undoes one.(`modules/agents/schedules/extension.ts`): schedule types of its own beside `cron` and`status`; the `options` it keeps on a schedule, checked on every write and, with the idmaps, on a project copy; and which issues start a schedule's run. `queueScheduleRuns`- (`issue-runs.ts`) queues the runs of its types on issues, with the trigger `event`.+ (`issue-runs.ts`) queues the runs of its types on issues, with the trigger `event`. A+ schedule of a type or with options no installed extension reads (`isScheduleSupported`)+ stays as it is, so it works again once the extension is back, but starts no run and+ answers 409 to an update; only a delete goes through.- `setRunAdmission` (`modules/agents/core/run-admission.ts`): the seconds a claimed runwaits before it starts, asked in the poller and in a runner's claim.- `onProjectEvent` (`modules/webhooks/emit.ts`): every issue and comment event thewebhooks get, inside the request that caused it.+Functions with no setter, for the routes such a build adds:++- `getAgentAnalytics({ teamIds, projectIds }, days)`+ (`modules/agents/core/runtime/analytics.ts`): the agent dashboard over any set of+ teams, or some of their projects.+- `tracedRuns(scope, from)`, `analyticsWindow(days)` (same file): the runs the dashboard+ is read from, with the whole trace metadata, and its window, for figures of the+ build's own.+- `workspaceScope(workspaceId)`, `onlyProject(scope, projectId)` (same file): the scope+ of the workspace dashboard, and a scope narrowed to one project as the team dashboard+ does it.+- `estimateCost` (`runtime/model-pricing.ts`): what a model call costs.+- `projectsWithPermission` (`shared/access.ts`): the projects a member may read.+## SCIM`modules/scim/` serves SCIM 2.0 (RFC 7643 / 7644) at `/scim/v2` for an identity providerdiff --git a/apps/api/package.json b/apps/api/package.jsonindex 60866a39..9df9fe2b 100644--- a/apps/api/package.json+++ b/apps/api/package.json@@ -25,6 +25,7 @@"@firecrawl/pdf-inspector": "^1.17.0","@mastra/core": "^1.58.0","@mastra/memory": "^1.26.1",+ "@mastra/observability": "^1.17.6","@mastra/pg": "^1.20.0","@modelcontextprotocol/sdk": "^1.30.0","@repo/agent-tools": "workspace:*",diff --git a/apps/api/src/background.ts b/apps/api/src/background.tsindex f8661194..f258a5da 100644--- a/apps/api/src/background.ts+++ b/apps/api/src/background.ts@@ -1,12 +1,14 @@import { intEnv } from '#shared/lib';import { agentRunConfig } from '#modules/agents/core/run-queue';import { processAgentRuns } from '#modules/agents/core/run-poller';+import { pruneAgentTraces } from '#modules/agents/core/runtime/trace-retention';import { sweepStaleIssues } from '#modules/issues/auto-archive';// The api's background jobs, started by index.ts rather than assembled into the app,// so importing the app in a test starts nothing. Several api replicas run them without-// overlapping: the queue is claimed with FOR UPDATE SKIP LOCKED, and the sweep only-// touches rows it has not archived yet.+// overlapping: the queue is claimed with FOR UPDATE SKIP LOCKED, the archive sweep only+// touches rows it has not archived yet, and the trace sweep deletes whatever is still+// past the window.// Each job gets a loop of its own. A run is an LLM call of minutes and a first sweep// can carry thousands of issues, so sharing one loop would let either hold the other@@ -16,6 +18,7 @@ export function startBackgroundJobs(): void {// Archiving is not time-sensitive, so the sweep runs far less often than the queue// is drained.startLoop('auto-archive', autoArchive, () => intEnv('AUTO_ARCHIVE_INTERVAL_MS', 3_600_000));+ startLoop('agent-traces', pruneTraces, () => intEnv('AGENT_TRACE_PRUNE_INTERVAL_MS', 3_600_000));}async function autoArchive(): Promise<void> {@@ -23,6 +26,11 @@ async function autoArchive(): Promise<void> {if (archived > 0) console.log(`[background] auto-archived ${archived} stale issues`);}+async function pruneTraces(): Promise<void> {+ const deleted = await pruneAgentTraces();+ if (deleted > 0) console.log(`[background] pruned ${deleted} agent trace spans`);+}+function startLoop(name: string, job: () => Promise<void>, intervalMs: () => number): void {const tick = async () => {try {diff --git a/apps/api/src/modules/agents/core/__tests__/integration/agent-analytics.test.ts b/apps/api/src/modules/agents/core/__tests__/integration/agent-analytics.test.tsnew file mode 100644index 00000000..6ebf570c--- /dev/null+++ b/apps/api/src/modules/agents/core/__tests__/integration/agent-analytics.test.ts@@ -0,0 +1,309 @@+import { describe, it, expect, beforeEach } from 'bun:test';+import { SpanType } from '@mastra/core/observability';+import { authedApi, type Api } from '#tests/helpers/app';+import { signUpTestUser } from '#tests/helpers/auth';+import { resetDb } from '#tests/helpers/db';+import { createAgent, projectIdOf, teamOf } from '#tests/helpers/agents';+import { createRole } from '#tests/helpers/roles';+import { addProjectMember } from '#tests/helpers/members';+import { getStore } from '../../runtime/store';++// The agent dashboard, GET /teams/:teamId/agent-analytics and the same over a+// workspace, GET /workspaces/:workspaceId/agent-analytics. It reads the traces the+// runtime records, so the spans are seeded the way the exporter writes them: a root+// span for the run carrying the metadata the queries scope on, a model call carrying+// the provider, the model and its token counts, and a tool call, which counts for+// nothing here.++async function setup() {+ const owner = await signUpTestUser({ name: 'Owner' });+ const asOwner = authedApi(owner.cookie);+ await asOwner.projects.post({ key: 'MKT', name: 'Marketing' });+ return { asOwner, teamId: await teamOf(asOwner, 'MKT') };+}++async function createScout(asOwner: Api) {+ const res = await createAgent(asOwner, 'MKT', {+ name: 'Scout',+ username: 'scout',+ kind: 'internal',+ });+ return res.data!.agent.id;+}++let nextId = 0;+const spanId = () => `analytics-span-${++nextId}`;++function daysAgo(days: number): Date {+ return new Date(Date.now() - days * 24 * 60 * 60 * 1000);+}++function hoursAgo(hours: number): Date {+ return new Date(Date.now() - hours * 60 * 60 * 1000);+}++async function seedRun(+ traceId: string,+ metadata: Record<string, unknown>,+ startedAt: Date,+ usage: { inputTokens: number; outputTokens: number },+ failed = false,+): Promise<void> {+ await getStore().init();+ const store = (await getStore().getStore('observability'))!;+ const root = spanId();+ await store.createSpan({+ span: {+ traceId,+ spanId: root,+ name: 'agent run',+ spanType: SpanType.AGENT_RUN,+ isEvent: false,+ startedAt,+ endedAt: new Date(startedAt.getTime() + 2000),+ ...(failed ? { error: { message: 'boom' } } : {}),+ metadata,+ },+ });+ await store.createSpan({+ span: {+ traceId,+ spanId: spanId(),+ parentSpanId: root,+ name: 'inference: 0',+ spanType: SpanType.MODEL_INFERENCE,+ isEvent: false,+ startedAt,+ endedAt: new Date(startedAt.getTime() + 1500),+ attributes: { provider: 'openai', model: 'gpt-5-mini', usage },+ },+ });+ await store.createSpan({+ span: {+ traceId,+ spanId: spanId(),+ parentSpanId: root,+ name: 'create_issue',+ spanType: SpanType.TOOL_CALL,+ isEvent: false,+ startedAt,+ endedAt: new Date(startedAt.getTime() + 300),+ },+ });+}++const teamDashboard = (api: Api, teamId: number) => api.teams({ teamId })['agent-analytics'];+const workspaceDashboard = (api: Api, workspaceId: number) =>+ api.workspaces({ workspaceId })['agent-analytics'];++async function ownWorkspaceId(api: Api): Promise<number> {+ return (await api.workspaces.get()).data!.find((one) => one.role === 'owner')!.id;+}++describe('agent analytics', () => {+ beforeEach(async () => {+ await resetDb();+ });++ it('adds up the runs, tokens and cost of the window', async () => {+ const { asOwner, teamId } = await setup();+ const agentId = await createScout(asOwner);+ const projectId = await projectIdOf(asOwner, 'MKT');+ const meta = { agentId, teamId, projectId };+ await seedRun('an-1', meta, daysAgo(1), { inputTokens: 1_000_000, outputTokens: 500_000 });+ await seedRun('an-2', meta, daysAgo(2), { inputTokens: 200_000, outputTokens: 0 }, true);+ // Before the window, so it only counts towards what the period is compared against.+ await seedRun('an-old', meta, daysAgo(40), { inputTokens: 10, outputTokens: 10 });++ const res = await teamDashboard(asOwner, teamId).get({ query: { days: 30 } });+ expect(res.status).toBe(200);+ const body = res.data!;+ expect(body.totals).toMatchObject({+ runs: 2,+ errors: 1,+ inputTokens: 1_200_000,+ outputTokens: 500_000,+ });+ // openai/gpt-5-mini: 2.5e-7 in, 2e-6 out.+ expect(body.totals.cost).toBeCloseTo(1.2 * 0.25 + 0.5 * 2, 6);+ expect(body.previous).toMatchObject({ runs: 1, inputTokens: 10, outputTokens: 10 });++ expect(body.models).toEqual([+ {+ provider: 'openai',+ model: 'gpt-5-mini',+ calls: 2,+ inputTokens: 1_200_000,+ outputTokens: 500_000,+ cost: body.totals.cost,+ },+ ]);+ expect(body.agents).toMatchObject([{ agentId, name: 'Scout', runs: 2, errors: 1 }]);+ expect(body.projects).toMatchObject([{ projectId, name: 'Marketing', runs: 2, errors: 1 }]);+ expect(body.teams).toMatchObject([{ teamId, runs: 2, errors: 1 }]);+ expect(body.tokensPerDay).toHaveLength(2);+ });++ it('splits the window by project', async () => {+ const { asOwner, teamId } = await setup();+ await asOwner.projects.post({ key: 'OPS', name: 'Operations' });+ const agentId = await createScout(asOwner);+ const mkt = await projectIdOf(asOwner, 'MKT');+ const ops = await projectIdOf(asOwner, 'OPS');+ await seedRun('an-mkt', { agentId, teamId, projectId: mkt }, daysAgo(1), {+ inputTokens: 300,+ outputTokens: 0,+ });+ await seedRun('an-ops', { agentId, teamId, projectId: ops }, daysAgo(1), {+ inputTokens: 100,+ outputTokens: 0,+ });++ const res = await teamDashboard(asOwner, teamId).get();+ expect(res.data!.projects.map((p) => [p.name, p.inputTokens])).toEqual([+ ['Marketing', 300],+ ['Operations', 100],+ ]);+ });++ it('narrows the window to one project', async () => {+ const { asOwner, teamId } = await setup();+ await asOwner.projects.post({ key: 'OPS', name: 'Operations' });+ const agentId = await createScout(asOwner);+ const mkt = await projectIdOf(asOwner, 'MKT');+ const ops = await projectIdOf(asOwner, 'OPS');+ const usage = { inputTokens: 100, outputTokens: 0 };+ await seedRun('an-mkt', { agentId, teamId, projectId: mkt }, daysAgo(1), usage);+ await seedRun('an-ops', { agentId, teamId, projectId: ops }, daysAgo(1), usage);++ const res = await teamDashboard(asOwner, teamId).get({ query: { projectId: ops } });+ expect(res.data!.totals.runs).toBe(1);+ expect(res.data!.projects.map((p) => p.name)).toEqual(['Operations']);+ expect(res.data!.readableProjects.map((p) => p.name)).toEqual(['Marketing', 'Operations']);+ });++ it('reads a window of a day by the hour', async () => {+ const { asOwner, teamId } = await setup();+ const meta = {+ agentId: await createScout(asOwner),+ teamId,+ projectId: await projectIdOf(asOwner, 'MKT'),+ };+ const usage = { inputTokens: 100, outputTokens: 100 };+ await seedRun('an-h1', meta, hoursAgo(1), usage);+ // Yesterday by the calendar, still inside the last 24 hours.+ await seedRun('an-h20', meta, hoursAgo(20), usage);+ await seedRun('an-h30', meta, hoursAgo(30), usage);++ const res = await teamDashboard(asOwner, teamId).get({ query: { days: 1 } });+ expect(res.status).toBe(200);+ expect(res.data!.totals.runs).toBe(2);+ expect(res.data!.previous.runs).toBe(1);+ // Both runs of the window sit in an hour bucket of their own.+ expect(res.data!.tokensPerDay).toHaveLength(2);+ });++ it('counts a run of the first day of the window in the window', async () => {+ const { asOwner, teamId } = await setup();+ const meta = {+ agentId: await createScout(asOwner),+ teamId,+ projectId: await projectIdOf(asOwner, 'MKT'),+ };+ // A minute after the window opens, in a day bucket that starts before it.+ const startedAt = new Date(daysAgo(30).getTime() + 60_000);+ await seedRun('an-edge', meta, startedAt, { inputTokens: 100, outputTokens: 100 });++ const res = await teamDashboard(asOwner, teamId).get({ query: { days: 30 } });+ expect(res.data!.totals).toMatchObject({ runs: 1, inputTokens: 100 });+ expect(res.data!.previous).toMatchObject({ runs: 0, inputTokens: 0 });+ });++ it("leaves out another team's runs", async () => {+ const { asOwner, teamId } = await setup();+ const meta = { agentId: await createScout(asOwner), projectId: 1 };+ await seedRun('an-other', { ...meta, teamId: teamId + 1000 }, daysAgo(1), {+ inputTokens: 100,+ outputTokens: 100,+ });++ const res = await teamDashboard(asOwner, teamId).get();+ expect(res.data!.totals.runs).toBe(0);+ });++ it('closes the dashboard to a member whose role does not grant usage', async () => {+ const { asOwner, teamId } = await setup();+ const role = await createRole(asOwner, 'MKT', {+ name: 'Agent handler',+ permissions: { ai_agents: { read: true } },+ });+ const asMember = await addProjectMember(asOwner, 'MKT', role.data!.id);++ expect((await teamDashboard(asMember, teamId).get()).status).toBe(403);+ });++ it('shows a member with usage only the projects where their role grants it', async () => {+ const { asOwner, teamId } = await setup();+ await asOwner.projects.post({ key: 'OPS', name: 'Operations' });+ const agentId = await createScout(asOwner);+ const usage = { inputTokens: 100, outputTokens: 0 };+ const mkt = await projectIdOf(asOwner, 'MKT');+ const ops = await projectIdOf(asOwner, 'OPS');+ await seedRun('an-mkt', { agentId, teamId, projectId: mkt }, daysAgo(1), usage);+ await seedRun('an-ops', { agentId, teamId, projectId: ops }, daysAgo(1), usage);+ const role = await createRole(asOwner, 'MKT', {+ name: 'Spend watcher',+ permissions: { agent_usage: { read: true } },+ });+ const asMember = await addProjectMember(asOwner, 'MKT', role.data!.id);++ const res = await teamDashboard(asMember, teamId).get();+ expect(res.status).toBe(200);+ expect(res.data!.totals.runs).toBe(1);+ expect(res.data!.projects.map((p) => p.name)).toEqual(['Marketing']);+ expect(res.data!.readableProjects.map((p) => p.name)).toEqual(['Marketing']);+ const other = await teamDashboard(asMember, teamId).get({ query: { projectId: ops } });+ expect(other.data!.totals.runs).toBe(0);+ });++ it('reads every team of the workspace and compares them', async () => {+ const { asOwner, teamId } = await setup();+ const ops = (await asOwner.teams.post({ name: 'Ops', slug: 'ops' })).data!;+ const meta = {+ agentId: await createScout(asOwner),+ projectId: await projectIdOf(asOwner, 'MKT'),+ };+ await seedRun('ws-mkt', { ...meta, teamId }, daysAgo(1), { inputTokens: 300, outputTokens: 0 });+ await seedRun('ws-ops', { ...meta, teamId: ops.id }, daysAgo(1), {+ inputTokens: 100,+ outputTokens: 0,+ });+ await seedRun('ws-other', { ...meta, teamId: teamId + 1000 }, daysAgo(1), {+ inputTokens: 999,+ outputTokens: 0,+ });++ const res = await workspaceDashboard(asOwner, await ownWorkspaceId(asOwner)).get({+ query: { days: 30 },+ });+ expect(res.status).toBe(200);+ expect(res.data!.totals).toMatchObject({ runs: 2, inputTokens: 400 });+ expect(res.data!.teams.map((row) => [row.teamId, row.inputTokens])).toEqual([+ [teamId, 300],+ [ops.id, 100],+ ]);+ expect(res.data!.teams[1]!.name).toBe('Ops');+ });++ it('closes the workspace dashboard to somebody who only works in a team of it', async () => {+ const { asOwner } = await setup();+ const role = await createRole(asOwner, 'MKT', {+ name: 'Spend watcher',+ permissions: { agent_usage: { read: true } },+ });+ const asMember = await addProjectMember(asOwner, 'MKT', role.data!.id);++ const res = await workspaceDashboard(asMember, await ownWorkspaceId(asOwner)).get();+ expect(res.status).toBe(404);+ });+});diff --git a/apps/api/src/modules/agents/core/__tests__/integration/agent-traces.test.ts b/apps/api/src/modules/agents/core/__tests__/integration/agent-traces.test.tsnew file mode 100644index 00000000..c7344d79--- /dev/null+++ b/apps/api/src/modules/agents/core/__tests__/integration/agent-traces.test.ts@@ -0,0 +1,267 @@+import { describe, it, expect, beforeEach } from 'bun:test';+import { SpanType } from '@mastra/core/observability';+import { authedApi, type Api } from '#tests/helpers/app';+import { signUpTestUser } from '#tests/helpers/auth';+import { resetDb } from '#tests/helpers/db';+import { createAgent, projectIdOf, teamOf } from '#tests/helpers/agents';+import { createRole } from '#tests/helpers/roles';+import { addProjectMember } from '#tests/helpers/members';+import { getStore } from '../../runtime/store';+import { pruneAgentTraces } from '../../runtime/trace-retention';+import { setAgentSettings } from '#modules/settings/service';++// The trace endpoints:+// GET /teams/:teamId/ai-agents/:agentId/traces — the traces of its runs+// GET /teams/:teamId/ai-agents/:agentId/traces/:traceId — one trace with its spans+//+// A trace is written by the runtime through Mastra (see runtime/observability), which+// needs a live model call, so the spans are seeded straight into the store the way the+// exporter writes them: a root span for the run carrying the metadata the endpoints+// filter on, and a child span for a tool call.++async function setup() {+ const owner = await signUpTestUser({ name: 'Owner' });+ const asOwner = authedApi(owner.cookie);+ await asOwner.projects.post({ key: 'MKT', name: 'Marketing' });+ return { asOwner, teamId: await teamOf(asOwner, 'MKT') };+}++const agents = (api: Api, teamId: number) => api.teams({ teamId })['ai-agents'];+const traces = (api: Api, teamId: number, agentId: number) =>+ agents(api, teamId)({ agentId }).traces;++async function createInternalAgent(asOwner: Api, name: string, username: string) {+ const res = await createAgent(asOwner, 'MKT', { name, username, kind: 'internal' });+ return res.data!.agent;+}++let nextId = 0;+const spanId = () => `span-${++nextId}`;++function daysAgo(days: number): Date {+ return new Date(Date.now() - days * 24 * 60 * 60 * 1000);+}++async function seedTrace(+ traceId: string,+ metadata: Record<string, unknown>,+ startedAt: Date,+): Promise<void> {+ await getStore().init();+ const store = (await getStore().getStore('observability'))!;+ const root = spanId();+ await store.createSpan({+ span: {+ traceId,+ spanId: root,+ name: 'agent run',+ spanType: SpanType.AGENT_RUN,+ isEvent: false,+ startedAt,+ endedAt: new Date(startedAt.getTime() + 1500),+ input: 'do the thing',+ output: 'done',+ metadata,+ },+ });+ await store.createSpan({+ span: {+ traceId,+ spanId: spanId(),+ parentSpanId: root,+ name: 'create_issue',+ spanType: SpanType.TOOL_CALL,+ isEvent: false,+ startedAt: new Date(startedAt.getTime() + 100),+ endedAt: new Date(startedAt.getTime() + 400),+ input: { title: 'Task' },+ output: { id: 7 },+ },+ });+}++describe('agent traces', () => {+ beforeEach(async () => {+ await resetDb();+ });++ it("lists the agent's traces newest first, with what each run belongs to", async () => {+ const { asOwner, teamId } = await setup();+ const agent = await createInternalAgent(asOwner, 'Scout', 'scout');+ const projectId = await projectIdOf(asOwner, 'MKT');+ await seedTrace(+ 'trace-old',+ { agentId: agent.id, teamId, projectId, runId: 11, trigger: 'mention', issueId: 3 },+ new Date('2026-01-01T10:00:00Z'),+ );+ // Mastra puts its own run id, a UUID, on a run that names none of ours.+ await seedTrace(+ 'trace-new',+ { agentId: agent.id, teamId, projectId, runId: '6e9edb53-5103-4d2d-bb27-7cdbc1294782' },+ new Date('2026-01-02T10:00:00Z'),+ );++ const res = await traces(asOwner, teamId, agent.id).get();+ expect(res.status).toBe(200);+ expect(res.data!.total).toBe(2);+ expect(res.data!.items.map((t) => t.traceId)).toEqual(['trace-new', 'trace-old']);+ expect(res.data!.items[1]).toMatchObject({+ status: 'success',+ durationMs: 1500,+ projectId,+ runId: 11,+ trigger: 'mention',+ issueId: 3,+ });+ // A chat run is queued nowhere, so its trace names no run.+ expect(res.data!.items[0]).toMatchObject({ runId: null, trigger: null });+ });++ it('reads one trace with its steps, and not one of another agent', async () => {+ const { asOwner, teamId } = await setup();+ const agent = await createInternalAgent(asOwner, 'Scout', 'scout');+ const other = await createInternalAgent(asOwner, 'Guide', 'guide');+ const projectId = await projectIdOf(asOwner, 'MKT');+ await seedTrace(+ 'trace-1',+ { agentId: agent.id, teamId, projectId },+ new Date('2026-01-01T10:00:00Z'),+ );++ const res = await traces(asOwner, teamId, agent.id)({ traceId: 'trace-1' }).get();+ expect(res.status).toBe(200);+ expect(res.data!.trace.traceId).toBe('trace-1');+ expect(res.data!.spans.map((s) => s.type)).toEqual(['agent_run', 'tool_call']);+ expect(res.data!.spans[1]).toMatchObject({+ name: 'create_issue',+ durationMs: 300,+ input: { title: 'Task' },+ output: { id: 7 },+ });++ const wrong = await traces(asOwner, teamId, other.id)({ traceId: 'trace-1' }).get();+ expect(wrong.status).toBe(404);+ });++ it('gives a member only the traces of a project they belong to', async () => {+ const { asOwner, teamId } = await setup();+ await asOwner.projects.post({ key: 'OPS', name: 'Operations' });+ const agent = await createInternalAgent(asOwner, 'Scout', 'scout');+ const mkt = await projectIdOf(asOwner, 'MKT');+ const ops = await projectIdOf(asOwner, 'OPS');+ await agents(asOwner, teamId)({ agentId: agent.id }).projects.put({ projectIds: [mkt, ops] });+ await seedTrace('trace-mkt', { agentId: agent.id, teamId, projectId: mkt }, new Date());+ await seedTrace('trace-ops', { agentId: agent.id, teamId, projectId: ops }, new Date());++ const role = await createRole(asOwner, 'MKT', {+ name: 'Agent handler',+ permissions: { ai_agents: { read: true } },+ });+ const asMember = await addProjectMember(asOwner, 'MKT', role.data!.id);++ // The owner runs the team, so both projects are theirs.+ const all = await traces(asOwner, teamId, agent.id).get();+ expect(all.data!.total).toBe(2);++ // The member reads one project at a time, and only one they are in.+ const asMemberTraces = traces(asMember, teamId, agent.id);+ expect((await asMemberTraces.get()).status).toBe(403);++ const theirs = await asMemberTraces.get({ query: { projectId: mkt } });+ expect(theirs.data!.items.map((t) => t.traceId)).toEqual(['trace-mkt']);++ const refused = await asMemberTraces.get({ query: { projectId: ops } });+ expect(refused.status).toBe(403);++ const hidden = await asMemberTraces({ traceId: 'trace-ops' }).get();+ expect(hidden.status).toBe(403);+ });++ it("keeps a member's chat to them, the team's owner included", async () => {+ const { asOwner, teamId } = await setup();+ const agent = await createInternalAgent(asOwner, 'Scout', 'scout');+ const projectId = await projectIdOf(asOwner, 'MKT');+ const role = await createRole(asOwner, 'MKT', {+ name: 'Agent handler',+ permissions: { ai_agents: { read: true } },+ });+ const user = await signUpTestUser();+ const invite = await asOwner+ .projects({ projectKey: 'MKT' })+ .invites.post({ email: user.email, role: 'member', roleId: role.data!.id });+ const member = authedApi(user.cookie);+ await member.invites({ token: invite.data!.token }).accept.post();+ const meta = { agentId: agent.id, teamId, projectId };+ await seedTrace('trace-chat', { ...meta, userId: user.userId }, new Date());+ await seedTrace('trace-queued', { ...meta, runId: 11, trigger: 'mention' }, new Date());++ const owners = await traces(asOwner, teamId, agent.id).get();+ expect(owners.data!.items.map((t) => t.traceId)).toEqual(['trace-queued']);+ expect(owners.data!.total).toBe(1);+ const hidden = await traces(asOwner, teamId, agent.id)({ traceId: 'trace-chat' }).get();+ expect(hidden.status).toBe(404);++ const theirs = await traces(member, teamId, agent.id).get({ query: { projectId } });+ expect(theirs.data!.items.map((t) => t.traceId).sort()).toEqual(['trace-chat', 'trace-queued']);+ const read = await traces(member, teamId, agent.id)({ traceId: 'trace-chat' }).get();+ expect(read.status).toBe(200);+ });+});++// The sweep the api runs on its own interval. The window is the instance setting, and a+// trace whose team is gone goes whatever the window says.+describe('agent trace retention', () => {+ beforeEach(async () => {+ await resetDb();+ });++ async function seedAged(asOwner: Api, teamId: number, agentId: number) {+ const projectId = await projectIdOf(asOwner, 'MKT');+ const meta = { agentId, teamId, projectId };+ await seedTrace('trace-old', meta, daysAgo(40));+ await seedTrace('trace-recent', meta, daysAgo(5));+ }++ const traceIds = async (asOwner: Api, teamId: number, agentId: number) => {+ const res = await traces(asOwner, teamId, agentId).get();+ return res.data!.items.map((t) => t.traceId);+ };++ it('deletes the traces past the instance window and keeps the rest', async () => {+ const { asOwner, teamId } = await setup();+ const agent = await createInternalAgent(asOwner, 'Scout', 'scout');+ await seedAged(asOwner, teamId, agent.id);+ await setAgentSettings({ traceRetentionDays: 30 });++ expect(await pruneAgentTraces()).toBeGreaterThan(0);++ expect(await traceIds(asOwner, teamId, agent.id)).toEqual(['trace-recent']);+ });++ it('keeps every trace when the instance keeps them all', async () => {+ const { asOwner, teamId } = await setup();+ const agent = await createInternalAgent(asOwner, 'Scout', 'scout');+ await seedAged(asOwner, teamId, agent.id);+ await setAgentSettings({ traceRetentionDays: 0 });++ await pruneAgentTraces();++ expect(await traceIds(asOwner, teamId, agent.id)).toEqual(['trace-recent', 'trace-old']);+ });++ it('drops the traces of a team that no longer exists', async () => {+ const { asOwner, teamId } = await setup();+ const agent = await createInternalAgent(asOwner, 'Scout', 'scout');+ const projectId = await projectIdOf(asOwner, 'MKT');+ await seedTrace(+ 'trace-orphan',+ { agentId: agent.id, teamId: teamId + 1000, projectId },+ new Date(),+ );+ await seedTrace('trace-mine', { agentId: agent.id, teamId, projectId }, new Date());++ await pruneAgentTraces();++ expect(await traceIds(asOwner, teamId, agent.id)).toEqual(['trace-mine']);+ });+});diff --git a/apps/api/src/modules/agents/core/__tests__/integration/ai-agents.test.ts b/apps/api/src/modules/agents/core/__tests__/integration/ai-agents.test.tsindex 938c5466..c6707153 100644--- a/apps/api/src/modules/agents/core/__tests__/integration/ai-agents.test.ts+++ b/apps/api/src/modules/agents/core/__tests__/integration/ai-agents.test.ts@@ -1048,11 +1048,14 @@ describe('ai agents', () => {// An agent is set up and talked to entirely over MCP. What stays out serves the chat// UI: the streamed run and the caller's own thread history, plus this agent's run- // history — the analytics routes carry the project-wide run feed MCP reads instead.+ // history and the traces of those runs — the analytics routes carry the project-wide+ // run feed MCP reads instead.it('exposes agent management and the run to MCP', () => {const untagged = untaggedRoutes((route) => route.includes('/ai-agents'));expect(untagged).toEqual(['GET /teams/:teamId/ai-agents/:agentId/runs',+ 'GET /teams/:teamId/ai-agents/:agentId/traces',+ 'GET /teams/:teamId/ai-agents/:agentId/traces/:traceId','POST /projects/:projectKey/ai-agents/:agentId/run/stream','GET /projects/:projectKey/ai-agents/:agentId/threads','PUT /projects/:projectKey/ai-agents/:agentId/threads/:threadId/favorite',diff --git a/apps/api/src/modules/agents/core/__tests__/unit/model-pricing.test.ts b/apps/api/src/modules/agents/core/__tests__/unit/model-pricing.test.tsnew file mode 100644index 00000000..09a7e941--- /dev/null+++ b/apps/api/src/modules/agents/core/__tests__/unit/model-pricing.test.ts@@ -0,0 +1,60 @@+import { describe, expect, it } from 'bun:test';+import { estimateCost } from '#modules/agents/core/runtime/model-pricing';++// The prices come from the table @mastra/observability bundles, so these check the+// lookup and the arithmetic against a few of its rows rather than the amounts+// themselves: a model priced as given, one whose dated name only matches after the+// release date is stripped, one whose cached tokens are billed at their own rate, and+// one the table does not price.++const NO_CACHE = { cacheReadTokens: 0, cacheWriteTokens: 0 };++describe('estimateCost', () => {+ it('bills input and output at the model rates', () => {+ // openai/gpt-5-mini: 2.5e-7 in, 2e-6 out.+ const cost = estimateCost('openai', 'gpt-5-mini', {+ inputTokens: 1_000_000,+ outputTokens: 1_000_000,+ ...NO_CACHE,+ });+ expect(cost).toBeCloseTo(0.25 + 2, 6);+ });++ it('falls back to the undated name when the table prices no such release', () => {+ // anthropic/claude-3-5-haiku is priced; the dated spelling of it is not.+ const dated = estimateCost('anthropic', 'claude-3-5-haiku-20241022', {+ inputTokens: 1_000_000,+ outputTokens: 0,+ ...NO_CACHE,+ });+ expect(dated).toBeCloseTo(0.8, 6);+ });++ it('bills cached input at the cache rate and the rest at the input rate', () => {+ // anthropic/claude-sonnet-4-5: 3e-6 in, 3e-7 cache read, 3.75e-6 cache write.+ const cost = estimateCost('anthropic', 'claude-sonnet-4-5', {+ inputTokens: 1_000_000,+ outputTokens: 0,+ cacheReadTokens: 400_000,+ cacheWriteTokens: 100_000,+ });+ expect(cost).toBeCloseTo(0.5 * 3 + 0.4 * 0.3 + 0.1 * 3.75, 6);+ });++ it('picks the tier by the average call of a sum', () => {+ // google/gemini-2-5-pro: 1.25e-6 in up to 200K input tokens, 2.5e-6 above.+ const usage = { inputTokens: 1_000_000, outputTokens: 0, ...NO_CACHE };+ expect(estimateCost('google', 'gemini-2.5-pro', usage, 10)).toBeCloseTo(1.25, 6);+ expect(estimateCost('google', 'gemini-2.5-pro', usage)).toBeCloseTo(2.5, 6);+ });++ it('reports nothing for a model the table does not price', () => {+ expect(+ estimateCost('openai', 'not-a-real-model', {+ inputTokens: 1000,+ outputTokens: 1000,+ ...NO_CACHE,+ }),+ ).toBeNull();+ });+});diff --git a/apps/api/src/modules/agents/core/index.ts b/apps/api/src/modules/agents/core/index.tsindex 9541896f..1e251950 100644--- a/apps/api/src/modules/agents/core/index.ts+++ b/apps/api/src/modules/agents/core/index.ts@@ -2,12 +2,14 @@ import { Elysia, t } from 'elysia';import { noContent, sseFrame, sseResponse } from '#shared/http';import { guards } from '#shared/guards';import { authContext } from '#shared/auth-context';-import { requireUser, type TeamMembership } from '#shared/access';+import { projectsWithPermission, requireUser, type TeamMembership } from '#shared/access';import { HttpError } from '#shared/lib';import { accessErrors, commonErrors, errors } from '#shared/responses';import { mcpTool } from '#mcp/generate';import { teamParams } from '#modules/teams/model';+import { workspaceParams } from '#modules/workspaces/model';import { runsTeam } from '#modules/teams/service';+import { paginate } from '#shared/pagination';import {listAgents,createAgent,@@ -21,7 +23,11 @@ import {type AgentKind,} from './service';import {+ AgentAnalyticsResponse,+ TeamAgentAnalyticsResponse,AgentRunPageResponse,+ AgentTraceDetailResponse,+ AgentTracePageResponse,AiAgentListResponse,AiAgentResponse,ChatMessagesResponse,@@ -32,6 +38,8 @@ import {RunAgentResponse,agentListQuery,agentParams,+ analyticsQuery,+ workspaceAnalyticsQuery,createAgentBody,projectAgentParams,runBody,@@ -40,6 +48,8 @@ import {threadListQuery,threadPageQuery,threadParams,+ traceParams,+ tracesQuery,updateAgentBody,} from './model';import { runAgent, streamAgent, type AgentRunEvent, type RunOpts } from './runtime';@@ -47,6 +57,13 @@ import { peoplePreamble } from './prompt/run-context';import { attachmentPreamble, chartPreamble } from './prompt/framing';import type { SessionUser } from '#shared/auth-context';import { listAgentRuns } from './run-queue';+import { getAgentTrace, listAgentTraces } from './runtime/traces';+import {+ analyticsProjects,+ getAgentAnalytics,+ onlyProject,+ workspaceScope,+} from './runtime/analytics';import {listChatThreads,getChatThreadMessages,@@ -113,6 +130,25 @@ function threadStore(kind: AgentKind) {};}+const DEFAULT_ANALYTICS_DAYS = 30;++// Whether the caller may read the traces of that project: an owner or a manager of the+// team reads every project the agent works in, anyone else only a project they belong to+// themselves. The list names the project in the query and one trace carries it in its own+// metadata, so a trace that names none is refused to everyone else.+async function assertTraceScope(+ membership: TeamMembership,+ projectId: number | null,+): Promise<void> {+ if (runsTeam(membership.role)) return;+ const mine =+ projectId != null &&+ (await memberProjectIds(membership.teamId, membership.userId)).includes(projectId);+ if (!mine) {+ throw new HttpError(403, 'You can only read the traces of a project you are a member of');+ }+}+// The agent a :agentId path addresses, scoped by agentScopeOf — one of another team, and// one of a project the caller is not in, both read as missing.async function requireVisibleAgent(agentId: number, membership: TeamMembership) {@@ -335,6 +371,111 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A},)+ // The traces of the agent's runs: what the model and the tools were called with at+ // every step, recorded by the runtime. A run of the queue carries its runId, so the+ // run history and its trace name each other.+ .get(+ '/teams/:teamId/ai-agents/:agentId/traces',+ async ({ params, membership, query }) => {+ await requireVisibleAgent(params.agentId, membership);+ await assertTraceScope(membership, query.projectId ?? null);+ return paginate(query, (window) =>+ listAgentTraces(params.agentId, membership.userId, {+ ...window,+ projectId: query.projectId,+ }),+ );+ },+ {+ params: agentParams,+ query: tracesQuery,+ teamPermission: ['ai_agents', 'read'],+ response: { 200: AgentTracePageResponse, ...commonErrors },+ detail: {+ summary: 'List agent traces',+ description:+ "One page of the traces of an agent's runs, newest first. An owner or a manager of " ++ 'the team reads them all; anyone else names a project they belong to. A chat ' ++ 'run is read only by the member who chatted.',+ },+ },+ )++ .get(+ '/teams/:teamId/ai-agents/:agentId/traces/:traceId',+ async ({ params, membership }) => {+ await requireVisibleAgent(params.agentId, membership);+ const trace = await getAgentTrace(params.agentId, params.traceId, membership.userId);+ if (!trace) throw new HttpError(404, 'Trace not found');+ await assertTraceScope(membership, trace.trace.projectId);+ return trace;+ },+ {+ params: traceParams,+ teamPermission: ['ai_agents', 'read'],+ response: { 200: AgentTraceDetailResponse, ...commonErrors },+ detail: {+ summary: 'Read an agent trace',+ description:+ 'Every step of one trace, oldest first: the run, the model calls it made, and the ' ++ 'tools it used, each with what it was given and what it returned.',+ },+ },+ )++ .get(+ '/teams/:teamId/agent-analytics',+ async ({ membership, query }) => {+ const scope = {+ teamIds: [membership.teamId],+ projectIds: await projectsWithPermission(membership, 'agent_usage', 'read'),+ };+ const [analytics, readableProjects] = await Promise.all([+ getAgentAnalytics(+ onlyProject(scope, query.projectId),+ query.days ?? DEFAULT_ANALYTICS_DAYS,+ ),+ analyticsProjects(scope),+ ]);+ return { ...analytics, readableProjects };+ },+ {+ params: teamParams,+ query: analyticsQuery,+ teamPermission: ['agent_usage', 'read'],+ response: { 200: TeamAgentAnalyticsResponse, ...commonErrors },+ detail: {+ summary: 'Read the agent dashboard of a team',+ description:+ 'Runs, tokens and model cost of the agents of the team, over the last `days` days ' ++ 'beside the same span before it. An owner or a manager of the team reads every ' ++ 'project; anyone else the projects where their role grants agent_usage read. ' ++ '`projectId` narrows it to one of them.',+ },+ },+ )++ .get(+ '/workspaces/:workspaceId/agent-analytics',+ async ({ standing, query }) =>+ getAgentAnalytics(+ await workspaceScope(standing.workspaceId),+ query.days ?? DEFAULT_ANALYTICS_DAYS,+ ),+ {+ workspaceManager: true,+ params: workspaceParams,+ query: workspaceAnalyticsQuery,+ response: { 200: AgentAnalyticsResponse, ...errors(400, 401, 404) },+ detail: {+ summary: 'Read the agent dashboard of a workspace',+ description:+ 'The agent dashboard over every team of a workspace you manage, with the teams ' ++ 'compared in `teams`.',+ },+ },+ )+.delete('/teams/:teamId/ai-agents/:agentId',async ({ params, membership }) => {diff --git a/apps/api/src/modules/agents/core/model.ts b/apps/api/src/modules/agents/core/model.tsindex 8d8d90b8..3ef769c3 100644--- a/apps/api/src/modules/agents/core/model.ts+++ b/apps/api/src/modules/agents/core/model.ts@@ -1,5 +1,6 @@import { t } from 'elysia';+import { pageQueryFields, pageResponse } from '#shared/pagination';import { agentRunTrigger, runContextTokens } from '../model';export { agentParams, projectAgentParams } from '../model';@@ -317,3 +318,116 @@ export const threadListQuery = t.Object({t.Boolean({ description: 'Return the starred conversations instead of the page.' }),),});++// The trace of one run of an internal agent (TraceSummary from runtime/traces).+export const AgentTraceResponse = t.Object({+ traceId: t.String(),+ name: t.String(),+ status: t.String({ description: "How the run ended: 'success', 'error' or 'running'." }),+ startedAt: t.String(),+ endedAt: t.Nullable(t.String()),+ durationMs: t.Nullable(t.Number()),+ projectId: t.Nullable(t.Number()),+ runId: t.Nullable(+ t.Number({+ description:+ 'The queued run this traced, as listed by the run history. Null for a trace of the ' ++ 'chat, which is queued nowhere.',+ }),+ ),+ trigger: t.Nullable(agentRunTrigger),+ issueId: t.Nullable(t.Number()),+});++export const AgentTracePageResponse = pageResponse(AgentTraceResponse);++// One step of a trace: the run itself, a model call, or a tool call (TraceSpan).+export const AgentTraceSpanResponse = t.Object({+ spanId: t.String(),+ parentSpanId: t.Nullable(t.String()),+ name: t.String(),+ type: t.String({+ description:+ "Mastra's span type: 'agent_run' for the run, 'model_generation' and its " ++ "'model_step' and 'model_inference' spans for the model, 'tool_call' for a tool.",+ }),+ status: t.String(),+ startedAt: t.String(),+ endedAt: t.Nullable(t.String()),+ durationMs: t.Nullable(t.Number()),+ input: t.Any(),+ output: t.Any(),+ error: t.Any(),+ attributes: t.Any({+ description:+ 'What the step itself reports: the model and its token counts for a model call, the ' ++ 'arguments for a tool call.',+ }),+});++export const AgentTraceDetailResponse = t.Object({+ trace: AgentTraceResponse,+ spans: t.Array(AgentTraceSpanResponse),+});++export const tracesQuery = t.Object({+ projectId: t.Optional(t.Numeric()),+ ...pageQueryFields,+});++export const traceParams = t.Object({+ teamId: t.Numeric(),+ agentId: t.Numeric(),+ traceId: t.String(),+});++// --- Agent analytics -------------------------------------------------------------++// Cost is in USD, and null where the price table names no such provider and model —+// the panel shows the tokens without an amount rather than a wrong one.+const usageFields = {+ inputTokens: t.Number(),+ outputTokens: t.Number(),+ cost: t.Nullable(t.Number()),+};++const totalsFields = { runs: t.Number(), errors: t.Number(), ...usageFields };++const AgentAnalyticsTotals = t.Object(totalsFields);++export const AgentAnalyticsResponse = t.Object({+ from: t.String(),+ to: t.String(),+ totals: AgentAnalyticsTotals,+ previous: AgentAnalyticsTotals,+ models: t.Array(+ t.Object({ provider: t.String(), model: t.String(), calls: t.Number(), ...usageFields }),+ ),+ agents: t.Array(t.Object({ agentId: t.Number(), name: t.String(), ...totalsFields })),+ projects: t.Array(t.Object({ projectId: t.Number(), name: t.String(), ...totalsFields })),+ teams: t.Array(t.Object({ teamId: t.Number(), name: t.String(), ...totalsFields })),+ tokensPerDay: t.Array(t.Object({ day: t.String(), ...usageFields })),+});++export const TeamAgentAnalyticsResponse = t.Composite([+ AgentAnalyticsResponse,+ t.Object({+ readableProjects: t.Array(t.Object({ projectId: t.Number(), name: t.String() }), {+ description:+ 'The projects of the team the caller reads the figures of: what `projectId` takes.',+ }),+ }),+]);++// The window, in days back from now. The same number of days before it is read as+// well, which is what every headline figure is compared against.+const analyticsDays = t.Optional(t.Numeric({ minimum: 1, maximum: 365 }));++export const workspaceAnalyticsQuery = t.Object({ days: analyticsDays });++export const analyticsQuery = t.Object({+ days: analyticsDays,+ projectId: t.Optional(+ t.Numeric({ description: 'Narrows the figures to one project of the team.' }),+ ),+});diff --git a/apps/api/src/modules/agents/core/run-poller.ts b/apps/api/src/modules/agents/core/run-poller.tsindex cb584401..1dfa06f4 100644--- a/apps/api/src/modules/agents/core/run-poller.ts+++ b/apps/api/src/modules/agents/core/run-poller.ts@@ -55,6 +55,8 @@ async function processRun(run: ClaimedRun): Promise<void> {threadId: runThreadId(run),issueId: run.issueId,scheduleId: run.scheduleId,+ runId: run.id,+ trigger: run.trigger,contextPreamble: runModePreamble(run.trigger) + peopleContext(run),abortSignal: AbortSignal.timeout(timeoutMs),});diff --git a/apps/api/src/modules/agents/core/runtime/analytics.ts b/apps/api/src/modules/agents/core/runtime/analytics.tsnew file mode 100644index 00000000..89257cce--- /dev/null+++ b/apps/api/src/modules/agents/core/runtime/analytics.ts@@ -0,0 +1,356 @@+import { db, aiAgent, project, team, user } from '@repo/db';+import { and, eq, inArray, sql, type SQL } from 'drizzle-orm';+import { iso, num } from '#shared/lib';+import { spansTableExists } from './store';+import { estimateCost, type CallUsage } from './model-pricing';++// The figures behind the agent dashboard, read from the traces the runtime records+// (see observability.ts). One trace is one run: its root span carries the team, the+// agent and the project in metadata, and below it is a `model_inference` span for every+// call the run made to a model, with the provider, the model and the token counts. The+// spans hold no foreign keys of ours, so everything is scoped through that metadata and+// the names are read separately.+//+// The scope is a list of teams: one team, or every team of a workspace. `projectIds`+// narrows it to those projects, for a member who may read only some. The window is+// asked for in days and always read twice: the period itself and the one before it, so+// every headline figure carries what it moved from. Both come back in a single pass over+// the spans, grouped by the bucket each row falls in — an hour for a window of a day, a+// day for anything longer — and split by when the row itself started, since the first+// bucket of a window starts before the window does.+//+// Traces are deleted once past the retention window, so a window longer than the+// retention shows only what is still stored.++// What a group of model calls read, wrote and cost. `cost` is null until a call of the+// group could be priced: the price table names no such provider and model.+interface Usage {+ inputTokens: number;+ outputTokens: number;+ cost: number | null;+}++export interface AgentAnalyticsTotals extends Usage {+ runs: number;+ errors: number;+}++export interface AgentAnalytics {+ from: string;+ to: string;+ totals: AgentAnalyticsTotals;+ previous: AgentAnalyticsTotals;+ models: (Usage & { provider: string; model: string; calls: number })[];+ agents: (AgentAnalyticsTotals & { agentId: number; name: string })[];+ projects: (AgentAnalyticsTotals & { projectId: number; name: string })[];+ teams: (AgentAnalyticsTotals & { teamId: number; name: string })[];+ tokensPerDay: (Usage & { day: string })[];+}++// The period a dashboard reads and the one before it. A window of a day is grouped by+// the hour, since by the day its chart would hold one or two points.+export interface AnalyticsWindow {+ from: Date;+ to: Date;+ previousFrom: Date;+ bucket: 'hour' | 'day';+}++export interface AnalyticsScope {+ teamIds: number[];+ projectIds?: number[] | null;+}++// Whether the scope reads nothing at all, which no query is sent for.+function emptyScope(scope: AnalyticsScope): boolean {+ return scope.teamIds.length === 0 || scope.projectIds?.length === 0;+}++export async function workspaceScope(workspaceId: number): Promise<AnalyticsScope> {+ const rows = await db.select({ id: team.id }).from(team).where(eq(team.workspaceId, workspaceId));+ return { teamIds: rows.map((row) => row.id) };+}++// The scope narrowed to one project, when one is asked for. A project it does not read+// leaves it reading nothing.+export function onlyProject(scope: AnalyticsScope, projectId?: number): AnalyticsScope {+ if (projectId == null) return scope;+ const readable = !scope.projectIds || scope.projectIds.includes(projectId);+ return { ...scope, projectIds: readable ? [projectId] : [] };+}++// The projects the scope reads, by name: what it may be narrowed to.+export async function analyticsProjects(+ scope: AnalyticsScope,+): Promise<{ projectId: number; name: string }[]> {+ if (emptyScope(scope)) return [];+ return db+ .select({ projectId: project.id, name: project.name })+ .from(project)+ .where(+ and(+ inArray(project.teamId, scope.teamIds),+ scope.projectIds ? inArray(project.id, scope.projectIds) : undefined,+ ),+ )+ .orderBy(project.name);+}++export function analyticsWindow(days: number): AnalyticsWindow {+ const bucket = days <= 1 ? 'hour' : 'day';+ const to = new Date();+ const windowMs = days * 24 * 60 * 60 * 1000;+ const from = new Date(to.getTime() - windowMs);+ return { from, to, previousFrom: new Date(from.getTime() - windowMs), bucket };+}++// The runs of the scope since `from`, one row per trace, as a statement to put in a+// WITH clause. `metadata` is the whole of what the run carried, for a reader that+// groups by more of it; its `runId` is ours on a queued run and Mastra's own UUID on a+// chat run. A team id that is not a number is left out rather than cast, inside a CASE+// since Postgres does not evaluate the conditions of an AND in order. The bound is+// passed as text and cast in the statement: the driver binds no Date inside a composed+// fragment.+export function tracedRuns(scope: AnalyticsScope, from: Date): SQL {+ const ids = (list: number[]) =>+ sql.join(+ list.map((id) => sql`${id}`),+ sql`, `,+ );+ const teamId = sql`CASE WHEN r.metadata->>'teamId' ~ '^[0-9]+$'+ THEN (r.metadata->>'teamId')::int END`;+ const projects = scope.projectIds+ ? sql` AND CASE WHEN r.metadata->>'projectId' ~ '^[0-9]+$'+ THEN (r.metadata->>'projectId')::int END IN (${ids(scope.projectIds)})`+ : sql``;+ return sql`+ SELECT r."traceId" AS trace_id,+ ${teamId} AS team_id,+ (r.metadata->>'agentId')::int AS agent_id,+ (r.metadata->>'projectId')::int AS project_id,+ r."startedAtZ" AS started_at,+ r."endedAtZ" AS ended_at,+ (r.error IS NOT NULL) AS failed,+ r.metadata AS metadata+ FROM mastra_ai_spans r+ WHERE r."parentSpanId" IS NULL+ AND ${teamId} IN (${ids(scope.teamIds)})+ AND r."startedAtZ" >= ${from.toISOString()}::timestamptz${projects}+ `;+}++// The raw driver hands a timestamp back as text.+function dayOf(value: unknown): Date {+ return value instanceof Date ? value : new Date(String(value));+}++// One row per bucket, period, team, agent, project and model: the model calls the runs+// of that bucket made. Fine enough to fold into every panel, and coarse enough that a long+// window stays a few hundred rows. A project belongs to one team, so the team adds no+// rows of its own. The token sums are bigint, which the driver hands back as a string.+type CallRow = {+ day: unknown;+ in_window: boolean;+ team_id: number | null;+ agent_id: number | null;+ project_id: number | null;+ provider: string | null;+ model: string | null;+ calls: number;+ input_tokens: unknown;+ output_tokens: unknown;+ cache_read: unknown;+ cache_write: unknown;+};++async function modelCalls(scope: AnalyticsScope, window: AnalyticsWindow): Promise<CallRow[]> {+ const rows = await db.execute(sql`+ WITH runs AS (${tracedRuns(scope, window.previousFrom)})+ SELECT date_trunc(${window.bucket}::text, s."startedAtZ") AS day,+ s."startedAtZ" >= ${window.from.toISOString()}::timestamptz AS in_window,+ runs.team_id,+ runs.agent_id,+ runs.project_id,+ s.attributes->>'provider' AS provider,+ s.attributes->>'model' AS model,+ count(*)::int AS calls,+ coalesce(sum((s.attributes->'usage'->>'inputTokens')::bigint), 0) AS input_tokens,+ coalesce(sum((s.attributes->'usage'->>'outputTokens')::bigint), 0) AS output_tokens,+ coalesce(sum((s.attributes->'usage'->'inputDetails'->>'cacheRead')::bigint), 0)+ AS cache_read,+ coalesce(sum((s.attributes->'usage'->'inputDetails'->>'cacheWrite')::bigint), 0)+ AS cache_write+ FROM mastra_ai_spans s+ JOIN runs ON runs.trace_id = s."traceId"+ WHERE s."spanType" = 'model_inference'+ GROUP BY 1, 2, 3, 4, 5, 6, 7+ `);+ return rows as unknown as CallRow[];+}++type RunRow = {+ in_window: boolean;+ team_id: number | null;+ agent_id: number | null;+ project_id: number | null;+ runs: number;+ errors: number;+};++async function runsPerPeriod(scope: AnalyticsScope, window: AnalyticsWindow): Promise<RunRow[]> {+ const rows = await db.execute(sql`+ WITH runs AS (${tracedRuns(scope, window.previousFrom)})+ SELECT started_at >= ${window.from.toISOString()}::timestamptz AS in_window,+ team_id,+ agent_id,+ project_id,+ count(*)::int AS runs,+ count(*) FILTER (WHERE failed)::int AS errors+ FROM runs+ GROUP BY 1, 2, 3, 4+ `);+ return rows as unknown as RunRow[];+}++function callUsage(row: CallRow): CallUsage {+ return {+ inputTokens: num(row.input_tokens),+ outputTokens: num(row.output_tokens),+ cacheReadTokens: num(row.cache_read),+ cacheWriteTokens: num(row.cache_write),+ };+}++function emptyUsage(): Usage {+ return { inputTokens: 0, outputTokens: 0, cost: null };+}++function emptyTotals(): AgentAnalyticsTotals {+ return { runs: 0, errors: 0, ...emptyUsage() };+}++function addUsage(entry: Usage, usage: CallUsage, cost: number | null): void {+ entry.inputTokens += usage.inputTokens;+ entry.outputTokens += usage.outputTokens;+ if (cost != null) entry.cost = (entry.cost ?? 0) + cost;+}++function addRuns(entry: AgentAnalyticsTotals, row: RunRow): void {+ entry.runs += row.runs;+ entry.errors += row.errors;+}++function entryOf<K, V>(map: Map<K, V>, key: K, init: () => V): V {+ let entry = map.get(key);+ if (!entry) {+ entry = init();+ map.set(key, entry);+ }+ return entry;+}++const tokensOf = (entry: Usage) => entry.inputTokens + entry.outputTokens;+const byTokens = (a: Usage, b: Usage) => tokensOf(b) - tokensOf(a);++export async function getAgentAnalytics(+ scope: AnalyticsScope,+ days: number,+): Promise<AgentAnalytics> {+ const window = analyticsWindow(days);+ const totals = emptyTotals();+ const previous = emptyTotals();+ const result: AgentAnalytics = {+ from: iso(window.from),+ to: iso(window.to),+ totals,+ previous,+ models: [],+ agents: [],+ projects: [],+ teams: [],+ tokensPerDay: [],+ };+ if (emptyScope(scope) || !(await spansTableExists())) return result;++ const [calls, runs, agentRows, projectRows, teamRows] = await Promise.all([+ modelCalls(scope, window),+ runsPerPeriod(scope, window),+ db+ .select({ id: aiAgent.id, name: user.name })+ .from(aiAgent)+ .innerJoin(user, eq(user.id, aiAgent.userId))+ .where(inArray(aiAgent.teamId, scope.teamIds)),+ db+ .select({ id: project.id, name: project.name })+ .from(project)+ .where(inArray(project.teamId, scope.teamIds)),+ db.select({ id: team.id, name: team.name }).from(team).where(inArray(team.id, scope.teamIds)),+ ]);++ const agentNames = new Map(agentRows.map((row) => [row.id, row.name]));+ const projectNames = new Map(projectRows.map((row) => [row.id, row.name]));+ const teamNames = new Map(teamRows.map((row) => [row.id, row.name]));+ const byModel = new Map<string, AgentAnalytics['models'][number]>();+ const byAgent = new Map<number, AgentAnalytics['agents'][number]>();+ const byProject = new Map<number, AgentAnalytics['projects'][number]>();+ const byTeam = new Map<number, AgentAnalytics['teams'][number]>();+ const byDay = new Map<string, AgentAnalytics['tokensPerDay'][number]>();+ // A deleted agent or project keeps its figures under an empty name.+ const agentEntry = (id: number) =>+ entryOf(byAgent, id, () => ({ agentId: id, name: agentNames.get(id) ?? '', ...emptyTotals() }));+ const projectEntry = (id: number) =>+ entryOf(byProject, id, () => ({+ projectId: id,+ name: projectNames.get(id) ?? '',+ ...emptyTotals(),+ }));+ const teamEntry = (id: number) =>+ entryOf(byTeam, id, () => ({ teamId: id, name: teamNames.get(id) ?? '', ...emptyTotals() }));++ for (const row of calls) {+ const usage = callUsage(row);+ const provider = row.provider ?? '';+ const model = row.model ?? '';+ const cost = provider && model ? estimateCost(provider, model, usage, row.calls) : null;+ if (!row.in_window) {+ addUsage(previous, usage, cost);+ continue;+ }+ addUsage(totals, usage, cost);+ const modelEntry = entryOf(byModel, `${provider}/${model}`, () => ({+ provider,+ model,+ calls: 0,+ ...emptyUsage(),+ }));+ modelEntry.calls += row.calls;+ addUsage(modelEntry, usage, cost);+ if (row.agent_id != null) addUsage(agentEntry(row.agent_id), usage, cost);+ if (row.project_id != null) addUsage(projectEntry(row.project_id), usage, cost);+ if (row.team_id != null) addUsage(teamEntry(row.team_id), usage, cost);+ const key = iso(dayOf(row.day));+ addUsage(+ entryOf(byDay, key, () => ({ day: key, ...emptyUsage() })),+ usage,+ cost,+ );+ }++ for (const row of runs) {+ if (!row.in_window) {+ addRuns(previous, row);+ continue;+ }+ addRuns(totals, row);+ if (row.agent_id != null) addRuns(agentEntry(row.agent_id), row);+ if (row.project_id != null) addRuns(projectEntry(row.project_id), row);+ if (row.team_id != null) addRuns(teamEntry(row.team_id), row);+ }++ result.models = [...byModel.values()].sort(byTokens);+ result.agents = [...byAgent.values()].sort(byTokens);+ result.projects = [...byProject.values()].sort(byTokens);+ result.teams = [...byTeam.values()].sort(byTokens);+ result.tokensPerDay = [...byDay.values()].sort((a, b) => a.day.localeCompare(b.day));+ return result;+}diff --git a/apps/api/src/modules/agents/core/runtime/index.ts b/apps/api/src/modules/agents/core/runtime/index.tsindex 99a1cc00..19eb0171 100644--- a/apps/api/src/modules/agents/core/runtime/index.ts+++ b/apps/api/src/modules/agents/core/runtime/index.ts@@ -1,5 +1,6 @@import { randomUUID } from 'node:crypto';import { Agent, type AgentExecutionOptions } from '@mastra/core/agent';+import type { TracingOptions } from '@mastra/core/observability';import {getAgentInProject,getInternalAgentApiKey,@@ -15,12 +16,14 @@ import { buildRouteTools } from './tools/route-tools';import { buildLocalTools } from './tools/local';import { buildSkillTool, skillsPreamble } from './skill-runtime';import { buildMemory, ensureThread, DEFAULT_LAST_MESSAGES } from './memory';+import { getMastra } from './observability';import { toolArgsText, toolText } from '../../chat-parts';import { recordContextUsage, type ContextUsage } from '../../chat-usage';import { isChatThreadId, newChatThreadId } from './thread-ids';import { errorMessage } from '../helpers/errors';import { projectPreamble } from '../prompt/framing';import { HttpError } from '#shared/lib';+import type { AgentRunTrigger } from '../../model';// Runtime execution of internal agents via Mastra. An agent is built on demand// from its stored configuration (provider/model/instructions) and run against a@@ -121,7 +124,7 @@ async function buildAgent(contextPreamble +(row.instructions ?? DEFAULT_INSTRUCTIONS) +skillsPreamble(skills);- return new Agent({+ const agent = new Agent({id: `ai-agent-${row.id}`,name: row.name,instructions,@@ -141,6 +144,9 @@ async function buildAgent(? { memory: buildMemory(row.memoryLastMessages ?? DEFAULT_LAST_MESSAGES) }: {}),});+ // An agent traces its run only through a container (see observability.ts).+ agent.__registerMastra(getMastra());+ return agent;}// Runs the internal agent identified by agentId in the given project against the@@ -301,7 +307,24 @@ async function prepareRun(// Mastra's generate/stream have overloaded options; type the shape we use. In// Mastra v1 the temperature belongs to the call's model settings — a flat// `temperature` option is only read by the legacy generate.- const options: RunOptions = { maxSteps: row.maxSteps ?? DEFAULT_MAX_STEPS };+ const options: RunOptions = {+ maxSteps: row.maxSteps ?? DEFAULT_MAX_STEPS,+ // What the run belongs to, kept on the trace: the spans hold no foreign keys of ours.+ // A queued run names its run, a chat run the person who asked, since the caller of a+ // queued run is the agent's own bot user.+ tracingOptions: {+ metadata: {+ agentId: row.id,+ teamId: row.teamId,+ projectId,+ ...(opts.runId != null+ ? { runId: opts.runId, trigger: opts.trigger }+ : { userId: opts.callerUserId }),+ ...(opts.issueId != null ? { issueId: opts.issueId } : {}),+ ...(opts.scheduleId != null ? { scheduleId: opts.scheduleId } : {}),+ },+ },+ };if (row.temperature != null) options.modelSettings = { temperature: row.temperature };if (row.reasoningEffort != null) {options.providerOptions = reasoningProviderOptions(row.reasoningEffort);@@ -340,11 +363,15 @@ export type RunOpts = {threadId?: string | null;issueId?: number | null;scheduleId?: number | null;+ // The queued run this executes, and what triggered it. Absent for a chat run.+ runId?: number;+ trigger?: AgentRunTrigger;contextPreamble?: string;};type RunOptions = {maxSteps: number;+ tracingOptions: TracingOptions;modelSettings?: { temperature: number };providerOptions?: ProviderOptions;memory?: { thread: string; resource: string };diff --git a/apps/api/src/modules/agents/core/runtime/memory.ts b/apps/api/src/modules/agents/core/runtime/memory.tsindex e74bc6d5..2d99678d 100644--- a/apps/api/src/modules/agents/core/runtime/memory.ts+++ b/apps/api/src/modules/agents/core/runtime/memory.ts@@ -1,5 +1,4 @@import { Memory } from '@mastra/memory';-import { PostgresStore } from '@mastra/pg';import { db } from '@repo/db';import { sql } from 'drizzle-orm';import { appendTextPart, toolArgsText, toolText } from '../../chat-parts';@@ -19,6 +18,7 @@ import {type ThreadRow,} from '../../chat-history';import { toIso } from '../helpers/dates';+import { getStore } from './store';import type { ChatMessageDTO, ChatMessagePage, ChatPart, ChatThreadPage } from '../../model';// Conversation memory for internal agents. Threads and their messages are@@ -43,17 +43,6 @@ const THREAD_PAGE_SIZE = 25;// typed.const TITLE_LIMIT = 80;-let store: PostgresStore | null = null;--function getStore(): PostgresStore {- if (!store) {- const url = process.env.DATABASE_URL;- if (!url) throw new Error('DATABASE_URL is required for agent memory');- store = new PostgresStore({ id: 'ai-agent-memory', connectionString: url });- }- return store;-}-export function buildMemory(lastMessages: number): Memory {return new Memory({storage: getStore(),diff --git a/apps/api/src/modules/agents/core/runtime/model-pricing.ts b/apps/api/src/modules/agents/core/runtime/model-pricing.tsnew file mode 100644index 00000000..a6a90267--- /dev/null+++ b/apps/api/src/modules/agents/core/runtime/model-pricing.ts@@ -0,0 +1,157 @@+import { createRequire } from 'node:module';+import { readFileSync } from 'node:fs';+import path from 'node:path';++// What a model call costs, in USD, from the token counts its span reports.+//+// The prices are the table @mastra/observability bundles for its own cost metrics+// (`dist/metrics/pricing-data.jsonl`, one row per provider and model). Those metrics need+// an analytics store its Postgres adapter does not implement, so the spans reach us+// carrying raw token counts and the price is applied here instead. The provider ids+// are the same registry our AI_PROVIDERS list comes from, so a credential's+// integration key matches the table directly.+//+// The file is not in the package's exports map, so a release that moves it leaves the+// table empty rather than failing the request: an unpriced call reports no cost, and+// the dashboard shows its tokens without one.++// The prices of one provider/model pair. Rates are USD per token, keyed by the+// meter the tokens are billed under; a tier applies once its conditions hold.+interface Rate {+ c: number;+}++// Only the total input token count ('tit') is used as a condition in the table.+type Condition = { f: string; op: string; value: number };++interface Tier {+ w?: Condition[];+ r: Record<string, Rate | undefined>;+}++interface PricingRow {+ p: string;+ m: string;+ s: { d: { u: string; t: Tier[] } };+}++// The token counts of one model call, as the span's `usage` attribute reports them.+// inputTokens is the whole input, cached tokens included, so the tokens billed at the+// plain input rate are what is left after the cache counts are taken out.+export interface CallUsage {+ inputTokens: number;+ outputTokens: number;+ cacheReadTokens: number;+ cacheWriteTokens: number;+}++let table: Map<string, Tier[]> | null = null;++function pricingPath(): string {+ const packageJson = createRequire(import.meta.url).resolve('@mastra/observability/package.json');+ return path.join(path.dirname(packageJson), 'dist', 'metrics', 'pricing-data.jsonl');+}++function key(provider: string, model: string): string {+ return `${provider.trim().toLowerCase()}::${model.trim().toLowerCase()}`;+}++function load(): Map<string, Tier[]> {+ const loaded = new Map<string, Tier[]>();+ try {+ for (const line of readFileSync(pricingPath(), 'utf-8').split('\n')) {+ if (!line.trim()) continue;+ const row = JSON.parse(line) as PricingRow;+ loaded.set(key(row.p, row.m), row.s.d.t);+ }+ } catch (error) {+ console.error('[agent-analytics] model prices unavailable:', error);+ }+ return loaded;+}++// A model id as the table may spell it: as reported, with dots normalized to dashes,+// and each of those without the release date providers append.+function modelVariants(model: string): string[] {+ const out = new Set<string>();+ for (const base of [model, model.replace(/\./g, '-')]) {+ out.add(base);+ out.add(+ base+ .replace(/@20\d{6}$/, '')+ .replace(/-20\d{2}-\d{2}-\d{2}$/, '')+ .replace(/-20\d{6}(-[a-z]+)?$/, '$1'),+ );+ }+ return [...out];+}++function tiersFor(provider: string, model: string): Tier[] | null {+ if (!table) table = load();+ for (const variant of modelVariants(model)) {+ const tiers = table.get(key(provider, variant));+ if (tiers) return tiers;+ }+ return null;+}++function holds(condition: Condition, inputTokens: number): boolean {+ if (condition.f !== 'tit') return false;+ switch (condition.op) {+ case 'gt':+ return inputTokens > condition.value;+ case 'gte':+ return inputTokens >= condition.value;+ case 'lt':+ return inputTokens < condition.value;+ case 'lte':+ return inputTokens <= condition.value;+ case 'eq':+ return inputTokens === condition.value;+ case 'neq':+ return inputTokens !== condition.value;+ default:+ return false;+ }+}++// The first tier whose conditions hold, or the base tier, which carries none.+function tierFor(tiers: Tier[], inputTokens: number): Tier | null {+ for (const tier of tiers) {+ if (tier.w?.length && tier.w.every((condition) => holds(condition, inputTokens))) return tier;+ }+ return tiers[0] ?? null;+}++// What model calls cost, or null when the table prices no such model. `usage` is the sum+// of `calls` calls; a tier is chosen by the input of one call, so a sum is priced at the+// tier of its average call. Cached reads and writes are billed at their own rates where+// the model has them, and at the plain input rate where it does not.+// ponytail: calls of very different sizes in one sum share a tier; pricing each call+// would need one row per call.+export function estimateCost(+ provider: string,+ model: string,+ usage: CallUsage,+ calls = 1,+): number | null {+ const tiers = tiersFor(provider, model);+ if (!tiers) return null;+ const tier = tierFor(tiers, usage.inputTokens / Math.max(calls, 1));+ const input = tier?.r.it?.c;+ const output = tier?.r.ot?.c;+ if (!tier || input == null || output == null) return null;++ const cacheRead = tier.r.icrt?.c ?? input;+ const cacheWrite = tier.r.icwt?.c ?? input;+ const plainInput = Math.max(+ 0,+ usage.inputTokens - usage.cacheReadTokens - usage.cacheWriteTokens,+ );+ return (+ plainInput * input ++ usage.cacheReadTokens * cacheRead ++ usage.cacheWriteTokens * cacheWrite ++ usage.outputTokens * output+ );+}diff --git a/apps/api/src/modules/agents/core/runtime/observability.ts b/apps/api/src/modules/agents/core/runtime/observability.tsnew file mode 100644index 00000000..da79e087--- /dev/null+++ b/apps/api/src/modules/agents/core/runtime/observability.ts@@ -0,0 +1,31 @@+import { Mastra } from '@mastra/core';+import { MastraStorageExporter, Observability } from '@mastra/observability';+import { getStore } from './store';++// Tracing of internal agent runs. Mastra emits a span for the run and one for every+// model call and tool call inside it, but only through a Mastra container: an agent+// built on its own writes nothing. So every agent a run builds is registered with the+// single container held here, which carries the exporter that writes the spans into+// the store (Mastra's own `mastra_ai_spans` table, on the application database).+//+// Nothing else of the container is used: the agents are built per run from their+// stored configuration, so none is registered as a named agent of it.++let mastra: Mastra | null = null;++export function getMastra(): Mastra {+ if (!mastra) {+ mastra = new Mastra({+ storage: getStore(),+ observability: new Observability({+ configs: {+ default: {+ serviceName: 'itsaplan-agents',+ exporters: [new MastraStorageExporter()],+ },+ },+ }),+ });+ }+ return mastra;+}diff --git a/apps/api/src/modules/agents/core/runtime/store.ts b/apps/api/src/modules/agents/core/runtime/store.tsnew file mode 100644index 00000000..7bbc489a--- /dev/null+++ b/apps/api/src/modules/agents/core/runtime/store.ts@@ -0,0 +1,27 @@+import { PostgresStore } from '@mastra/pg';+import { db } from '@repo/db';+import { sql } from 'drizzle-orm';++// The Postgres store Mastra keeps its own tables in, on the application database.+// Two things write to it: conversation memory (threads and messages, see memory.ts)+// and the traces of agent runs (see observability.ts).++let store: PostgresStore | null = null;++export function getStore(): PostgresStore {+ if (!store) {+ const url = process.env.DATABASE_URL;+ if (!url) throw new Error('DATABASE_URL is required for the agent store');+ store = new PostgresStore({ id: 'ai-agent-memory', connectionString: url });+ }+ return store;+}++// Mastra creates its tables on first use, so an instance whose agents have never run+// has none of them yet. Everything that reads the spans directly checks this first.+export async function spansTableExists(): Promise<boolean> {+ const rows = await db.execute<{ exists: boolean }>(+ sql`SELECT to_regclass('public.mastra_ai_spans') IS NOT NULL AS exists`,+ );+ return rows[0]?.exists === true;+}diff --git a/apps/api/src/modules/agents/core/runtime/trace-retention.ts b/apps/api/src/modules/agents/core/runtime/trace-retention.tsnew file mode 100644index 00000000..3f4a9954--- /dev/null+++ b/apps/api/src/modules/agents/core/runtime/trace-retention.ts@@ -0,0 +1,60 @@+import { db, team } from '@repo/db';+import { sql, type SQL } from 'drizzle-orm';+import { getAgentSettings } from '#modules/settings/service';+import { spansTableExists } from './store';++// The sweep that drops old run traces, run by the api's background loop. The window is+// the instance setting; 0 days keeps every trace.+//+// A window applies to a run, not to each of its spans: the sweep finds the root spans+// past it and deletes every span of their traces, so a trace is never left half removed.++// Traces deleted per statement, which bounds how long one delete holds its locks.+const BATCH = 200;+// Batches one sweep runs per condition before it leaves the rest to the next one.+const MAX_BATCHES = 50;++async function deleteBatch(where: SQL): Promise<number> {+ const res = await db.execute(sql`+ DELETE FROM mastra_ai_spans+ WHERE "traceId" IN (+ SELECT "traceId" FROM mastra_ai_spans+ WHERE "parentSpanId" IS NULL AND (${where})+ LIMIT ${BATCH}+ )+ `);+ return (res as unknown as { count?: number }).count ?? 0;+}++async function deleteUntilDone(where: SQL): Promise<number> {+ let deleted = 0;+ for (let batch = 0; batch < MAX_BATCHES; batch++) {+ const rows = await deleteBatch(where);+ deleted += rows;+ if (rows === 0) break;+ }+ return deleted;+}++// The team id a trace carries, as an integer. The metadata is a jsonb value like any+// other, so a value that is not a number is left for the orphan sweep rather than cast.+const traceTeamId = sql`(CASE WHEN metadata->>'teamId' ~ '^[0-9]+$' THEN (metadata->>'teamId')::int END)`;++// Deletes every trace past the window and every trace whose team is gone. Returns how+// many spans it removed.+export async function pruneAgentTraces(): Promise<number> {+ if (!(await spansTableExists())) return 0;+ const { traceRetentionDays } = await getAgentSettings();+ let deleted = 0;+ if (traceRetentionDays > 0) {+ deleted += await deleteUntilDone(+ sql`"startedAtZ" < now() - make_interval(days => ${traceRetentionDays})`,+ );+ }+ // A deleted team takes its agents and its runs with it, but the spans carry no foreign+ // keys of ours, so its traces are left behind for this.+ deleted += await deleteUntilDone(+ sql`${traceTeamId} IS NULL OR ${traceTeamId} NOT IN (SELECT id FROM ${team})`,+ );+ return deleted;+}diff --git a/apps/api/src/modules/agents/core/runtime/traces.ts b/apps/api/src/modules/agents/core/runtime/traces.tsnew file mode 100644index 00000000..67fb57f1--- /dev/null+++ b/apps/api/src/modules/agents/core/runtime/traces.ts@@ -0,0 +1,166 @@+import { db } from '@repo/db';+import { sql } from 'drizzle-orm';+import { getStore } from './store';+import { toIso } from '../helpers/dates';+import type { AgentRunTrigger } from '../../model';++// Read side of the traces observability.ts writes: one trace per run of an internal+// agent, holding a span for the run and one for every model call and tool call inside+// it. The spans are Mastra's own rows and carry no foreign keys of ours, so a trace is+// found by the metadata the run put on it (see prepareRun in index.ts) — the store+// indexes that metadata, so filtering on it is a lookup, not a scan.++// The trace of one run, as the list shows it.+export interface TraceSummary {+ traceId: string;+ name: string;+ status: string;+ startedAt: string;+ endedAt: string | null;+ durationMs: number | null;+ projectId: number | null;+ // The queued run this traced, and what triggered it. Null for a trace of the test+ // chat, which is queued nowhere.+ runId: number | null;+ trigger: AgentRunTrigger | null;+ issueId: number | null;+}++// One step of a trace: the run itself, a model call, or a tool call.+export interface TraceSpan {+ spanId: string;+ parentSpanId: string | null;+ name: string;+ type: string;+ status: string;+ startedAt: string;+ endedAt: string | null;+ durationMs: number | null;+ input: unknown;+ output: unknown;+ error: unknown;+ // What the span itself reports: the model and its token counts for a model call,+ // the arguments for a tool call.+ attributes: unknown;+}++async function traceStore() {+ // Mastra creates its tables on an agent's first run; init creates them on an instance+ // whose agents never ran, and returns at once after the first call.+ await getStore().init();+ const store = await getStore().getStore('observability');+ if (!store) throw new Error('The agent store keeps no traces');+ return store;+}++function numberOf(value: unknown): number | null {+ return typeof value === 'number' ? value : null;+}++function timeOf(value: Date | string): number {+ return new Date(toIso(value)).getTime();+}++function durationOf(startedAt: Date | string, endedAt: Date | string | null | undefined) {+ return endedAt == null ? null : timeOf(endedAt) - timeOf(startedAt);+}++type SpanRow = {+ traceId: string;+ spanId: string;+ parentSpanId?: string | null;+ name: string;+ spanType: string;+ status?: string | null;+ startedAt: Date | string;+ endedAt?: Date | string | null;+ error?: unknown;+ metadata?: Record<string, unknown> | null;+};++// A span of the trace list carries a status Mastra computed; a span read through+// getTrace carries none, so it is derived from its error and its end.+function statusOf(span: SpanRow): string {+ if (span.status) return span.status;+ if (span.error != null) return 'error';+ return span.endedAt ? 'success' : 'running';+}++function toSummary(span: SpanRow): TraceSummary {+ const metadata = span.metadata ?? {};+ const trigger = metadata.trigger;+ return {+ traceId: span.traceId,+ name: span.name,+ status: statusOf(span),+ startedAt: toIso(span.startedAt),+ endedAt: span.endedAt ? toIso(span.endedAt) : null,+ durationMs: durationOf(span.startedAt, span.endedAt),+ projectId: numberOf(metadata.projectId),+ runId: numberOf(metadata.runId),+ trigger: typeof trigger === 'string' ? (trigger as AgentRunTrigger) : null,+ issueId: numberOf(metadata.issueId),+ };+}++// One page of the agent's traces the viewer may read, newest first, optionally only+// those of one project. A chat run carries the member who chatted, and its spans hold+// what they wrote, so like the chat thread itself its trace is theirs alone: the team's+// owner reads it no more than anyone else. Read with SQL rather than the store's list,+// whose metadata filter matches values and cannot leave out the chats of other people.+export async function listAgentTraces(+ agentId: number,+ viewerId: string,+ opts: { projectId?: number; limit: number; offset: number },+): Promise<{ items: TraceSummary[]; total: number }> {+ await traceStore();+ const where = sql`r."parentSpanId" IS NULL+ AND r.metadata->>'agentId' = ${String(agentId)}+ AND (r.metadata->>'userId' IS NULL OR r.metadata->>'userId' = ${viewerId})+ ${opts.projectId != null ? sql`AND r.metadata->>'projectId' = ${String(opts.projectId)}` : sql``}`;+ const [rows, counted] = await Promise.all([+ db.execute(sql`+ SELECT r."traceId", r."spanId", r.name, r."spanType", r.error, r.metadata,+ r."startedAtZ" AS "startedAt", r."endedAtZ" AS "endedAt"+ FROM mastra_ai_spans r+ WHERE ${where}+ ORDER BY r."startedAtZ" DESC+ LIMIT ${opts.limit} OFFSET ${opts.offset}`),+ db.execute(sql`SELECT count(*)::int AS total FROM mastra_ai_spans r WHERE ${where}`),+ ]);+ const [count] = counted as unknown as { total: number }[];+ return { items: (rows as unknown as SpanRow[]).map(toSummary), total: count?.total ?? 0 };+}++// Every span of one trace, oldest first, or null when the trace is not this agent's or+// is another person's chat — either reads as missing rather than as refused.+export async function getAgentTrace(+ agentId: number,+ traceId: string,+ viewerId: string,+): Promise<{ trace: TraceSummary; spans: TraceSpan[] } | null> {+ const store = await traceStore();+ const trace = await store.getTrace({ traceId });+ if (!trace) return null;+ const root = trace.spans.find((span) => span.parentSpanId == null);+ if (!root || numberOf(root.metadata?.agentId) !== agentId) return null;+ const chattedBy = root.metadata?.userId;+ if (chattedBy != null && chattedBy !== viewerId) return null;+ const spans = [...trace.spans]+ .sort((a, b) => timeOf(a.startedAt) - timeOf(b.startedAt))+ .map((span) => ({+ spanId: span.spanId,+ parentSpanId: span.parentSpanId ?? null,+ name: span.name,+ type: span.spanType,+ status: statusOf(span),+ startedAt: toIso(span.startedAt),+ endedAt: span.endedAt ? toIso(span.endedAt) : null,+ durationMs: durationOf(span.startedAt, span.endedAt),+ input: span.input ?? null,+ output: span.output ?? null,+ error: span.error ?? null,+ attributes: span.attributes ?? null,+ }));+ return { trace: toSummary(root), spans };+}diff --git a/apps/api/src/modules/agents/schedules/__tests__/integration/schedule-extension.test.ts b/apps/api/src/modules/agents/schedules/__tests__/integration/schedule-extension.test.tsindex d3e663e7..e2bb1e10 100644--- a/apps/api/src/modules/agents/schedules/__tests__/integration/schedule-extension.test.ts+++ b/apps/api/src/modules/agents/schedules/__tests__/integration/schedule-extension.test.ts@@ -254,4 +254,50 @@ describe('agent schedule extension', () => {const copied = (await schedules(asOwner, 'DST').get()).data!.items;expect(copied[0]).toMatchObject({ type: 'event', options: { event: 'issue.label_changed' } });});++ it('keeps the schedules an extension made once it is removed, but runs and edits none', async () => {+ const { asOwner, backlog, started, agent } = await setup();+ setScheduleTypes(['event']);+ setScheduleOptionsCheck(keepOptions);+ const event = (+ await schedules(asOwner).post({ agentId: agent.id, name: 'Labels', type: 'event' })+ ).data!;+ const filtered = (+ await schedules(asOwner).post({+ agentId: agent.id,+ name: 'Bugs only',+ type: 'status',+ columnId: started.id,+ options: { labels: ['bug'] },+ })+ ).data!;+ const plain = (+ await schedules(asOwner).post({+ agentId: agent.id,+ name: 'Every issue',+ type: 'status',+ columnId: started.id,+ })+ ).data!;+ setScheduleTypes();+ setScheduleOptionsCheck();++ const listed = (await schedules(asOwner).get()).data!.items;+ const supported = Object.fromEntries(listed.map((row) => [row.name, row.supported]));+ expect(supported).toEqual({ Labels: false, 'Bugs only': false, 'Every issue': true });++ const issue = (await createIssue(asOwner, backlog.id)).data!;+ await asOwner.issues({ issueId: issue.id }).patch({ columnId: started.id });+ expect(await runsOf(asOwner, filtered.id)).toEqual([]);+ expect(await runsOf(asOwner, plain.id)).toHaveLength(1);++ const paused = await schedules(asOwner)({ scheduleId: filtered.id }).patch({+ status: 'paused',+ });+ expect(paused.status).toBe(409);+ const renamed = await schedules(asOwner)({ scheduleId: event.id }).patch({ name: 'Other' });+ expect(renamed.status).toBe(409);+ const deleted = await schedules(asOwner)({ scheduleId: event.id }).delete();+ expect(deleted.status).toBe(204);+ });});diff --git a/apps/api/src/modules/agents/schedules/extension.ts b/apps/api/src/modules/agents/schedules/extension.tsindex 17263941..d32022ac 100644--- a/apps/api/src/modules/agents/schedules/extension.ts+++ b/apps/api/src/modules/agents/schedules/extension.ts@@ -58,6 +58,16 @@ export function checkScheduleOptions(input: ScheduleOptionsInput): Promise<Schedreturn optionsCheck(input);}+// Whether this instance runs the schedule as it was set up: its type is installed, and+// what its options ask for is read by an installed extension. One made by an extension+// since removed is kept as it is, so it works again once the extension is back, but it+// starts no run and is not edited: run without its options it would start on issues+// they leave out.+export function isScheduleSupported(schedule: { type: string; options: ScheduleOptions }): boolean {+ if (!isScheduleType(schedule.type)) return false;+ return optionsCheck !== noOptions || Object.keys(schedule.options).length === 0;+}+type IssueFilter = (schedule: ScheduleForExtension, issueIds: number[]) => Promise<number[]>;const everyIssue: IssueFilter = async (_schedule, issueIds) => issueIds;diff --git a/apps/api/src/modules/agents/schedules/index.ts b/apps/api/src/modules/agents/schedules/index.tsindex 48e89753..cbadc5c0 100644--- a/apps/api/src/modules/agents/schedules/index.ts+++ b/apps/api/src/modules/agents/schedules/index.ts@@ -107,6 +107,12 @@ export const agentScheduleRoutes = new Elysia({async ({ project, params, body, user }) => {const current = await getAgentSchedule(project.id, params.scheduleId, requireUser(user).id);if (!current) throw new HttpError(404, 'Schedule not found');+ if (!current.supported) {+ throw new HttpError(+ 409,+ 'This schedule was set up with Cloud or Pro and does not run here; it can only be deleted',+ );+ }const trigger = await scheduleTriggerFields(project, current.type, body);// A resumed cron schedule runs next from now, not from when it was paused.const resuming = body.status === 'active' && current.status === 'paused';@@ -150,7 +156,7 @@ export const agentScheduleRoutes = new Elysia({summary: 'Update an agent schedule',description:"Update a schedule's agent, task, cron or column, options, or status. Its type stays " +- 'the one it was created with.',+ 'the one it was created with. A schedule that is not supported here answers 409.',...mcpTool('update_agent_schedule'),},},diff --git a/apps/api/src/modules/agents/schedules/issue-runs.ts b/apps/api/src/modules/agents/schedules/issue-runs.tsindex e0a7bde6..32376805 100644--- a/apps/api/src/modules/agents/schedules/issue-runs.ts+++ b/apps/api/src/modules/agents/schedules/issue-runs.ts@@ -1,6 +1,6 @@import { db, agentRun, agentSchedule, aiAgent, issue, project, projectColumn } from '@repo/db';import { and, eq, inArray, ne, notInArray, sql } from 'drizzle-orm';-import { filterScheduleIssues, type ScheduleForExtension } from './extension';+import { filterScheduleIssues, isScheduleSupported, type ScheduleForExtension } from './extension';// The runs schedules queue on issues: a 'status' schedule's when an issue enters its// column, and those of an extension's types when the extension calls queueScheduleRuns.@@ -107,7 +107,8 @@ export async function queueScheduleRuns();}-async function insertIssueRuns(schedules: IssueSchedule[], issueIds: number[]): Promise<void> {+async function insertIssueRuns(all: IssueSchedule[], issueIds: number[]): Promise<void> {+ const schedules = all.filter(isScheduleSupported);if (schedules.length === 0) return;const issues = await db.select({diff --git a/apps/api/src/modules/agents/schedules/model.ts b/apps/api/src/modules/agents/schedules/model.tsindex 6ba8b2a5..1e2c10cc 100644--- a/apps/api/src/modules/agents/schedules/model.ts+++ b/apps/api/src/modules/agents/schedules/model.ts@@ -102,6 +102,11 @@ export const AgentScheduleResponse = t.Object({description:"Whether you may run or stop this schedule; an 'owner'-scoped agent serves its owner only.",}),+ supported: t.Boolean({+ description:+ 'False for a schedule whose type or options come from Cloud or Pro and are not on this ' ++ 'instance. It is kept as it is but starts no run and cannot be updated, only deleted.',+ }),createdAt: t.String(),updatedAt: t.String(),});diff --git a/apps/api/src/modules/agents/schedules/service.ts b/apps/api/src/modules/agents/schedules/service.tsindex 1f167937..c820a66c 100644--- a/apps/api/src/modules/agents/schedules/service.ts+++ b/apps/api/src/modules/agents/schedules/service.ts@@ -3,7 +3,7 @@ import { and, desc, eq, isNull, sql } from 'drizzle-orm';import { HttpError, iso, rethrowDuplicate } from '#shared/lib';import { getTeamLimits } from '#shared/limits';import { minCronIntervalSeconds, nextCronRun } from './cron';-import type { ScheduleOptions } from './extension';+import { isScheduleSupported, type ScheduleOptions } from './extension';import { agentWorksInProject, canTriggerAgent, isTriggerableBy } from '../core/service';import { contextTokensOf } from '../core/run-queue';import { deleteThreadsWhere } from '../core/runtime/memory';@@ -35,6 +35,7 @@ export interface AgentScheduleRow {// Whether the member reading the schedule may send its agent a task: an 'owner'-scoped// runner serves its owner only.canTrigger: boolean;+ supported: boolean;createdAt: string;updatedAt: string;}@@ -90,6 +91,7 @@ function mapSchedule(row: SelectedSchedule, actorUserId: string): AgentScheduleRnextRunAt: schedule.nextRunAt ? iso(schedule.nextRunAt) : null,lastRunAt: schedule.lastRunAt ? iso(schedule.lastRunAt) : null,canTrigger: isTriggerableBy({ kind, runnerScope, ownerUserId }, actorUserId),+ supported: isScheduleSupported(schedule),createdAt: iso(schedule.createdAt),updatedAt: iso(schedule.updatedAt),};diff --git a/apps/api/src/modules/god/__tests__/integration/god-agent-settings.test.ts b/apps/api/src/modules/god/__tests__/integration/god-agent-settings.test.tsnew file mode 100644index 00000000..0b0a8c43--- /dev/null+++ b/apps/api/src/modules/god/__tests__/integration/god-agent-settings.test.ts@@ -0,0 +1,60 @@+import { describe, it, expect, beforeEach } from 'bun:test';+import { resetDb } from '#tests/helpers/db';+import { addUser, setup } from '../helpers';++// The instance-wide agent settings under god mode: what applies to every team's+// agents. Today that is how long the traces of their runs are kept, which the+// background sweep reads (agents/core/runtime/trace-retention.ts).++describe('god agent settings', () => {+ beforeEach(async () => {+ await resetDb();+ });++ it('refuses both routes for a user who is not the instance owner', async () => {+ await setup();+ const outsider = await addUser();++ expect((await outsider.api.god['agent-settings'].get()).status).toBe(403);+ expect((await outsider.api.god['agent-settings'].put({ traceRetentionDays: 7 })).status).toBe(+ 403,+ );+ });++ it('starts at 30 days', async () => {+ const { god } = await setup();++ const res = await god.api.god['agent-settings'].get();++ expect(res.status).toBe(200);+ expect(res.data?.traceRetentionDays).toBe(30);+ });++ it('stores a change and reads it back', async () => {+ const { god } = await setup();++ const put = await god.api.god['agent-settings'].put({ traceRetentionDays: 7 });+ const get = await god.api.god['agent-settings'].get();++ expect(put.status).toBe(200);+ expect(get.data?.traceRetentionDays).toBe(7);+ });++ it('takes 0, which keeps every trace', async () => {+ const { god } = await setup();++ const res = await god.api.god['agent-settings'].put({ traceRetentionDays: 0 });++ expect(res.status).toBe(200);+ expect(res.data?.traceRetentionDays).toBe(0);+ });++ it('refuses a negative window and one past ten years', async () => {+ const { god } = await setup();++ expect((await god.api.god['agent-settings'].put({ traceRetentionDays: -1 })).status).toBe(400);+ expect((await god.api.god['agent-settings'].put({ traceRetentionDays: 3651 })).status).toBe(+ 400,+ );+ });+});diff --git a/apps/api/src/modules/god/index.ts b/apps/api/src/modules/god/index.tsindex 0c0463e9..4b6a802f 100644--- a/apps/api/src/modules/god/index.ts+++ b/apps/api/src/modules/god/index.ts@@ -71,9 +71,12 @@ import {setHotkeySettings,getProjectDefaults,setProjectDefaults,+ getAgentSettings,+ setAgentSettings,} from '#modules/settings/service';import { getUpdateStatus } from '#modules/settings/updates';import {+ AgentSettingsSchema,HotkeyCombosSchema,ProjectDefaultsSchema,StorageSettingsSchema,@@ -333,6 +336,25 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })},})+ .get('/god/agent-settings', () => getAgentSettings(), {+ response: { 200: AgentSettingsSchema, ...errors(401, 403) },+ detail: {+ summary: 'Get instance agent settings',+ description: "Get what applies to every team's agents on this instance.",+ },+ })++ .put('/god/agent-settings', ({ body }) => setAgentSettings(body), {+ body: AgentSettingsSchema,+ response: { 200: AgentSettingsSchema, ...errors(400, 401, 403) },+ detail: {+ summary: 'Update instance agent settings',+ description:+ "Update what applies to every team's agents. A shorter trace retention takes effect " ++ 'on the next sweep, which deletes the traces already past it.',+ },+ })+.get('/god/hotkey-settings', () => getHotkeySettings(), {response: { 200: HotkeyCombosSchema, ...errors(401, 403) },detail: {diff --git a/apps/api/src/modules/members/service.ts b/apps/api/src/modules/members/service.tsindex 22fa8843..5b5bb1f7 100644--- a/apps/api/src/modules/members/service.ts+++ b/apps/api/src/modules/members/service.ts@@ -131,6 +131,27 @@ export async function getMemberContext(return r ? toMemberContext(r.role as MemberRole, r.permissions) : null;}+// A user's resolved matrix in each project of the team they are a member of.+export async function getProjectPermissions(+ teamId: number,+ userId: string,+): Promise<{ projectId: number; permissions: Permissions }[]> {+ const rows = await db+ .select({+ projectId: project.id,+ role: projectMember.role,+ permissions: teamRole.permissions,+ })+ .from(projectMember)+ .innerJoin(project, eq(project.id, projectMember.projectId))+ .leftJoin(teamRole, eq(teamRole.id, projectMember.roleId))+ .where(and(eq(project.teamId, teamId), eq(projectMember.userId, userId)));+ return rows.map((row) => ({+ projectId: row.projectId,+ permissions: toMemberContext(row.role as MemberRole, row.permissions).permissions,+ }));+}+// The access a user has across a team: the permissions of their project memberships// in it, merged. Permissions are only ever assigned per project, so this is what a// team-scoped resource checks for a member who is neither owner nor manager of the@@ -138,15 +159,8 @@ export async function getMemberContext(// what lets a project owner manage the resources the team holds for all of them.// Someone who is a member of no project of the team gets an empty matrix.export async function getTeamPermissions(teamId: number, userId: string): Promise<Permissions> {- const rows = await db- .select({ role: projectMember.role, permissions: teamRole.permissions })- .from(projectMember)- .innerJoin(project, eq(project.id, projectMember.projectId))- .leftJoin(teamRole, eq(teamRole.id, projectMember.roleId))- .where(and(eq(project.teamId, teamId), eq(projectMember.userId, userId)));const merged = emptyPermissions();- for (const row of rows) {- const { permissions } = toMemberContext(row.role as MemberRole, row.permissions);+ for (const { permissions } of await getProjectPermissions(teamId, userId)) {for (const resource of PERMISSION_RESOURCES) {for (const action of PERMISSION_ACTIONS) {merged[resource][action] ||= permissions[resource][action];diff --git a/apps/api/src/modules/settings/model.ts b/apps/api/src/modules/settings/model.tsindex db2b6df7..2e182412 100644--- a/apps/api/src/modules/settings/model.ts+++ b/apps/api/src/modules/settings/model.ts@@ -11,6 +11,15 @@ export const ProjectDefaultsSchema = t.Object({mcpEnabled: t.Boolean(),});+export const AgentSettingsSchema = t.Object({+ traceRetentionDays: t.Integer({+ minimum: 0,+ maximum: 3650,+ description:+ 'Days the traces of an agent run are kept for. 0 keeps them until they are deleted by hand.',+ }),+});+// A command id bound to a combination written as modifier tokens plus a key// ('mod+k', 'n'). The set of commands lives in the web app (its lib/hotkeys), so// the API checks the shape and stores the map as given.diff --git a/apps/api/src/modules/settings/service.ts b/apps/api/src/modules/settings/service.tsindex b4c748b9..d503833e 100644--- a/apps/api/src/modules/settings/service.ts+++ b/apps/api/src/modules/settings/service.ts@@ -60,6 +60,32 @@ export async function setProjectDefaults(return next;}+// The instance agent settings (app_setting key 'agents'): what applies to every team's+// agents.++const AGENT_SETTINGS_KEY = 'agents';++export interface AgentSettings {+ // Days the traces of an agent run are kept for; the background sweep deletes older+ // ones (agents/core/runtime/trace-retention.ts). 0 keeps them.+ traceRetentionDays: number;+}++function defaultAgentSettings(): AgentSettings {+ return { traceRetentionDays: 30 };+}++export async function getAgentSettings(): Promise<AgentSettings> {+ const stored = await getSetting<Partial<AgentSettings>>(AGENT_SETTINGS_KEY);+ return { ...defaultAgentSettings(), ...(stored ?? {}) };+}++export async function setAgentSettings(patch: Partial<AgentSettings>): Promise<AgentSettings> {+ const next = { ...(await getAgentSettings()), ...patch };+ await setSetting(AGENT_SETTINGS_KEY, next);+ return next;+}+// The instance keyboard shortcuts (app_setting key 'hotkeys'): the combination// each command is bound to for everyone on this instance. Only the bindings// changed in god mode are stored; the web app fills the rest from its built-indiff --git a/apps/api/src/shared/access.ts b/apps/api/src/shared/access.tsindex 82aa40d0..39d39b41 100644--- a/apps/api/src/shared/access.ts+++ b/apps/api/src/shared/access.ts@@ -6,7 +6,11 @@ import {type ProjectRow,} from '#modules/projects/service';import { featureLabel, type ProjectFeature } from './features';-import { getMemberContext, getTeamPermissions } from '#modules/members/service';+import {+ getMemberContext,+ getProjectPermissions,+ getTeamPermissions,+} from '#modules/members/service';import { getTeamMembership, runsTeam, type TeamStanding } from '#modules/teams/service';import { projectWorkspaceGrant, workspaceGrant } from '#modules/workspaces/service';import { hasPermission, type PermissionAction, type PermissionResource } from './permissions';@@ -338,3 +342,20 @@ export async function requireTeamPermission(}return membership;}++// The projects of the team where the member holds the permission, for a team-wide read+// that shows each member only those. Null is every project: whoever runs the team, or+// holds the permission through their role in the workspace.+export async function projectsWithPermission(+ membership: TeamMembership,+ resource: PermissionResource,+ action: PermissionAction,+): Promise<number[] | null> {+ if (runsTeam(membership.role)) return null;+ const access = await getTeamAccess(membership.teamId, membership.userId);+ if (access?.grant && hasPermission(access.grant, resource, action)) return null;+ const projects = await getProjectPermissions(membership.teamId, membership.userId);+ return projects+ .filter((entry) => hasPermission(entry.permissions, resource, action))+ .map((entry) => entry.projectId);+}diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex dd9fbb6c..d4b7cc48 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -18,8 +18,11 @@ Next.js App Router, SSR (not SPA). Tailwind v4 + shadcn/ui. See root `AGENTS.md`nowhere else. `useWorkspaceSections(workspace, core)` returns a workspace's settings menu,shown by `WorkspaceSectionNav`: here the core's sections as they are, while the hostedbuild adds its own at any position or drops some. One it adds carries in `Component` the- page `/workspaces/:id/:sectionId` opens. `/workspaces/:id` names no section and opens the- first entry of the menu, so the order also decides the page a workspace opens on.+ page `/workspaces/:id/:sectionId` opens. Every section names its group: an `overview`+ one sits at the top of the menu, a `settings` one in the folding Settings group below,+ each in the order given.+ `/workspaces/:id` names no section and opens the first entry of the menu, so the order+ also decides the page a workspace opens on.`NoTeamStart` is the start page of an account with no team and no workspace it owns,which happens while personal workspaces are off; here it says who adds them.`WorkspaceRailActions` sits below the workspace tiles of a rail; here it says where more@@ -35,7 +38,10 @@ Next.js App Router, SSR (not SPA). Tailwind v4 + shadcn/ui. See root `AGENTS.md`and edits an agent schedule: here the core's, while the hosted build opens its own withthe same props, with the schedule types it adds and the `options` it keeps on aschedule. The schedule list names such a type by the message- `settings.schedules.types.<id>`. `cloudMessages` is the+ `settings.schedules.types.<id>`. `AgentAnalyticsExtras` renders below the panels of an+ agent dashboard, a team's or a workspace's, with the scope and the window it shows;+ here a preview of the panels the hosted build and Pro add, which folds to its title and+ description. `cloudMessages` is thehosted build's English, merged into the catalogue the keys are typed against (a godsection's name and blurb go under `sections.god.<slug>` like the core ones), and`loadCloudMessages(locale)` returns its other languages. The i18n request config importsdiff --git a/apps/web/messages/ar/agentAnalytics.json b/apps/web/messages/ar/agentAnalytics.jsonnew file mode 100644index 00000000..f5380a21--- /dev/null+++ b/apps/web/messages/ar/agentAnalytics.json@@ -0,0 +1,80 @@+{+ "window": "{days, plural, =1 {آخر 24 ساعة} few {آخر # أيام} many {آخر # يوماً} other {آخر # يوم}}",+ "retentionNote": "الوكلاء الداخليون فقط. لا تُحتسب عمليات التشغيل الأقدم من مدة حفظ التتبّعات في هذه النسخة.",+ "noComparison": "لا يوجد ما نقارن به",+ "vsPrevious": "مقابل {value} سابقاً",+ "deletedAgent": "وكيل محذوف",+ "deletedProject": "مشروع محذوف",+ "allProjects": "كل المشاريع",+ "totalTokens": "إجمالي الرموز",+ "totalCost": "إجمالي التكلفة",+ "stats": {+ "cost": "تكلفة النماذج",+ "tokens": "الرموز",+ "runs": "عمليات التشغيل",+ "errors": "عمليات فاشلة"+ },+ "measure": {+ "tokens": "الرموز",+ "cost": "التكلفة"+ },+ "series": {+ "input": "الإدخال",+ "output": "الإخراج"+ },+ "models": {+ "title": "حسب النموذج",+ "description": "الرموز والتكلفة لكل نموذج.",+ "model": "النموذج",+ "input": "الإدخال",+ "output": "الإخراج",+ "cost": "التكلفة",+ "empty": "لا استدعاءات للنماذج في هذه الفترة"+ },+ "byAgent": {+ "title": "حسب الوكيل",+ "description": "ما استخدمه كل وكيل.",+ "empty": "لم يعمل أي وكيل في هذه الفترة"+ },+ "byProject": {+ "title": "حسب المشروع",+ "description": "ما استخدمه الوكلاء في كل مشروع.",+ "empty": "لم يعمل أي وكيل في هذه الفترة"+ },+ "byTeam": {+ "title": "حسب الفريق",+ "description": "ما استخدمه وكلاء كل فريق.",+ "empty": "لم يعمل أي وكيل في هذه الفترة"+ },+ "overTime": {+ "title": "عبر الزمن",+ "description": "الرموز والتكلفة خلال الفترة.",+ "empty": "لا استهلاك في هذه الفترة"+ },+ "preview": {+ "title": "المزيد في Cloud وPro",+ "description": "الإنفاق حسب الشخص والمشغّل، ومدة التشغيل، واستدعاءات الأدوات. متاح في Cloud وفي نسخة Pro للاستضافة الذاتية.",+ "hide": "إخفاء",+ "show": "إظهار",+ "byPerson": {+ "title": "حسب الشخص",+ "description": "من شغّل الوكلاء في محادثة أو بإشارة."+ },+ "byTrigger": {+ "title": "حسب المشغّل",+ "description": "محادثة أو إشارة أو جدول أو حدث مهمة."+ },+ "bySchedule": {+ "title": "حسب الجدول",+ "description": "ما أنفقه كل جدول."+ },+ "tools": {+ "title": "الأدوات",+ "description": "استدعاءات الأدوات وعدد ما فشل منها."+ },+ "latency": {+ "title": "مدة التشغيل",+ "description": "الوسيط والمئين 95 لكل يوم."+ }+ }+}diff --git a/apps/web/messages/ar/common.json b/apps/web/messages/ar/common.jsonindex 226ef529..fc265d10 100644--- a/apps/web/messages/ar/common.json+++ b/apps/web/messages/ar/common.json@@ -211,5 +211,6 @@"page": "الصفحة {number}","perPage": "لكل صفحة","range": "{first}-{last} من {total}"- }+ },+ "aboutCloudAndPro": "اعرف المزيد عن Cloud وPro"}diff --git a/apps/web/messages/ar/god.json b/apps/web/messages/ar/god.jsonindex 81f90cb6..ed3e482e 100644--- a/apps/web/messages/ar/god.json+++ b/apps/web/messages/ar/god.json@@ -164,7 +164,13 @@"workspacesSaved": "اتحفظت إعدادات مساحات العمل","workspaces": "مساحات العمل","personalWorkspaces": "مساحة عمل لكل شخص",- "personalWorkspacesHint": "كل حساب بياخد مساحة عمل خاصة بيه باسم صاحبه. لو اتقفل، الناس بيشتغلوا بس في مساحات العمل اللي اتضافوا ليها."+ "personalWorkspacesHint": "كل حساب بياخد مساحة عمل خاصة بيه باسم صاحبه. لو اتقفل، الناس بيشتغلوا بس في مساحات العمل اللي اتضافوا ليها.",+ "agents": "الوكلاء",+ "agentsSaved": "تم حفظ إعدادات الوكلاء",+ "traceRetention": "مدة حفظ تتبّعات التشغيل",+ "traceRetentionHint": "كل تشغيل لوكيل يسجّل استدعاءات النموذج والأدوات. لوحات الاستهلاك تحتسب العمليات المحفوظة فقط.",+ "traceDays": "{days, plural, one {يوم واحد} two {يومان} few {# أيام} many {# يوماً} other {# يوم}}",+ "traceForever": "دائماً"},"authentication": {"saved": "تم حفظ إعدادات المصادقة",diff --git a/apps/web/messages/ar/permissions.json b/apps/web/messages/ar/permissions.jsonindex 21cc7df8..508b04b8 100644--- a/apps/web/messages/ar/permissions.json+++ b/apps/web/messages/ar/permissions.json@@ -17,6 +17,7 @@"integrations": "التكاملات (integrations)","agent_skills": "مهارات الوكلاء (agent skills)","agent_tools": "أدوات الوكلاء (agent tools)",+ "agent_usage": "استهلاك الوكلاء","custom_fields": "الحقول المخصّصة","issue_templates": "قوالب المهام","workflow_config": "تهيئة سير العمل",diff --git a/apps/web/messages/ar/sections.json b/apps/web/messages/ar/sections.jsonindex e620bcab..38c150eb 100644--- a/apps/web/messages/ar/sections.json+++ b/apps/web/messages/ar/sections.json@@ -25,7 +25,7 @@},"general": {"label": "عام",- "description": "مساحات العمل الشخصية والإعدادات الافتراضية للمشاريع الجديدة."+ "description": "مساحات العمل الشخصية والإعدادات الافتراضية للمشاريع الجديدة وتتبّعات الوكلاء."},"authentication": {"label": "المصادقة",diff --git a/apps/web/messages/ar/settings.json b/apps/web/messages/ar/settings.jsonindex 7aadc4c9..38131fd1 100644--- a/apps/web/messages/ar/settings.json+++ b/apps/web/messages/ar/settings.json@@ -46,6 +46,8 @@"runsSuffix": "{description} UTC","statusActive": "نشطة","statusPaused": "متوقفة مؤقتًا",+ "unavailable": "يتطلب Cloud أو Pro",+ "unavailableHint": "أُنشئ باستخدام Cloud أو Pro. محفوظ كما هو، لكنه لا يعمل هنا.","viewTask": "عرض المهمة","noRunsShort": "لا توجد تشغيلات بعد","pause": "إيقاف الجدولة مؤقتًا",diff --git a/apps/web/messages/ar/teams.json b/apps/web/messages/ar/teams.jsonindex de475521..086eaa00 100644--- a/apps/web/messages/ar/teams.json+++ b/apps/web/messages/ar/teams.json@@ -51,6 +51,10 @@"agents": {"title": "وكلاء الذكاء الاصطناعي","description": "وكلاء الذكاء الاصطناعي التابعون لهذا الفريق، والمشاريع التي يعمل فيها كل منهم."+ },+ "analytics": {+ "title": "الاستهلاك",+ "description": "إنفاق وكلاء الفريق على النماذج، حسب الوكيل والمشروع واليوم."}},"info": {@@ -658,6 +662,11 @@"title": "حذف {name}؟","description": "<strong>{name}</strong> وفرقها هيتحذفوا. الناس هيحتفظوا بحساباتهم وفرقهم التانية. ده مش هينفع ترجع فيه.","deleted": "تم حذف مساحة العمل"- }+ },+ "agentUsage": {+ "title": "استهلاك الذكاء الاصطناعي",+ "description": "إنفاق وكلاء جميع الفرق على النماذج."+ },+ "settingsGroup": "الإعدادات"}}diff --git a/apps/web/messages/en/agentAnalytics.json b/apps/web/messages/en/agentAnalytics.jsonnew file mode 100644index 00000000..ca799e6a--- /dev/null+++ b/apps/web/messages/en/agentAnalytics.json@@ -0,0 +1,80 @@+{+ "window": "{days, plural, =1 {Last 24 hours} other {Last # days}}",+ "retentionNote": "Internal agents only. Runs older than the instance's trace retention are not counted.",+ "noComparison": "Nothing to compare with",+ "vsPrevious": "vs {value} before",+ "deletedAgent": "Deleted agent",+ "deletedProject": "Deleted project",+ "allProjects": "All projects",+ "totalTokens": "Total tokens",+ "totalCost": "Total cost",+ "stats": {+ "cost": "Model cost",+ "tokens": "Tokens",+ "runs": "Runs",+ "errors": "Failed runs"+ },+ "measure": {+ "tokens": "Tokens",+ "cost": "Cost"+ },+ "series": {+ "input": "Input",+ "output": "Output"+ },+ "models": {+ "title": "By model",+ "description": "Tokens and cost of each model.",+ "model": "Model",+ "input": "Input",+ "output": "Output",+ "cost": "Cost",+ "empty": "No model calls in this period"+ },+ "byAgent": {+ "title": "By agent",+ "description": "What each agent used.",+ "empty": "No agent runs in this period"+ },+ "byProject": {+ "title": "By project",+ "description": "What the agents used in each project.",+ "empty": "No agent runs in this period"+ },+ "byTeam": {+ "title": "By team",+ "description": "What each team's agents used.",+ "empty": "No agent runs in this period"+ },+ "overTime": {+ "title": "Over time",+ "description": "Tokens and cost across the period.",+ "empty": "No usage in this period"+ },+ "preview": {+ "title": "More in Cloud and Pro",+ "description": "Spend by person and trigger, run time and tool calls. Available in Cloud and self-hosted Pro.",+ "hide": "Hide",+ "show": "Show",+ "byPerson": {+ "title": "By person",+ "description": "Who started runs in a chat or with a mention."+ },+ "byTrigger": {+ "title": "By trigger",+ "description": "Chat, mention, schedule or issue event."+ },+ "bySchedule": {+ "title": "By schedule",+ "description": "What each schedule spent."+ },+ "tools": {+ "title": "Tools",+ "description": "Tool calls and how many failed."+ },+ "latency": {+ "title": "Run time",+ "description": "Median and 95th percentile per day."+ }+ }+}diff --git a/apps/web/messages/en/common.json b/apps/web/messages/en/common.jsonindex adfa0eba..3b266fc4 100644--- a/apps/web/messages/en/common.json+++ b/apps/web/messages/en/common.json@@ -211,5 +211,6 @@"page": "Page {number}","perPage": "per page","range": "{first}-{last} of {total}"- }+ },+ "aboutCloudAndPro": "Learn about Cloud and Pro"}diff --git a/apps/web/messages/en/god.json b/apps/web/messages/en/god.jsonindex 225300f8..0c44247b 100644--- a/apps/web/messages/en/god.json+++ b/apps/web/messages/en/god.json@@ -164,7 +164,13 @@"workspacesSaved": "Workspace settings saved","workspaces": "Workspaces","personalWorkspaces": "A workspace for everyone",- "personalWorkspacesHint": "Every account gets a workspace of its own, named after the person. Off, people work only in the workspaces they are added to."+ "personalWorkspacesHint": "Every account gets a workspace of its own, named after the person. Off, people work only in the workspaces they are added to.",+ "agents": "Agents",+ "agentsSaved": "Agent settings saved",+ "traceRetention": "Keep run traces",+ "traceRetentionHint": "Each agent run records its model and tool calls. Usage dashboards count only the runs still kept.",+ "traceDays": "{days, plural, one {# day} other {# days}}",+ "traceForever": "Forever"},"authentication": {"saved": "Authentication settings saved",diff --git a/apps/web/messages/en/permissions.json b/apps/web/messages/en/permissions.jsonindex 2e900d20..76e7edbd 100644--- a/apps/web/messages/en/permissions.json+++ b/apps/web/messages/en/permissions.json@@ -17,6 +17,7 @@"integrations": "Integrations","agent_skills": "Agent skills","agent_tools": "Agent tools",+ "agent_usage": "Agent usage","custom_fields": "Custom fields","issue_templates": "Issue templates","workflow_config": "Workflow configuration",diff --git a/apps/web/messages/en/sections.json b/apps/web/messages/en/sections.jsonindex 79d2c607..8dbe9cab 100644--- a/apps/web/messages/en/sections.json+++ b/apps/web/messages/en/sections.json@@ -25,7 +25,7 @@},"general": {"label": "General",- "description": "Personal workspaces and defaults for new projects."+ "description": "Personal workspaces, defaults for new projects, and agent traces."},"authentication": {"label": "Authentication",diff --git a/apps/web/messages/en/settings.json b/apps/web/messages/en/settings.jsonindex 0bc08098..9ad7ca81 100644--- a/apps/web/messages/en/settings.json+++ b/apps/web/messages/en/settings.json@@ -46,6 +46,8 @@"runsSuffix": "{description} UTC","statusActive": "Active","statusPaused": "Paused",+ "unavailable": "Needs Cloud or Pro",+ "unavailableHint": "Set up with Cloud or Pro. Kept as it is, but it does not run here.","viewTask": "View task","noRunsShort": "No runs yet","pause": "Pause schedule",diff --git a/apps/web/messages/en/teams.json b/apps/web/messages/en/teams.jsonindex 56221fe0..c67b842c 100644--- a/apps/web/messages/en/teams.json+++ b/apps/web/messages/en/teams.json@@ -51,6 +51,10 @@"agents": {"title": "AI Agents","description": "The AI agents this team owns, and the projects each of them works in."+ },+ "analytics": {+ "title": "Usage",+ "description": "What the team's agents spent on models, by agent, project and day."}},"info": {@@ -658,6 +662,11 @@"title": "Delete {name}?","description": "<strong>{name}</strong> and its teams are deleted. People keep their accounts and their other teams. This cannot be undone.","deleted": "Workspace deleted"- }+ },+ "agentUsage": {+ "title": "AI usage",+ "description": "What the agents of every team spent on models."+ },+ "settingsGroup": "Settings"}}diff --git a/apps/web/messages/es-ES/agentAnalytics.json b/apps/web/messages/es-ES/agentAnalytics.jsonnew file mode 100644index 00000000..e706ebf1--- /dev/null+++ b/apps/web/messages/es-ES/agentAnalytics.json@@ -0,0 +1,80 @@+{+ "window": "{days, plural, =1 {Últimas 24 horas} other {Últimos # días}}",+ "retentionNote": "Solo agentes internos. No se cuentan las ejecuciones más antiguas que la retención de trazas de la instancia.",+ "noComparison": "Nada con lo que comparar",+ "vsPrevious": "frente a {value} antes",+ "deletedAgent": "Agente eliminado",+ "deletedProject": "Proyecto eliminado",+ "allProjects": "Todos los proyectos",+ "totalTokens": "Total de tokens",+ "totalCost": "Coste total",+ "stats": {+ "cost": "Coste de modelos",+ "tokens": "Tokens",+ "runs": "Ejecuciones",+ "errors": "Ejecuciones fallidas"+ },+ "measure": {+ "tokens": "Tokens",+ "cost": "Coste"+ },+ "series": {+ "input": "Entrada",+ "output": "Salida"+ },+ "models": {+ "title": "Por modelo",+ "description": "Tokens y coste de cada modelo.",+ "model": "Modelo",+ "input": "Entrada",+ "output": "Salida",+ "cost": "Coste",+ "empty": "No hubo llamadas a modelos en este periodo"+ },+ "byAgent": {+ "title": "Por agente",+ "description": "Lo que ha usado cada agente.",+ "empty": "No hubo ejecuciones de agentes en este periodo"+ },+ "byProject": {+ "title": "Por proyecto",+ "description": "Lo que han usado los agentes en cada proyecto.",+ "empty": "No hubo ejecuciones de agentes en este periodo"+ },+ "byTeam": {+ "title": "Por equipo",+ "description": "Lo que han usado los agentes de cada equipo.",+ "empty": "No hubo ejecuciones de agentes en este periodo"+ },+ "overTime": {+ "title": "En el tiempo",+ "description": "Tokens y coste del periodo.",+ "empty": "Sin consumo en este periodo"+ },+ "preview": {+ "title": "Más en Cloud y Pro",+ "description": "Gasto por persona y disparador, duración de ejecuciones y llamadas a herramientas. Disponible en Cloud y en Pro autoalojado.",+ "hide": "Ocultar",+ "show": "Mostrar",+ "byPerson": {+ "title": "Por persona",+ "description": "Quién inició ejecuciones en un chat o con una mención."+ },+ "byTrigger": {+ "title": "Por disparador",+ "description": "Chat, mención, programación o evento de tarea."+ },+ "bySchedule": {+ "title": "Por programación",+ "description": "Lo que gastó cada programación."+ },+ "tools": {+ "title": "Herramientas",+ "description": "Llamadas a herramientas y cuántas fallaron."+ },+ "latency": {+ "title": "Duración",+ "description": "Mediana y percentil 95 por día."+ }+ }+}diff --git a/apps/web/messages/es-ES/common.json b/apps/web/messages/es-ES/common.jsonindex e4611cc1..3729fa73 100644--- a/apps/web/messages/es-ES/common.json+++ b/apps/web/messages/es-ES/common.json@@ -211,5 +211,6 @@"page": "Página {number}","perPage": "por página","range": "{first}-{last} de {total}"- }+ },+ "aboutCloudAndPro": "Más sobre Cloud y Pro"}diff --git a/apps/web/messages/es-ES/god.json b/apps/web/messages/es-ES/god.jsonindex 46870bed..3a5d08bd 100644--- a/apps/web/messages/es-ES/god.json+++ b/apps/web/messages/es-ES/god.json@@ -164,7 +164,13 @@"workspacesSaved": "Ajustes de espacios de trabajo guardados","workspaces": "Espacios de trabajo","personalWorkspaces": "Un espacio de trabajo para cada persona",- "personalWorkspacesHint": "Cada cuenta recibe un espacio de trabajo propio con el nombre de la persona. Desactivado, cada persona trabaja solo en los espacios de trabajo a los que se le ha añadido."+ "personalWorkspacesHint": "Cada cuenta recibe un espacio de trabajo propio con el nombre de la persona. Desactivado, cada persona trabaja solo en los espacios de trabajo a los que se le ha añadido.",+ "agents": "Agentes",+ "agentsSaved": "Ajustes de agentes guardados",+ "traceRetention": "Conservar trazas de ejecución",+ "traceRetentionHint": "Cada ejecución de un agente registra sus llamadas al modelo y a las herramientas. Los paneles de consumo solo cuentan las ejecuciones conservadas.",+ "traceDays": "{days, plural, one {# día} other {# días}}",+ "traceForever": "Siempre"},"authentication": {"saved": "Los ajustes de autenticación se han guardado",diff --git a/apps/web/messages/es-ES/permissions.json b/apps/web/messages/es-ES/permissions.jsonindex f270180e..40dd7915 100644--- a/apps/web/messages/es-ES/permissions.json+++ b/apps/web/messages/es-ES/permissions.json@@ -17,6 +17,7 @@"integrations": "Integraciones","agent_skills": "Habilidades del agente","agent_tools": "Herramientas del agente",+ "agent_usage": "Consumo de agentes","custom_fields": "Campos personalizados","issue_templates": "Plantillas de ticket","workflow_config": "Configuración del flujo de trabajo",diff --git a/apps/web/messages/es-ES/sections.json b/apps/web/messages/es-ES/sections.jsonindex ce32efed..40ad04f9 100644--- a/apps/web/messages/es-ES/sections.json+++ b/apps/web/messages/es-ES/sections.json@@ -25,7 +25,7 @@},"general": {"label": "General",- "description": "Espacios de trabajo personales y valores por defecto para los proyectos nuevos."+ "description": "Espacios de trabajo personales, valores por defecto para los proyectos nuevos y trazas de agentes."},"authentication": {"label": "Autenticación",diff --git a/apps/web/messages/es-ES/settings.json b/apps/web/messages/es-ES/settings.jsonindex 47e6fd5f..74a95a59 100644--- a/apps/web/messages/es-ES/settings.json+++ b/apps/web/messages/es-ES/settings.json@@ -46,6 +46,8 @@"runsSuffix": "{description} UTC","statusActive": "Activa","statusPaused": "En pausa",+ "unavailable": "Requiere Cloud o Pro",+ "unavailableHint": "Creado con Cloud o Pro. Se conserva tal cual, pero aquí no se ejecuta.","viewTask": "Ver la tarea","noRunsShort": "Todavía no hay ejecuciones","pause": "Posponer la programación",diff --git a/apps/web/messages/es-ES/teams.json b/apps/web/messages/es-ES/teams.jsonindex 1a4d179d..2f7a6035 100644--- a/apps/web/messages/es-ES/teams.json+++ b/apps/web/messages/es-ES/teams.json@@ -51,6 +51,10 @@"agents": {"title": "Agentes de IA","description": "Los agentes de IA que este equipo posee, y los proyectos en los que trabaja cada uno de ellos."+ },+ "analytics": {+ "title": "Consumo",+ "description": "Lo que han gastado en modelos los agentes del equipo, por agente, proyecto y día."}},"info": {@@ -658,6 +662,11 @@"title": "¿Eliminar {name}?","description": "<strong>{name}</strong> y sus equipos se eliminan. Las personas conservan sus cuentas y sus otros equipos. No se puede deshacer.","deleted": "Espacio de trabajo eliminado"- }+ },+ "agentUsage": {+ "title": "Consumo de IA",+ "description": "Lo que han gastado en modelos los agentes de todos los equipos."+ },+ "settingsGroup": "Ajustes"}}diff --git a/apps/web/messages/fr/agentAnalytics.json b/apps/web/messages/fr/agentAnalytics.jsonnew file mode 100644index 00000000..91dcabaa--- /dev/null+++ b/apps/web/messages/fr/agentAnalytics.json@@ -0,0 +1,80 @@+{+ "window": "{days, plural, =1 {Dernières 24 heures} other {# derniers jours}}",+ "retentionNote": "Agents internes uniquement. Les exécutions plus anciennes que la conservation des traces de l'instance ne sont pas comptées.",+ "noComparison": "Rien à comparer",+ "vsPrevious": "contre {value} avant",+ "deletedAgent": "Agent supprimé",+ "deletedProject": "Projet supprimé",+ "allProjects": "Tous les projets",+ "totalTokens": "Total des jetons",+ "totalCost": "Coût total",+ "stats": {+ "cost": "Coût des modèles",+ "tokens": "Jetons",+ "runs": "Exécutions",+ "errors": "Exécutions en échec"+ },+ "measure": {+ "tokens": "Jetons",+ "cost": "Coût"+ },+ "series": {+ "input": "Entrée",+ "output": "Sortie"+ },+ "models": {+ "title": "Par modèle",+ "description": "Jetons et coût de chaque modèle.",+ "model": "Modèle",+ "input": "Entrée",+ "output": "Sortie",+ "cost": "Coût",+ "empty": "Aucun appel de modèle sur cette période"+ },+ "byAgent": {+ "title": "Par agent",+ "description": "Ce que chaque agent a utilisé.",+ "empty": "Aucune exécution d'agent sur cette période"+ },+ "byProject": {+ "title": "Par projet",+ "description": "Ce que les agents ont utilisé dans chaque projet.",+ "empty": "Aucune exécution d'agent sur cette période"+ },+ "byTeam": {+ "title": "Par équipe",+ "description": "Ce que les agents de chaque équipe ont utilisé.",+ "empty": "Aucune exécution d'agent sur cette période"+ },+ "overTime": {+ "title": "Dans le temps",+ "description": "Jetons et coût sur la période.",+ "empty": "Aucune consommation sur cette période"+ },+ "preview": {+ "title": "Plus dans Cloud et Pro",+ "description": "Dépenses par personne et par déclencheur, durée des exécutions et appels d'outils. Disponible dans Cloud et dans Pro auto-hébergé.",+ "hide": "Masquer",+ "show": "Afficher",+ "byPerson": {+ "title": "Par personne",+ "description": "Qui a lancé des exécutions dans un chat ou par une mention."+ },+ "byTrigger": {+ "title": "Par déclencheur",+ "description": "Chat, mention, planification ou événement de tâche."+ },+ "bySchedule": {+ "title": "Par planification",+ "description": "Ce que chaque planification a dépensé."+ },+ "tools": {+ "title": "Outils",+ "description": "Appels d'outils et combien ont échoué."+ },+ "latency": {+ "title": "Durée d'exécution",+ "description": "Médiane et 95e centile par jour."+ }+ }+}diff --git a/apps/web/messages/fr/common.json b/apps/web/messages/fr/common.jsonindex 441931de..7d7a0108 100644--- a/apps/web/messages/fr/common.json+++ b/apps/web/messages/fr/common.json@@ -211,5 +211,6 @@"page": "Page {number}","perPage": "par page","range": "{first}-{last} sur {total}"- }+ },+ "aboutCloudAndPro": "En savoir plus sur Cloud et Pro"}diff --git a/apps/web/messages/fr/god.json b/apps/web/messages/fr/god.jsonindex 8a7148ad..69e0eb90 100644--- a/apps/web/messages/fr/god.json+++ b/apps/web/messages/fr/god.json@@ -164,7 +164,13 @@"workspacesSaved": "Paramètres des espaces de travail enregistrés","workspaces": "Espaces de travail","personalWorkspaces": "Un espace de travail pour chacun",- "personalWorkspacesHint": "Chaque compte reçoit son propre espace de travail, à son nom. Désactivé, chacun travaille seulement dans les espaces de travail où il a été ajouté."+ "personalWorkspacesHint": "Chaque compte reçoit son propre espace de travail, à son nom. Désactivé, chacun travaille seulement dans les espaces de travail où il a été ajouté.",+ "agents": "Agents",+ "agentsSaved": "Paramètres des agents enregistrés",+ "traceRetention": "Conserver les traces d'exécution",+ "traceRetentionHint": "Chaque exécution d'agent enregistre ses appels au modèle et aux outils. Les tableaux de consommation ne comptent que les exécutions conservées.",+ "traceDays": "{days, plural, one {# jour} other {# jours}}",+ "traceForever": "Toujours"},"authentication": {"saved": "Paramètres d'authentification enregistrés",diff --git a/apps/web/messages/fr/permissions.json b/apps/web/messages/fr/permissions.jsonindex bc6c4229..1aa20d9b 100644--- a/apps/web/messages/fr/permissions.json+++ b/apps/web/messages/fr/permissions.json@@ -17,6 +17,7 @@"integrations": "Intégrations","agent_skills": "Compétences des agents","agent_tools": "Outils des agents",+ "agent_usage": "Consommation des agents","custom_fields": "Champs personnalisés","issue_templates": "Modèles de tickets","workflow_config": "Configuration du flux de travail",diff --git a/apps/web/messages/fr/sections.json b/apps/web/messages/fr/sections.jsonindex eab62675..b5e6b2c5 100644--- a/apps/web/messages/fr/sections.json+++ b/apps/web/messages/fr/sections.json@@ -25,7 +25,7 @@},"general": {"label": "Général",- "description": "Les espaces de travail personnels et les valeurs par défaut des nouveaux projets."+ "description": "Les espaces de travail personnels, les valeurs par défaut des nouveaux projets et les traces des agents."},"authentication": {"label": "Authentification",diff --git a/apps/web/messages/fr/settings.json b/apps/web/messages/fr/settings.jsonindex 7fc48742..116763fb 100644--- a/apps/web/messages/fr/settings.json+++ b/apps/web/messages/fr/settings.json@@ -46,6 +46,8 @@"runsSuffix": "{description} UTC","statusActive": "Active","statusPaused": "En pause",+ "unavailable": "Nécessite Cloud ou Pro",+ "unavailableHint": "Créé avec Cloud ou Pro. Conservé tel quel, mais ne s'exécute pas ici.","viewTask": "Voir la tâche","noRunsShort": "Aucune exécution","pause": "Mettre la planification en pause",diff --git a/apps/web/messages/fr/teams.json b/apps/web/messages/fr/teams.jsonindex dc357cd2..d9b9c661 100644--- a/apps/web/messages/fr/teams.json+++ b/apps/web/messages/fr/teams.json@@ -51,6 +51,10 @@"agents": {"title": "Agents IA","description": "Les agents IA que cette équipe détient, et les projets dans lesquels chacun travaille."+ },+ "analytics": {+ "title": "Consommation",+ "description": "Ce que les agents de l'équipe ont dépensé en modèles, par agent, projet et jour."}},"info": {@@ -658,6 +662,11 @@"title": "Supprimer {name} ?","description": "<strong>{name}</strong> et ses équipes sont supprimés. Les personnes gardent leur compte et leurs autres équipes. Cette action est irréversible.","deleted": "Espace de travail supprimé"- }+ },+ "agentUsage": {+ "title": "Consommation IA",+ "description": "Ce que les agents de toutes les équipes ont dépensé en modèles."+ },+ "settingsGroup": "Paramètres"}}diff --git a/apps/web/messages/id/agentAnalytics.json b/apps/web/messages/id/agentAnalytics.jsonnew file mode 100644index 00000000..1554f30a--- /dev/null+++ b/apps/web/messages/id/agentAnalytics.json@@ -0,0 +1,80 @@+{+ "window": "{days, plural, =1 {24 jam terakhir} other {# hari terakhir}}",+ "retentionNote": "Hanya agen internal. Eksekusi yang lebih lama dari masa simpan trace instance tidak dihitung.",+ "noComparison": "Tidak ada pembanding",+ "vsPrevious": "sebelumnya {value}",+ "deletedAgent": "Agen dihapus",+ "deletedProject": "Proyek dihapus",+ "allProjects": "Semua proyek",+ "totalTokens": "Total token",+ "totalCost": "Total biaya",+ "stats": {+ "cost": "Biaya model",+ "tokens": "Token",+ "runs": "Eksekusi",+ "errors": "Eksekusi gagal"+ },+ "measure": {+ "tokens": "Token",+ "cost": "Biaya"+ },+ "series": {+ "input": "Input",+ "output": "Output"+ },+ "models": {+ "title": "Per model",+ "description": "Token dan biaya tiap model.",+ "model": "Model",+ "input": "Input",+ "output": "Output",+ "cost": "Biaya",+ "empty": "Tidak ada panggilan model pada periode ini"+ },+ "byAgent": {+ "title": "Per agen",+ "description": "Yang dipakai tiap agen.",+ "empty": "Tidak ada eksekusi agen pada periode ini"+ },+ "byProject": {+ "title": "Per proyek",+ "description": "Yang dipakai agen di tiap proyek.",+ "empty": "Tidak ada eksekusi agen pada periode ini"+ },+ "byTeam": {+ "title": "Per tim",+ "description": "Yang dipakai agen tiap tim.",+ "empty": "Tidak ada eksekusi agen pada periode ini"+ },+ "overTime": {+ "title": "Dari waktu ke waktu",+ "description": "Token dan biaya selama periode.",+ "empty": "Tidak ada penggunaan pada periode ini"+ },+ "preview": {+ "title": "Lebih banyak di Cloud dan Pro",+ "description": "Biaya per orang dan pemicu, durasi eksekusi, dan panggilan alat. Tersedia di Cloud dan Pro self-hosted.",+ "hide": "Sembunyikan",+ "show": "Tampilkan",+ "byPerson": {+ "title": "Per orang",+ "description": "Siapa yang menjalankan agen lewat chat atau mention."+ },+ "byTrigger": {+ "title": "Per pemicu",+ "description": "Chat, mention, jadwal, atau peristiwa tugas."+ },+ "bySchedule": {+ "title": "Per jadwal",+ "description": "Biaya tiap jadwal."+ },+ "tools": {+ "title": "Alat",+ "description": "Panggilan alat dan berapa yang gagal."+ },+ "latency": {+ "title": "Durasi eksekusi",+ "description": "Median dan persentil ke-95 per hari."+ }+ }+}diff --git a/apps/web/messages/id/common.json b/apps/web/messages/id/common.jsonindex 198b2aa3..b26deb6f 100644--- a/apps/web/messages/id/common.json+++ b/apps/web/messages/id/common.json@@ -211,5 +211,6 @@"page": "Halaman {number}","perPage": "per halaman","range": "{first}-{last} dari {total}"- }+ },+ "aboutCloudAndPro": "Pelajari Cloud dan Pro"}diff --git a/apps/web/messages/id/god.json b/apps/web/messages/id/god.jsonindex 0cf52690..cdeb7901 100644--- a/apps/web/messages/id/god.json+++ b/apps/web/messages/id/god.json@@ -164,7 +164,13 @@"workspacesSaved": "Pengaturan workspace disimpan","workspaces": "Workspace","personalWorkspaces": "Workspace untuk setiap orang",- "personalWorkspacesHint": "Setiap akun mendapat workspace sendiri dengan nama pemiliknya. Jika nonaktif, orang hanya bekerja di workspace tempat mereka ditambahkan."+ "personalWorkspacesHint": "Setiap akun mendapat workspace sendiri dengan nama pemiliknya. Jika nonaktif, orang hanya bekerja di workspace tempat mereka ditambahkan.",+ "agents": "Agen",+ "agentsSaved": "Pengaturan agen disimpan",+ "traceRetention": "Simpan trace eksekusi",+ "traceRetentionHint": "Setiap eksekusi agen mencatat panggilan ke model dan alat. Dasbor penggunaan hanya menghitung eksekusi yang masih disimpan.",+ "traceDays": "{days} hari",+ "traceForever": "Selamanya"},"authentication": {"saved": "Pengaturan autentikasi disimpan",diff --git a/apps/web/messages/id/permissions.json b/apps/web/messages/id/permissions.jsonindex 0fcbfadc..4f1b48e8 100644--- a/apps/web/messages/id/permissions.json+++ b/apps/web/messages/id/permissions.json@@ -17,6 +17,7 @@"integrations": "Integrasi","agent_skills": "Keahlian agen","agent_tools": "Alat agen",+ "agent_usage": "Penggunaan agen","custom_fields": "Bidang kustom","issue_templates": "Templat issue","workflow_config": "Konfigurasi alur kerja",diff --git a/apps/web/messages/id/sections.json b/apps/web/messages/id/sections.jsonindex 32fece82..9203f7e7 100644--- a/apps/web/messages/id/sections.json+++ b/apps/web/messages/id/sections.json@@ -25,7 +25,7 @@},"general": {"label": "Umum",- "description": "Workspace pribadi dan pengaturan bawaan untuk proyek baru."+ "description": "Workspace pribadi, pengaturan bawaan untuk proyek baru, dan trace agen."},"authentication": {"label": "Autentikasi",diff --git a/apps/web/messages/id/settings.json b/apps/web/messages/id/settings.jsonindex d248cdac..30d70207 100644--- a/apps/web/messages/id/settings.json+++ b/apps/web/messages/id/settings.json@@ -46,6 +46,8 @@"runsSuffix": "{description} UTC","statusActive": "Aktif","statusPaused": "Dijeda",+ "unavailable": "Perlu Cloud atau Pro",+ "unavailableHint": "Dibuat dengan Cloud atau Pro. Disimpan apa adanya, tetapi tidak berjalan di sini.","viewTask": "Lihat tugas","noRunsShort": "Belum pernah dijalankan","pause": "Jeda jadwal",diff --git a/apps/web/messages/id/teams.json b/apps/web/messages/id/teams.jsonindex 69e2bc10..e98d106e 100644--- a/apps/web/messages/id/teams.json+++ b/apps/web/messages/id/teams.json@@ -51,6 +51,10 @@"agents": {"title": "Agen AI","description": "Agen AI yang dimiliki tim ini, dan proyek tempat mereka bekerja."+ },+ "analytics": {+ "title": "Penggunaan",+ "description": "Biaya model yang dipakai agen tim, per agen, proyek, dan hari."}},"info": {@@ -658,6 +662,11 @@"title": "Hapus {name}?","description": "<strong>{name}</strong> dan timnya akan dihapus. Orang-orang tetap memiliki akun dan tim lain mereka. Tindakan ini tidak dapat dibatalkan.","deleted": "Workspace dihapus"- }+ },+ "agentUsage": {+ "title": "Penggunaan AI",+ "description": "Biaya model yang dipakai agen semua tim."+ },+ "settingsGroup": "Pengaturan"}}diff --git a/apps/web/messages/pt-BR/agentAnalytics.json b/apps/web/messages/pt-BR/agentAnalytics.jsonnew file mode 100644index 00000000..e4256cd1--- /dev/null+++ b/apps/web/messages/pt-BR/agentAnalytics.json@@ -0,0 +1,80 @@+{+ "window": "{days, plural, =1 {Últimas 24 horas} other {Últimos # dias}}",+ "retentionNote": "Apenas agentes internos. Execuções mais antigas que a retenção de rastros da instância não são contadas.",+ "noComparison": "Nada para comparar",+ "vsPrevious": "contra {value} antes",+ "deletedAgent": "Agente excluído",+ "deletedProject": "Projeto excluído",+ "allProjects": "Todos os projetos",+ "totalTokens": "Total de tokens",+ "totalCost": "Custo total",+ "stats": {+ "cost": "Custo dos modelos",+ "tokens": "Tokens",+ "runs": "Execuções",+ "errors": "Execuções com falha"+ },+ "measure": {+ "tokens": "Tokens",+ "cost": "Custo"+ },+ "series": {+ "input": "Entrada",+ "output": "Saída"+ },+ "models": {+ "title": "Por modelo",+ "description": "Tokens e custo de cada modelo.",+ "model": "Modelo",+ "input": "Entrada",+ "output": "Saída",+ "cost": "Custo",+ "empty": "Nenhuma chamada de modelo neste período"+ },+ "byAgent": {+ "title": "Por agente",+ "description": "Quanto cada agente usou.",+ "empty": "Nenhuma execução de agente neste período"+ },+ "byProject": {+ "title": "Por projeto",+ "description": "Quanto os agentes usaram em cada projeto.",+ "empty": "Nenhuma execução de agente neste período"+ },+ "byTeam": {+ "title": "Por equipe",+ "description": "Quanto os agentes de cada equipe usaram.",+ "empty": "Nenhuma execução de agente neste período"+ },+ "overTime": {+ "title": "Ao longo do tempo",+ "description": "Tokens e custo no período.",+ "empty": "Nenhum consumo neste período"+ },+ "preview": {+ "title": "Mais no Cloud e no Pro",+ "description": "Gastos por pessoa e gatilho, duração das execuções e chamadas de ferramentas. Disponível no Cloud e no Pro auto-hospedado.",+ "hide": "Ocultar",+ "show": "Mostrar",+ "byPerson": {+ "title": "Por pessoa",+ "description": "Quem iniciou execuções em um chat ou com uma menção."+ },+ "byTrigger": {+ "title": "Por gatilho",+ "description": "Chat, menção, agendamento ou evento de tarefa."+ },+ "bySchedule": {+ "title": "Por agendamento",+ "description": "Quanto cada agendamento gastou."+ },+ "tools": {+ "title": "Ferramentas",+ "description": "Chamadas de ferramentas e quantas falharam."+ },+ "latency": {+ "title": "Duração",+ "description": "Mediana e percentil 95 por dia."+ }+ }+}diff --git a/apps/web/messages/pt-BR/common.json b/apps/web/messages/pt-BR/common.jsonindex 4b50efc8..b151c958 100644--- a/apps/web/messages/pt-BR/common.json+++ b/apps/web/messages/pt-BR/common.json@@ -211,5 +211,6 @@"page": "Página {number}","perPage": "por página","range": "{first}-{last} de {total}"- }+ },+ "aboutCloudAndPro": "Saiba mais sobre Cloud e Pro"}diff --git a/apps/web/messages/pt-BR/god.json b/apps/web/messages/pt-BR/god.jsonindex 4a8d9a2e..aa0b7061 100644--- a/apps/web/messages/pt-BR/god.json+++ b/apps/web/messages/pt-BR/god.json@@ -164,7 +164,13 @@"workspacesSaved": "Configurações de workspace salvas","workspaces": "Workspaces","personalWorkspaces": "Um workspace para cada pessoa",- "personalWorkspacesHint": "Cada conta recebe um workspace próprio com o nome da pessoa. Desativado, as pessoas trabalham apenas nos workspaces aos quais foram adicionadas."+ "personalWorkspacesHint": "Cada conta recebe um workspace próprio com o nome da pessoa. Desativado, as pessoas trabalham apenas nos workspaces aos quais foram adicionadas.",+ "agents": "Agentes",+ "agentsSaved": "Configurações de agentes salvas",+ "traceRetention": "Manter rastros de execução",+ "traceRetentionHint": "Cada execução de agente registra as chamadas ao modelo e às ferramentas. Os painéis de consumo contam só as execuções mantidas.",+ "traceDays": "{days, plural, one {# dia} other {# dias}}",+ "traceForever": "Sempre"},"authentication": {"saved": "Configurações de autenticação salvas",diff --git a/apps/web/messages/pt-BR/permissions.json b/apps/web/messages/pt-BR/permissions.jsonindex 07224ccc..d270a907 100644--- a/apps/web/messages/pt-BR/permissions.json+++ b/apps/web/messages/pt-BR/permissions.json@@ -17,6 +17,7 @@"integrations": "Integrações","agent_skills": "Habilidades de agente","agent_tools": "Ferramentas de agente",+ "agent_usage": "Consumo dos agentes","custom_fields": "Campos personalizados","issue_templates": "Modelos de issue","workflow_config": "Configuração de fluxo de trabalho",diff --git a/apps/web/messages/pt-BR/sections.json b/apps/web/messages/pt-BR/sections.jsonindex 19d00d49..b0d59ec9 100644--- a/apps/web/messages/pt-BR/sections.json+++ b/apps/web/messages/pt-BR/sections.json@@ -25,7 +25,7 @@},"general": {"label": "Geral",- "description": "Workspaces pessoais e padrões para novos projetos."+ "description": "Workspaces pessoais, padrões para novos projetos e rastros de agentes."},"authentication": {"label": "Autenticação",diff --git a/apps/web/messages/pt-BR/settings.json b/apps/web/messages/pt-BR/settings.jsonindex 918355aa..14b76169 100644--- a/apps/web/messages/pt-BR/settings.json+++ b/apps/web/messages/pt-BR/settings.json@@ -46,6 +46,8 @@"runsSuffix": "{description} UTC","statusActive": "Ativo","statusPaused": "Pausado",+ "unavailable": "Requer Cloud ou Pro",+ "unavailableHint": "Criado com Cloud ou Pro. Mantido como está, mas não roda aqui.","viewTask": "Ver tarefa","noRunsShort": "Nenhuma execução ainda","pause": "Pausar agendamento",diff --git a/apps/web/messages/pt-BR/teams.json b/apps/web/messages/pt-BR/teams.jsonindex 9e3df839..886fb0f5 100644--- a/apps/web/messages/pt-BR/teams.json+++ b/apps/web/messages/pt-BR/teams.json@@ -51,6 +51,10 @@"agents": {"title": "Agentes de IA","description": "Os agentes de IA que este time possui e os projetos em que cada um trabalha."+ },+ "analytics": {+ "title": "Consumo",+ "description": "Quanto os agentes da equipe gastaram com modelos, por agente, projeto e dia."}},"info": {@@ -658,6 +662,11 @@"title": "Excluir {name}?","description": "<strong>{name}</strong> e os times dele são excluídos. As pessoas mantêm suas contas e seus outros times. Isso não pode ser desfeito.","deleted": "Workspace excluído"- }+ },+ "agentUsage": {+ "title": "Consumo de IA",+ "description": "Quanto os agentes de todas as equipes gastaram com modelos."+ },+ "settingsGroup": "Configurações"}}diff --git a/apps/web/messages/ru/agentAnalytics.json b/apps/web/messages/ru/agentAnalytics.jsonnew file mode 100644index 00000000..7da30087--- /dev/null+++ b/apps/web/messages/ru/agentAnalytics.json@@ -0,0 +1,80 @@+{+ "window": "{days, plural, =1 {За 24 часа} one {За # день} few {За # дня} other {За # дней}}",+ "retentionNote": "Только внутренние агенты. Запуски старше срока хранения трассировок в инстансе не учитываются.",+ "noComparison": "Не с чем сравнить",+ "vsPrevious": "было {value}",+ "deletedAgent": "Удалённый агент",+ "deletedProject": "Удалённый проект",+ "allProjects": "Все проекты",+ "totalTokens": "Всего токенов",+ "totalCost": "Всего",+ "stats": {+ "cost": "Стоимость моделей",+ "tokens": "Токены",+ "runs": "Запуски",+ "errors": "Неудачные запуски"+ },+ "measure": {+ "tokens": "Токены",+ "cost": "Стоимость"+ },+ "series": {+ "input": "Ввод",+ "output": "Вывод"+ },+ "models": {+ "title": "По моделям",+ "description": "Токены и стоимость каждой модели.",+ "model": "Модель",+ "input": "Ввод",+ "output": "Вывод",+ "cost": "Стоимость",+ "empty": "За период не было вызовов моделей"+ },+ "byAgent": {+ "title": "По агентам",+ "description": "Сколько использовал каждый агент.",+ "empty": "За период агенты не запускались"+ },+ "byProject": {+ "title": "По проектам",+ "description": "Сколько агенты использовали в каждом проекте.",+ "empty": "За период агенты не запускались"+ },+ "byTeam": {+ "title": "По командам",+ "description": "Сколько использовали агенты каждой команды.",+ "empty": "За период агенты не запускались"+ },+ "overTime": {+ "title": "По времени",+ "description": "Токены и стоимость за период.",+ "empty": "За период нет расходов"+ },+ "preview": {+ "title": "Больше в Cloud и Pro",+ "description": "Расходы по людям и триггерам, время запусков и вызовы инструментов. Доступно в Cloud и в Pro-версии для своего сервера.",+ "hide": "Скрыть",+ "show": "Показать",+ "byPerson": {+ "title": "По людям",+ "description": "Кто запускал агентов в чате или упоминанием."+ },+ "byTrigger": {+ "title": "По триггерам",+ "description": "Чат, упоминание, расписание или событие задачи."+ },+ "bySchedule": {+ "title": "По расписаниям",+ "description": "Сколько потратило каждое расписание."+ },+ "tools": {+ "title": "Инструменты",+ "description": "Вызовы инструментов и сколько из них завершились ошибкой."+ },+ "latency": {+ "title": "Время запуска",+ "description": "Медиана и 95-й перцентиль по дням."+ }+ }+}diff --git a/apps/web/messages/ru/common.json b/apps/web/messages/ru/common.jsonindex af03dde7..5a38d97a 100644--- a/apps/web/messages/ru/common.json+++ b/apps/web/messages/ru/common.json@@ -211,5 +211,6 @@"page": "Страница {number}","perPage": "на странице","range": "{first}-{last} из {total}"- }+ },+ "aboutCloudAndPro": "Подробнее о Cloud и Pro"}diff --git a/apps/web/messages/ru/god.json b/apps/web/messages/ru/god.jsonindex 84dfb50f..e9b7a4b8 100644--- a/apps/web/messages/ru/god.json+++ b/apps/web/messages/ru/god.json@@ -164,7 +164,13 @@"workspacesSaved": "Настройки воркспейсов сохранены","workspaces": "Воркспейсы","personalWorkspaces": "Воркспейс для каждого",- "personalWorkspacesHint": "Каждый аккаунт получает свой воркспейс с именем человека. Если выключено, люди работают только в воркспейсах, куда их добавили."+ "personalWorkspacesHint": "Каждый аккаунт получает свой воркспейс с именем человека. Если выключено, люди работают только в воркспейсах, куда их добавили.",+ "agents": "Агенты",+ "agentsSaved": "Настройки агентов сохранены",+ "traceRetention": "Хранить трассировки запусков",+ "traceRetentionHint": "Каждый запуск агента записывает вызовы модели и инструментов. Дашборды расходов учитывают только сохранённые запуски.",+ "traceDays": "{days, plural, one {# день} few {# дня} other {# дней}}",+ "traceForever": "Всегда"},"authentication": {"saved": "Настройки аутентификации сохранены",diff --git a/apps/web/messages/ru/permissions.json b/apps/web/messages/ru/permissions.jsonindex b29658d4..2134a3a7 100644--- a/apps/web/messages/ru/permissions.json+++ b/apps/web/messages/ru/permissions.json@@ -17,6 +17,7 @@"integrations": "Интеграции","agent_skills": "Навыки агентов","agent_tools": "Инструменты агентов",+ "agent_usage": "Расходы агентов","custom_fields": "Пользовательские поля","issue_templates": "Шаблоны задач","workflow_config": "Настройки рабочего процесса",diff --git a/apps/web/messages/ru/sections.json b/apps/web/messages/ru/sections.jsonindex 7b7dbfdc..2a364627 100644--- a/apps/web/messages/ru/sections.json+++ b/apps/web/messages/ru/sections.json@@ -25,7 +25,7 @@},"general": {"label": "Общее",- "description": "Свои воркспейсы и настройки по умолчанию для новых проектов."+ "description": "Свои воркспейсы, настройки по умолчанию для новых проектов и трассировки агентов."},"authentication": {"label": "Аутентификация",diff --git a/apps/web/messages/ru/settings.json b/apps/web/messages/ru/settings.jsonindex 89168c2b..54051fa5 100644--- a/apps/web/messages/ru/settings.json+++ b/apps/web/messages/ru/settings.json@@ -46,6 +46,8 @@"runsSuffix": "{description} UTC","statusActive": "Активное","statusPaused": "На паузе",+ "unavailable": "Нужен Cloud или Pro",+ "unavailableHint": "Создано в Cloud или Pro. Сохранено как есть, но здесь не запускается.","viewTask": "Посмотреть задачу","noRunsShort": "Запусков пока нет","pause": "Приостановить расписание",diff --git a/apps/web/messages/ru/teams.json b/apps/web/messages/ru/teams.jsonindex 3a227d0d..4743a639 100644--- a/apps/web/messages/ru/teams.json+++ b/apps/web/messages/ru/teams.json@@ -51,6 +51,10 @@"agents": {"title": "ИИ-агенты","description": "ИИ-агенты команды и проекты, в которых работает каждый из них."+ },+ "analytics": {+ "title": "Расходы",+ "description": "Сколько потратили агенты команды на модели: по агентам, проектам и дням."}},"info": {@@ -658,6 +662,11 @@"title": "Удалить {name}?","description": "<strong>{name}</strong> и его команды будут удалены. Люди сохранят свои аккаунты и другие команды. Это нельзя отменить.","deleted": "Воркспейс удалён"- }+ },+ "agentUsage": {+ "title": "Расходы на ИИ",+ "description": "Сколько потратили на модели агенты всех команд."+ },+ "settingsGroup": "Настройки"}}diff --git a/apps/web/messages/uk/agentAnalytics.json b/apps/web/messages/uk/agentAnalytics.jsonnew file mode 100644index 00000000..b80b8664--- /dev/null+++ b/apps/web/messages/uk/agentAnalytics.json@@ -0,0 +1,80 @@+{+ "window": "{days, plural, =1 {За 24 години} one {За # день} few {За # дні} other {За # днів}}",+ "retentionNote": "Лише внутрішні агенти. Запуски, старші за термін зберігання трасувань в інстансі, не враховуються.",+ "noComparison": "Немає з чим порівняти",+ "vsPrevious": "було {value}",+ "deletedAgent": "Видалений агент",+ "deletedProject": "Видалений проєкт",+ "allProjects": "Усі проєкти",+ "totalTokens": "Усього токенів",+ "totalCost": "Усього",+ "stats": {+ "cost": "Вартість моделей",+ "tokens": "Токени",+ "runs": "Запуски",+ "errors": "Невдалі запуски"+ },+ "measure": {+ "tokens": "Токени",+ "cost": "Вартість"+ },+ "series": {+ "input": "Введення",+ "output": "Виведення"+ },+ "models": {+ "title": "За моделями",+ "description": "Токени та вартість кожної моделі.",+ "model": "Модель",+ "input": "Введення",+ "output": "Виведення",+ "cost": "Вартість",+ "empty": "За період не було викликів моделей"+ },+ "byAgent": {+ "title": "За агентами",+ "description": "Скільки використав кожен агент.",+ "empty": "За період агенти не запускалися"+ },+ "byProject": {+ "title": "За проєктами",+ "description": "Скільки агенти використали в кожному проєкті.",+ "empty": "За період агенти не запускалися"+ },+ "byTeam": {+ "title": "За командами",+ "description": "Скільки використали агенти кожної команди.",+ "empty": "За період агенти не запускалися"+ },+ "overTime": {+ "title": "У часі",+ "description": "Токени та вартість за період.",+ "empty": "За період немає витрат"+ },+ "preview": {+ "title": "Більше в Cloud і Pro",+ "description": "Витрати за людьми й тригерами, час запусків і виклики інструментів. Доступно в Cloud і в Pro-версії для власного сервера.",+ "hide": "Сховати",+ "show": "Показати",+ "byPerson": {+ "title": "За людьми",+ "description": "Хто запускав агентів у чаті або згадкою."+ },+ "byTrigger": {+ "title": "За тригерами",+ "description": "Чат, згадка, розклад або подія задачі."+ },+ "bySchedule": {+ "title": "За розкладами",+ "description": "Скільки витратив кожен розклад."+ },+ "tools": {+ "title": "Інструменти",+ "description": "Виклики інструментів і скільки з них завершилися помилкою."+ },+ "latency": {+ "title": "Час запуску",+ "description": "Медіана і 95-й перцентиль по днях."+ }+ }+}diff --git a/apps/web/messages/uk/common.json b/apps/web/messages/uk/common.jsonindex 5a641e01..87bb5d44 100644--- a/apps/web/messages/uk/common.json+++ b/apps/web/messages/uk/common.json@@ -211,5 +211,6 @@"page": "Сторінка {number}","perPage": "на сторінці","range": "{first}-{last} з {total}"- }+ },+ "aboutCloudAndPro": "Докладніше про Cloud і Pro"}diff --git a/apps/web/messages/uk/god.json b/apps/web/messages/uk/god.jsonindex 36265262..e955170b 100644--- a/apps/web/messages/uk/god.json+++ b/apps/web/messages/uk/god.json@@ -164,7 +164,13 @@"workspacesSaved": "Налаштування воркспейсів збережено","workspaces": "Воркспейси","personalWorkspaces": "Воркспейс для кожного",- "personalWorkspacesHint": "Кожен акаунт отримує свій воркспейс з ім'ям людини. Якщо вимкнено, люди працюють лише у воркспейсах, до яких їх додали."+ "personalWorkspacesHint": "Кожен акаунт отримує свій воркспейс з ім'ям людини. Якщо вимкнено, люди працюють лише у воркспейсах, до яких їх додали.",+ "agents": "Агенти",+ "agentsSaved": "Налаштування агентів збережено",+ "traceRetention": "Зберігати трасування запусків",+ "traceRetentionHint": "Кожен запуск агента записує виклики моделі та інструментів. Дашборди витрат враховують лише збережені запуски.",+ "traceDays": "{days, plural, one {# день} few {# дні} other {# днів}}",+ "traceForever": "Завжди"},"authentication": {"saved": "Налаштування автентифікації збережено",diff --git a/apps/web/messages/uk/permissions.json b/apps/web/messages/uk/permissions.jsonindex 0a16b07b..00788b61 100644--- a/apps/web/messages/uk/permissions.json+++ b/apps/web/messages/uk/permissions.json@@ -17,6 +17,7 @@"integrations": "Інтеграції","agent_skills": "Навички агентів","agent_tools": "Інструменти агентів",+ "agent_usage": "Витрати агентів","custom_fields": "Власні поля","issue_templates": "Шаблони задач","workflow_config": "Налаштування робочого процесу",diff --git a/apps/web/messages/uk/sections.json b/apps/web/messages/uk/sections.jsonindex 3b05ab5d..b33a8768 100644--- a/apps/web/messages/uk/sections.json+++ b/apps/web/messages/uk/sections.json@@ -25,7 +25,7 @@},"general": {"label": "Загальне",- "description": "Власні воркспейси та налаштування за замовчуванням для нових проєктів."+ "description": "Власні воркспейси, налаштування за замовчуванням для нових проєктів і трасування агентів."},"authentication": {"label": "Автентифікація",diff --git a/apps/web/messages/uk/settings.json b/apps/web/messages/uk/settings.jsonindex 9cbd820b..aa928b1e 100644--- a/apps/web/messages/uk/settings.json+++ b/apps/web/messages/uk/settings.json@@ -46,6 +46,8 @@"runsSuffix": "{description} UTC","statusActive": "Активний","statusPaused": "На паузі",+ "unavailable": "Потрібен Cloud або Pro",+ "unavailableHint": "Створено в Cloud або Pro. Збережено як є, але тут не запускається.","viewTask": "Переглянути задачу","noRunsShort": "Запусків ще немає","pause": "Призупинити розклад",diff --git a/apps/web/messages/uk/teams.json b/apps/web/messages/uk/teams.jsonindex 087a97dd..a90aa87e 100644--- a/apps/web/messages/uk/teams.json+++ b/apps/web/messages/uk/teams.json@@ -51,6 +51,10 @@"agents": {"title": "ШІ-агенти","description": "ШІ-агенти команди та проєкти, у яких працює кожен із них."+ },+ "analytics": {+ "title": "Витрати",+ "description": "Скільки витратили агенти команди на моделі: за агентами, проєктами та днями."}},"info": {@@ -658,6 +662,11 @@"title": "Видалити {name}?","description": "<strong>{name}</strong> і його команди буде видалено. Люди збережуть свої акаунти та інші команди. Це не можна скасувати.","deleted": "Воркспейс видалено"- }+ },+ "agentUsage": {+ "title": "Витрати на ШІ",+ "description": "Скільки витратили на моделі агенти всіх команд."+ },+ "settingsGroup": "Налаштування"}}diff --git a/apps/web/messages/zh-CN/agentAnalytics.json b/apps/web/messages/zh-CN/agentAnalytics.jsonnew file mode 100644index 00000000..f78d3e8a--- /dev/null+++ b/apps/web/messages/zh-CN/agentAnalytics.json@@ -0,0 +1,80 @@+{+ "window": "{days, plural, =1 {最近 24 小时} other {最近 # 天}}",+ "retentionNote": "仅统计内部代理。早于实例追踪保留期的运行不计入。",+ "noComparison": "没有可对比的数据",+ "vsPrevious": "之前为 {value}",+ "deletedAgent": "已删除的代理",+ "deletedProject": "已删除的项目",+ "allProjects": "所有项目",+ "totalTokens": "Token 总数",+ "totalCost": "总花费",+ "stats": {+ "cost": "模型花费",+ "tokens": "Token",+ "runs": "运行",+ "errors": "失败的运行"+ },+ "measure": {+ "tokens": "Token",+ "cost": "花费"+ },+ "series": {+ "input": "输入",+ "output": "输出"+ },+ "models": {+ "title": "按模型",+ "description": "每个模型的 Token 与花费。",+ "model": "模型",+ "input": "输入",+ "output": "输出",+ "cost": "花费",+ "empty": "此期间没有模型调用"+ },+ "byAgent": {+ "title": "按代理",+ "description": "每个代理的用量。",+ "empty": "此期间没有代理运行"+ },+ "byProject": {+ "title": "按项目",+ "description": "代理在每个项目中的用量。",+ "empty": "此期间没有代理运行"+ },+ "byTeam": {+ "title": "按团队",+ "description": "每个团队的代理用量。",+ "empty": "此期间没有代理运行"+ },+ "overTime": {+ "title": "随时间",+ "description": "此期间的 Token 与花费。",+ "empty": "此期间没有用量"+ },+ "preview": {+ "title": "Cloud 和 Pro 中的更多内容",+ "description": "按人员和触发方式的花费、运行时长和工具调用。可在 Cloud 和自托管 Pro 版中使用。",+ "hide": "隐藏",+ "show": "显示",+ "byPerson": {+ "title": "按人员",+ "description": "谁在聊天中或通过提及启动了运行。"+ },+ "byTrigger": {+ "title": "按触发方式",+ "description": "聊天、提及、计划或任务事件。"+ },+ "bySchedule": {+ "title": "按计划",+ "description": "每个计划的花费。"+ },+ "tools": {+ "title": "工具",+ "description": "工具调用次数及失败次数。"+ },+ "latency": {+ "title": "运行时长",+ "description": "每天的中位数和第 95 百分位。"+ }+ }+}diff --git a/apps/web/messages/zh-CN/common.json b/apps/web/messages/zh-CN/common.jsonindex 5e31c836..8a33858c 100644--- a/apps/web/messages/zh-CN/common.json+++ b/apps/web/messages/zh-CN/common.json@@ -211,5 +211,6 @@"page": "第 {number} 页","perPage": "每页","range": "第 {first}-{last} 项,共 {total} 项"- }+ },+ "aboutCloudAndPro": "了解 Cloud 和 Pro"}diff --git a/apps/web/messages/zh-CN/god.json b/apps/web/messages/zh-CN/god.jsonindex 936fe03f..11c1c06f 100644--- a/apps/web/messages/zh-CN/god.json+++ b/apps/web/messages/zh-CN/god.json@@ -164,7 +164,13 @@"workspacesSaved": "工作区设置已保存","workspaces": "工作区","personalWorkspaces": "每人一个工作区",- "personalWorkspacesHint": "每个账户都会获得一个以其姓名命名的专属工作区。关闭后,成员只能在被添加到的工作区中工作。"+ "personalWorkspacesHint": "每个账户都会获得一个以其姓名命名的专属工作区。关闭后,成员只能在被添加到的工作区中工作。",+ "agents": "代理",+ "agentsSaved": "代理设置已保存",+ "traceRetention": "保留运行追踪",+ "traceRetentionHint": "代理的每次运行都会记录模型和工具调用。用量面板只统计仍保留的运行。",+ "traceDays": "{days} 天",+ "traceForever": "永久"},"authentication": {"saved": "身份验证设置已保存",diff --git a/apps/web/messages/zh-CN/permissions.json b/apps/web/messages/zh-CN/permissions.jsonindex 0ed88c21..10a227bf 100644--- a/apps/web/messages/zh-CN/permissions.json+++ b/apps/web/messages/zh-CN/permissions.json@@ -17,6 +17,7 @@"integrations": "集成","agent_skills": "代理技能","agent_tools": "代理工具",+ "agent_usage": "代理用量","custom_fields": "自定义字段","issue_templates": "问题模板","workflow_config": "工作流配置",diff --git a/apps/web/messages/zh-CN/sections.json b/apps/web/messages/zh-CN/sections.jsonindex e3a02ce3..acd89423 100644--- a/apps/web/messages/zh-CN/sections.json+++ b/apps/web/messages/zh-CN/sections.json@@ -25,7 +25,7 @@},"general": {"label": "通用",- "description": "个人工作区和新建项目的默认设置。"+ "description": "个人工作区、新建项目的默认设置和代理追踪。"},"authentication": {"label": "身份验证",diff --git a/apps/web/messages/zh-CN/settings.json b/apps/web/messages/zh-CN/settings.jsonindex a6f2cb1c..32f4e047 100644--- a/apps/web/messages/zh-CN/settings.json+++ b/apps/web/messages/zh-CN/settings.json@@ -46,6 +46,8 @@"runsSuffix": "{description} UTC","statusActive": "已启用","statusPaused": "已暂停",+ "unavailable": "需要 Cloud 或 Pro",+ "unavailableHint": "使用 Cloud 或 Pro 创建。按原样保留,但不会在此运行。","viewTask": "查看任务","noRunsShort": "暂无运行记录","pause": "暂停定时任务",diff --git a/apps/web/messages/zh-CN/teams.json b/apps/web/messages/zh-CN/teams.jsonindex 99720000..26f41576 100644--- a/apps/web/messages/zh-CN/teams.json+++ b/apps/web/messages/zh-CN/teams.json@@ -51,6 +51,10 @@"agents": {"title": "AI 代理","description": "该团队拥有的 AI 代理,以及各自工作的项目。"+ },+ "analytics": {+ "title": "用量",+ "description": "团队代理在模型上的花费,按代理、项目和日期统计。"}},"info": {@@ -658,6 +662,11 @@"title": "删除 {name}?","description": "<strong>{name}</strong> 及其团队将被删除。成员会保留自己的账户和其他团队。此操作无法撤销。","deleted": "工作区已删除"- }+ },+ "agentUsage": {+ "title": "AI 用量",+ "description": "所有团队的代理在模型上的花费。"+ },+ "settingsGroup": "设置"}}diff --git a/apps/web/src/app/[teamRef]/settings/analytics/page.tsx b/apps/web/src/app/[teamRef]/settings/analytics/page.tsxnew file mode 100644index 00000000..9993d0b2--- /dev/null+++ b/apps/web/src/app/[teamRef]/settings/analytics/page.tsx@@ -0,0 +1,9 @@+'use client';++import TeamAgentAnalyticsSection from '@/features/agent-analytics/TeamAgentAnalyticsSection';+import { useRouteTeam } from '@/features/teams/hooks/useRouteTeam';++export default function Page() {+ const team = useRouteTeam();+ return team && <TeamAgentAnalyticsSection teamId={team.id} />;+}diff --git a/apps/web/src/app/workspaces/[workspaceId]/agent-usage/page.tsx b/apps/web/src/app/workspaces/[workspaceId]/agent-usage/page.tsxnew file mode 100644index 00000000..3e7b5897--- /dev/null+++ b/apps/web/src/app/workspaces/[workspaceId]/agent-usage/page.tsx@@ -0,0 +1,9 @@+'use client';++import WorkspaceAgentAnalyticsSection from '@/features/agent-analytics/WorkspaceAgentAnalyticsSection';+import { useRouteWorkspaceId } from '@/features/teams/hooks/useRouteWorkspaceId';++export default function Page() {+ const workspaceId = useRouteWorkspaceId();+ return workspaceId !== null && <WorkspaceAgentAnalyticsSection workspaceId={workspaceId} />;+}diff --git a/apps/web/src/ce/AgentAnalyticsExtras.tsx b/apps/web/src/ce/AgentAnalyticsExtras.tsxnew file mode 100644index 00000000..9a0a7c73--- /dev/null+++ b/apps/web/src/ce/AgentAnalyticsExtras.tsx@@ -0,0 +1,11 @@+'use client';++import type { AgentAnalyticsScope } from '@/lib/api/endpoints/agentAnalytics';+import AgentAnalyticsPreview from '@/features/agent-analytics/components/AgentAnalyticsPreview';++// Below the panels of an agent dashboard, over the scope and the window it shows. A+// self-hosted instance shows what the hosted build and Pro add there; they render the+// panels themselves.+export default function AgentAnalyticsExtras(_props: { scope: AgentAnalyticsScope; days: number }) {+ return <AgentAnalyticsPreview />;+}diff --git a/apps/web/src/ce/WorkspaceRailActions.tsx b/apps/web/src/ce/WorkspaceRailActions.tsxindex cee37e3d..931131f7 100644--- a/apps/web/src/ce/WorkspaceRailActions.tsx+++ b/apps/web/src/ce/WorkspaceRailActions.tsx@@ -1,14 +1,16 @@-import { Plus } from 'lucide-react';+import { ExternalLink, Plus } from 'lucide-react';import { useTranslations } from 'next-intl';import { workspaceTileClass } from '@/components/layout/utils/workspaceTile';import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';+import { PRO_URL } from '@/utils/app';// Below the workspace tiles of a rail. On a self-hosted instance a person owns one// workspace, made at sign-up, so the button says where more are available; the hosted// build creates a workspace instead.export default function WorkspaceRailActions() {const t = useTranslations('teams.workspace');+ const tCommon = useTranslations('common');return (<Popover>@@ -25,6 +27,15 @@ export default function WorkspaceRailActions() {<PopoverContent side="right" align="start" className="w-64 text-sm"><p className="font-medium">{t('createUnavailableTitle')}</p><p className="mt-1 text-xs text-muted-foreground">{t('createUnavailableHint')}</p>+ <a+ href={PRO_URL}+ target="_blank"+ rel="noreferrer"+ className="mt-3 inline-flex items-center gap-1 text-xs font-medium hover:underline"+ >+ {tCommon('aboutCloudAndPro')}+ <ExternalLink className="size-3.5" />+ </a></PopoverContent></Popover>);diff --git a/apps/web/src/ce/index.ts b/apps/web/src/ce/index.tsindex ce1a2c87..335eeaa6 100644--- a/apps/web/src/ce/index.ts+++ b/apps/web/src/ce/index.ts@@ -1,6 +1,7 @@// What the `@/cloud` alias resolves to in this repository: the stubs a self-hosted// instance runs. The hosted build points the alias at its own module exporting the// same names, so a cloud-only part is imported from here and nowhere else.+export { default as AgentAnalyticsExtras } from './AgentAnalyticsExtras';export { default as GodSectionExtras } from './GodSectionExtras';export { default as godSections } from './godSections';export { cloudMessages, loadCloudMessages } from './messages';diff --git a/apps/web/src/features/agent-analytics/TeamAgentAnalyticsSection.tsx b/apps/web/src/features/agent-analytics/TeamAgentAnalyticsSection.tsxnew file mode 100644index 00000000..19b4c134--- /dev/null+++ b/apps/web/src/features/agent-analytics/TeamAgentAnalyticsSection.tsx@@ -0,0 +1,79 @@+'use client';++import { useState, type ReactNode } from 'react';+import { useTranslations } from 'next-intl';+import { AgentAnalyticsExtras } from '@/cloud';+import { useTeam, useTeamQuery } from '@/services/teams.service';+import { useTeamAgentAnalyticsQuery } from '@/services/agentAnalytics.service';+import SectionPageView from '@/components/common/page/SectionPageView';+import { Skeleton } from '@/components/ui/skeleton';+import AgentAnalyticsPanels from './components/AgentAnalyticsPanels';+import ProjectSelect from './components/ProjectSelect';+import RetentionHint from './components/RetentionHint';+import WindowSelect from './components/WindowSelect';++// What the team's agents spent. Its owner and managers read every project of the team;+// anyone else the projects where their role grants agent_usage, which the api+// narrows the figures to. Any one of those projects narrows the page further, picked+// in the header or from the breakdown by project.+export default function TeamAgentAnalyticsSection({ teamId }: { teamId: number }) {+ const t = useTranslations('teams.sections.analytics');+ const tCommon = useTranslations('common');+ const team = useTeam(teamId);+ const permissions = useTeamQuery(teamId).data?.permissions;+ const runsTeam = team?.role === 'owner' || team?.role === 'manager';+ const canRead = runsTeam || permissions?.agent_usage.read === true;+ const [days, setDays] = useState(30);+ const [projectId, setProjectId] = useState<number | null>(null);+ const { data } = useTeamAgentAnalyticsQuery(canRead ? teamId : null, days, projectId);+ // One project to read is no choice to make.+ const projects = data && data.readableProjects.length > 1 ? data.readableProjects : null;++ let content: ReactNode;+ if (!team || (!runsTeam && !permissions)) {+ content = <Skeleton className="h-72 w-full" />;+ } else if (!canRead) {+ content = <p className="text-sm text-muted-foreground">{tCommon('noSectionAccess')}</p>;+ } else if (!data) {+ content = (+ <div className="space-y-6">+ <Skeleton className="h-24 w-full" />+ <Skeleton className="h-64 w-full" />+ </div>+ );+ } else {+ content = (+ <div className="space-y-6">+ <AgentAnalyticsPanels+ data={data}+ onSelectProject={projects && projectId == null ? setProjectId : undefined}+ />+ <AgentAnalyticsExtras scope={{ teamId, projectId }} days={days} />+ </div>+ );+ }++ return (+ <SectionPageView+ title={t('title')}+ description={+ <>+ {t('description')} <RetentionHint />+ </>+ }+ wide+ actions={+ canRead ? (+ <>+ {projects && (+ <ProjectSelect projects={projects} value={projectId} onChange={setProjectId} />+ )}+ <WindowSelect value={days} onChange={setDays} />+ </>+ ) : undefined+ }+ >+ {content}+ </SectionPageView>+ );+}diff --git a/apps/web/src/features/agent-analytics/WorkspaceAgentAnalyticsSection.tsx b/apps/web/src/features/agent-analytics/WorkspaceAgentAnalyticsSection.tsxnew file mode 100644index 00000000..99ebeb27--- /dev/null+++ b/apps/web/src/features/agent-analytics/WorkspaceAgentAnalyticsSection.tsx@@ -0,0 +1,44 @@+'use client';++import { useState } from 'react';+import { useTranslations } from 'next-intl';+import { AgentAnalyticsExtras } from '@/cloud';+import { useWorkspaceAgentAnalyticsQuery } from '@/services/agentAnalytics.service';+import SectionPageView from '@/components/common/page/SectionPageView';+import { Skeleton } from '@/components/ui/skeleton';+import AgentAnalyticsPanels from './components/AgentAnalyticsPanels';+import RetentionHint from './components/RetentionHint';+import WindowSelect from './components/WindowSelect';++// What the agents of every team of the workspace spent, with the teams compared. Its+// owner and its admins read it, over every project.+export default function WorkspaceAgentAnalyticsSection({ workspaceId }: { workspaceId: number }) {+ const t = useTranslations('teams.workspace.agentUsage');+ const [days, setDays] = useState(30);+ const { data } = useWorkspaceAgentAnalyticsQuery(workspaceId, days);++ return (+ <SectionPageView+ title={t('title')}+ description={+ <>+ {t('description')} <RetentionHint />+ </>+ }+ wide+ actions={<WindowSelect value={days} onChange={setDays} />}+ >+ {data ? (+ <div className="space-y-6">+ <AgentAnalyticsPanels data={data} byTeam />+ <AgentAnalyticsExtras scope={{ workspaceId }} days={days} />+ </div>+ ) : (+ <div className="space-y-6">+ <Skeleton className="h-24 w-full" />+ <Skeleton className="h-64 w-full" />+ </div>+ )}+ </SectionPageView>+ );+}diff --git a/apps/web/src/features/agent-analytics/components/AgentAnalyticsPanels.tsx b/apps/web/src/features/agent-analytics/components/AgentAnalyticsPanels.tsxnew file mode 100644index 00000000..9d2925be--- /dev/null+++ b/apps/web/src/features/agent-analytics/components/AgentAnalyticsPanels.tsx@@ -0,0 +1,70 @@+import { useTranslations } from 'next-intl';+import { cn } from '@/lib/utils';+import type { AgentAnalytics } from '@/lib/api/endpoints/agentAnalytics';+import StatCards from './StatCards';+import TokensOverTime from './TokensOverTime';+import ModelUsage from './ModelUsage';+import UsageBreakdown from './UsageBreakdown';++// The panels of one window of the dashboard. With `onSelectProject` a project of the+// breakdown narrows the dashboard to it; `byTeam` compares the teams, for a dashboard+// over several.+export default function AgentAnalyticsPanels({+ data,+ onSelectProject,+ byTeam = false,+}: {+ data: AgentAnalytics;+ onSelectProject?: (projectId: number) => void;+ byTeam?: boolean;+}) {+ const t = useTranslations('agentAnalytics');++ return (+ <div className="space-y-6">+ <StatCards data={data} />+ <div className="grid gap-4 xl:grid-cols-2">+ <TokensOverTime data={data} />+ <ModelUsage data={data} />+ </div>+ <div className={cn('grid gap-4', byTeam ? 'xl:grid-cols-3' : 'xl:grid-cols-2')}>+ {byTeam && (+ <UsageBreakdown+ title={t('byTeam.title')}+ description={t('byTeam.description')}+ empty={t('byTeam.empty')}+ items={data.teams.map((team) => ({+ ...team,+ key: String(team.teamId),+ label: team.name,+ }))}+ total={data.totals}+ />+ )}+ <UsageBreakdown+ title={t('byAgent.title')}+ description={t('byAgent.description')}+ empty={t('byAgent.empty')}+ items={data.agents.map((agent) => ({+ ...agent,+ key: String(agent.agentId),+ label: agent.name || t('deletedAgent'),+ }))}+ total={data.totals}+ />+ <UsageBreakdown+ title={t('byProject.title')}+ description={t('byProject.description')}+ empty={t('byProject.empty')}+ items={data.projects.map((project) => ({+ ...project,+ key: String(project.projectId),+ label: project.name || t('deletedProject'),+ }))}+ total={data.totals}+ onSelect={onSelectProject && ((key) => onSelectProject(Number(key)))}+ />+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/agent-analytics/components/AgentAnalyticsPreview.tsx b/apps/web/src/features/agent-analytics/components/AgentAnalyticsPreview.tsxnew file mode 100644index 00000000..525053a1--- /dev/null+++ b/apps/web/src/features/agent-analytics/components/AgentAnalyticsPreview.tsx@@ -0,0 +1,69 @@+'use client';++import { ChevronDown, ExternalLink, Lock } from 'lucide-react';+import { useTranslations } from 'next-intl';+import { Button } from '@/components/ui/button';+import { usePersistedOpen } from '@/hooks/usePersistedOpen';+import { cn } from '@/lib/utils';+import { PRO_URL } from '@/utils/app';+import Panel from './Panel';++const PANELS = ['byPerson', 'byTrigger', 'bySchedule', 'tools', 'latency'] as const;++// Placeholder bar widths: what a panel's list looks like, holding no figure. They stay+// still, so they do not read as a panel that is loading.+const BARS = ['85%', '60%', '40%'];++// What the panels of the hosted build and Pro add to the dashboard, named and shown as+// empty shapes.+export default function AgentAnalyticsPreview() {+ const t = useTranslations('agentAnalytics.preview');+ const tCommon = useTranslations('common');+ const { open, toggle } = usePersistedOpen('agent-analytics-preview');++ return (+ <section className="space-y-4 rounded-xl border border-dashed p-5">+ <header className="flex items-center justify-between gap-4">+ <div className="min-w-0">+ <h3 className="flex items-center gap-2 text-sm font-semibold tracking-tight">+ <Lock className="size-4 shrink-0 text-muted-foreground" />+ {t('title')}+ </h3>+ <p className="mt-1 text-xs text-muted-foreground">{t('description')}</p>+ </div>+ <div className="flex shrink-0 flex-wrap items-center justify-end gap-1">+ <Button variant="ghost" size="sm" asChild>+ <a href={PRO_URL} target="_blank" rel="noreferrer">+ {tCommon('aboutCloudAndPro')}+ <ExternalLink />+ </a>+ </Button>+ <Button variant="ghost" size="sm" aria-expanded={open} onClick={toggle}>+ {open ? t('hide') : t('show')}+ <ChevronDown+ className={cn('transition-transform duration-150', open && 'rotate-180')}+ />+ </Button>+ </div>+ </header>+ {open && (+ <div className="grid gap-4 xl:grid-cols-2">+ {PANELS.map((panel) => (+ <Panel+ key={panel}+ title={t(`${panel}.title`)}+ description={t(`${panel}.description`)}+ className="opacity-70"+ >+ <div className="space-y-2" aria-hidden>+ {BARS.map((width) => (+ <div key={width} className="h-6 rounded-sm bg-muted" style={{ width }} />+ ))}+ </div>+ </Panel>+ ))}+ </div>+ )}+ </section>+ );+}diff --git a/apps/web/src/features/agent-analytics/components/BarList.tsx b/apps/web/src/features/agent-analytics/components/BarList.tsxnew file mode 100644index 00000000..fbd42c8d--- /dev/null+++ b/apps/web/src/features/agent-analytics/components/BarList.tsx@@ -0,0 +1,59 @@+import PanelEmpty from './PanelEmpty';++export interface BarRow {+ key: string;+ label: string;+ value: number;+ trailing: string;+}++// A share is taken against the largest row rather than the total, so a list of one still+// fills its track.+export default function BarList({+ rows,+ empty,+ onSelect,+}: {+ rows: BarRow[];+ empty: string;+ onSelect?: (key: string) => void;+}) {+ if (rows.length === 0) return <PanelEmpty label={empty} />;+ const max = Math.max(...rows.map((row) => row.value), 1);++ return (+ <div className="space-y-2">+ {rows.map((row) => {+ const content = (+ <>+ <div className="h-6 min-w-0 flex-1 rounded-sm bg-muted/40">+ <div+ className="flex h-full min-w-fit items-center rounded-sm bg-primary/85"+ style={{ width: `${(row.value / max) * 100}%` }}+ >+ <span className="truncate px-2 text-xs text-primary-foreground">{row.label}</span>+ </div>+ </div>+ <span className="w-20 shrink-0 text-end text-xs text-muted-foreground tabular-nums">+ {row.trailing}+ </span>+ </>+ );+ return onSelect ? (+ <button+ key={row.key}+ type="button"+ onClick={() => onSelect(row.key)}+ className="flex w-full items-center gap-3 rounded-sm text-start hover:opacity-80 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"+ >+ {content}+ </button>+ ) : (+ <div key={row.key} className="flex items-center gap-3">+ {content}+ </div>+ );+ })}+ </div>+ );+}diff --git a/apps/web/src/features/agent-analytics/components/MeasureTabs.tsx b/apps/web/src/features/agent-analytics/components/MeasureTabs.tsxnew file mode 100644index 00000000..9c1bd2b5--- /dev/null+++ b/apps/web/src/features/agent-analytics/components/MeasureTabs.tsx@@ -0,0 +1,22 @@+import { useTranslations } from 'next-intl';+import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';++export type Measure = 'tokens' | 'cost';++export default function MeasureTabs({+ value,+ onChange,+}: {+ value: Measure;+ onChange: (next: Measure) => void;+}) {+ const t = useTranslations('agentAnalytics');+ return (+ <Tabs value={value} onValueChange={(next) => onChange(next as Measure)}>+ <TabsList variant="line">+ <TabsTrigger value="tokens">{t('measure.tokens')}</TabsTrigger>+ <TabsTrigger value="cost">{t('measure.cost')}</TabsTrigger>+ </TabsList>+ </Tabs>+ );+}diff --git a/apps/web/src/features/agent-analytics/components/ModelUsage.tsx b/apps/web/src/features/agent-analytics/components/ModelUsage.tsxnew file mode 100644index 00000000..40211805--- /dev/null+++ b/apps/web/src/features/agent-analytics/components/ModelUsage.tsx@@ -0,0 +1,63 @@+import { useTranslations } from 'next-intl';+import type { AgentAnalytics } from '@/lib/api/endpoints/agentAnalytics';+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '@/components/ui/table';+import Panel from './Panel';+import PanelEmpty from './PanelEmpty';+import { formatCost, formatCount } from '../utils/format';++// The models the window's calls ran on, with what each read, wrote and cost. A model+// the price table does not name shows its tokens and no amount.+export default function ModelUsage({ data }: { data: AgentAnalytics }) {+ const t = useTranslations('agentAnalytics');+ return (+ <Panel+ title={t('models.title')}+ description={t('models.description')}+ value={formatCost(data.totals.cost)}+ valueLabel={t('totalCost')}+ >+ {data.models.length === 0 ? (+ <PanelEmpty label={t('models.empty')} />+ ) : (+ <div className="overflow-x-auto">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>{t('models.model')}</TableHead>+ <TableHead className="text-end">{t('models.input')}</TableHead>+ <TableHead className="text-end">{t('models.output')}</TableHead>+ <TableHead className="text-end">{t('models.cost')}</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {data.models.map((row) => (+ <TableRow key={`${row.provider}/${row.model}`}>+ <TableCell className="max-w-[220px]">+ <span className="block truncate font-medium">{row.model}</span>+ <span className="block truncate text-xs text-muted-foreground">+ {row.provider}+ </span>+ </TableCell>+ <TableCell className="text-end tabular-nums">+ {formatCount(row.inputTokens)}+ </TableCell>+ <TableCell className="text-end tabular-nums">+ {formatCount(row.outputTokens)}+ </TableCell>+ <TableCell className="text-end tabular-nums">{formatCost(row.cost)}</TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </div>+ )}+ </Panel>+ );+}diff --git a/apps/web/src/features/agent-analytics/components/Panel.tsx b/apps/web/src/features/agent-analytics/components/Panel.tsxnew file mode 100644index 00000000..f847b4de--- /dev/null+++ b/apps/web/src/features/agent-analytics/components/Panel.tsx@@ -0,0 +1,36 @@+import type { ReactNode } from 'react';+import { cn } from '@/lib/utils';++export default function Panel({+ title,+ description,+ value,+ valueLabel,+ className,+ children,+}: {+ title: string;+ description: string;+ value?: string;+ valueLabel?: string;+ className?: string;+ children: ReactNode;+}) {+ return (+ <section className={cn('flex min-w-0 flex-col rounded-xl bg-card p-5 shadow-sm', className)}>+ <header className="mb-4 flex items-start justify-between gap-4">+ <div className="min-w-0">+ <h3 className="truncate text-sm font-semibold tracking-tight">{title}</h3>+ <p className="text-xs text-muted-foreground">{description}</p>+ </div>+ {value !== undefined && (+ <div className="shrink-0 text-end">+ <p className="text-sm font-semibold tabular-nums">{value}</p>+ {valueLabel && <p className="text-xs text-muted-foreground">{valueLabel}</p>}+ </div>+ )}+ </header>+ <div className="min-w-0">{children}</div>+ </section>+ );+}diff --git a/apps/web/src/features/agent-analytics/components/PanelEmpty.tsx b/apps/web/src/features/agent-analytics/components/PanelEmpty.tsxnew file mode 100644index 00000000..c0a96fcd--- /dev/null+++ b/apps/web/src/features/agent-analytics/components/PanelEmpty.tsx@@ -0,0 +1,3 @@+export default function PanelEmpty({ label }: { label: string }) {+ return <p className="py-10 text-center text-sm text-muted-foreground">{label}</p>;+}diff --git a/apps/web/src/features/agent-analytics/components/ProjectSelect.tsx b/apps/web/src/features/agent-analytics/components/ProjectSelect.tsxnew file mode 100644index 00000000..03c04d43--- /dev/null+++ b/apps/web/src/features/agent-analytics/components/ProjectSelect.tsx@@ -0,0 +1,41 @@+import { useTranslations } from 'next-intl';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';++const ALL = 'all';++// The project a dashboard is narrowed to, or null for every project it reads.+export default function ProjectSelect({+ projects,+ value,+ onChange,+}: {+ projects: { projectId: number; name: string }[];+ value: number | null;+ onChange: (projectId: number | null) => void;+}) {+ const t = useTranslations('agentAnalytics');+ return (+ <Select+ value={value == null ? ALL : String(value)}+ onValueChange={(next) => onChange(next === ALL ? null : Number(next))}+ >+ <SelectTrigger className="w-48" size="sm">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value={ALL}>{t('allProjects')}</SelectItem>+ {projects.map((project) => (+ <SelectItem key={project.projectId} value={String(project.projectId)}>+ {project.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+}diff --git a/apps/web/src/features/agent-analytics/components/RetentionHint.tsx b/apps/web/src/features/agent-analytics/components/RetentionHint.tsxnew file mode 100644index 00000000..919a953a--- /dev/null+++ b/apps/web/src/features/agent-analytics/components/RetentionHint.tsx@@ -0,0 +1,24 @@+'use client';++import { HelpCircle } from 'lucide-react';+import { useTranslations } from 'next-intl';+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';++export default function RetentionHint() {+ const t = useTranslations('agentAnalytics');++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ aria-label={t('retentionNote')}+ className="inline-flex rounded-full align-middle text-muted-foreground transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"+ >+ <HelpCircle className="size-4" />+ </button>+ </TooltipTrigger>+ <TooltipContent className="max-w-xs">{t('retentionNote')}</TooltipContent>+ </Tooltip>+ );+}diff --git a/apps/web/src/features/agent-analytics/components/StatCards.tsx b/apps/web/src/features/agent-analytics/components/StatCards.tsxnew file mode 100644index 00000000..7c956acf--- /dev/null+++ b/apps/web/src/features/agent-analytics/components/StatCards.tsx@@ -0,0 +1,57 @@+import { useTranslations } from 'next-intl';+import type { AgentAnalytics } from '@/lib/api/endpoints/agentAnalytics';+import StatDelta, { type StatComparison } from './StatDelta';+import { formatCost, formatCount } from '../utils/format';++type Stat = StatComparison & { key: string; label: string; value: string };++// The headline figures of the window, each beside what the same span before it held.+export default function StatCards({ data }: { data: AgentAnalytics }) {+ const t = useTranslations('agentAnalytics');+ const { totals, previous } = data;++ const stats: Stat[] = [+ {+ key: 'cost',+ label: t('stats.cost'),+ value: formatCost(totals.cost),+ current: totals.cost ?? 0,+ previous: previous.cost,+ previousLabel: formatCost(previous.cost),+ },+ {+ key: 'tokens',+ label: t('stats.tokens'),+ value: formatCount(totals.inputTokens + totals.outputTokens),+ current: totals.inputTokens + totals.outputTokens,+ previous: previous.inputTokens + previous.outputTokens,+ },+ {+ key: 'runs',+ label: t('stats.runs'),+ value: formatCount(totals.runs),+ current: totals.runs,+ previous: previous.runs,+ },+ {+ key: 'errors',+ label: t('stats.errors'),+ value: formatCount(totals.errors),+ current: totals.errors,+ previous: previous.errors,+ riseIsBad: true,+ },+ ];++ return (+ <div className="grid grid-cols-2 gap-x-8 gap-y-6 xl:grid-cols-4">+ {stats.map((stat) => (+ <div key={stat.key} className="min-w-0">+ <p className="text-xs text-muted-foreground">{stat.label}</p>+ <p className="mt-1 text-3xl font-semibold tracking-tight tabular-nums">{stat.value}</p>+ <StatDelta stat={stat} />+ </div>+ ))}+ </div>+ );+}diff --git a/apps/web/src/features/agent-analytics/components/StatDelta.tsx b/apps/web/src/features/agent-analytics/components/StatDelta.tsxnew file mode 100644index 00000000..8c8a1ceb--- /dev/null+++ b/apps/web/src/features/agent-analytics/components/StatDelta.tsx@@ -0,0 +1,39 @@+import { TrendingDown, TrendingUp } from 'lucide-react';+import { useTranslations } from 'next-intl';+import { cn } from '@/lib/utils';+import { changeRatio, formatCount, formatPercent } from '../utils/format';++// How far one headline figure moved from the same span before it. A previous period+// of zero has no ratio, and a previous cost nothing could be priced for is null; both+// read as having nothing to compare against.+export interface StatComparison {+ current: number;+ previous: number | null;+ // What to print for the previous value when it is not a plain count.+ previousLabel?: string;+ // Only the error count is coloured by its direction: a period that cost less than+ // the one before it is not a decline.+ riseIsBad?: boolean;+}++export default function StatDelta({ stat }: { stat: StatComparison }) {+ const t = useTranslations('agentAnalytics');+ const ratio = stat.previous == null ? null : changeRatio(stat.current, stat.previous);+ if (ratio == null) {+ return <p className="mt-1 text-xs text-muted-foreground">{t('noComparison')}</p>;+ }+ const Icon = ratio >= 0 ? TrendingUp : TrendingDown;+ let tone = 'text-muted-foreground';+ if (stat.riseIsBad) {+ tone = ratio > 0 ? 'text-destructive' : 'text-emerald-600 dark:text-emerald-500';+ }+ return (+ <p className="mt-1 flex items-center gap-1.5 text-xs text-muted-foreground">+ <span className={cn('flex items-center gap-1 font-medium', tone)}>+ <Icon className="size-3.5" />+ {formatPercent(ratio)}+ </span>+ {t('vsPrevious', { value: stat.previousLabel ?? formatCount(stat.previous ?? 0) })}+ </p>+ );+}diff --git a/apps/web/src/features/agent-analytics/components/TokensOverTime.tsx b/apps/web/src/features/agent-analytics/components/TokensOverTime.tsxnew file mode 100644index 00000000..c3da8785--- /dev/null+++ b/apps/web/src/features/agent-analytics/components/TokensOverTime.tsx@@ -0,0 +1,89 @@+import { useState } from 'react';+import { CartesianGrid, Line, LineChart, XAxis } from 'recharts';+import { useTranslations } from 'next-intl';+import type { AgentAnalytics } from '@/lib/api/endpoints/agentAnalytics';+import {+ ChartContainer,+ ChartTooltip,+ ChartTooltipContent,+ type ChartConfig,+} from '@/components/ui/chart';+import Panel from './Panel';+import PanelEmpty from './PanelEmpty';+import MeasureTabs, { type Measure } from './MeasureTabs';+import { bucketLabel, formatCost, formatCount } from '../utils/format';++const SERIES_COLOR = { input: '#6366f1', output: '#f59e0b' };++// Input and output tokens per day, or what each day cost.+export default function TokensOverTime({ data }: { data: AgentAnalytics }) {+ const t = useTranslations('agentAnalytics');+ const [measure, setMeasure] = useState<Measure>('tokens');+ const tokens = data.totals.inputTokens + data.totals.outputTokens;++ const chartData = data.tokensPerDay.map((day) => ({+ label: bucketLabel(data, day.day),+ input: day.inputTokens,+ output: day.outputTokens,+ cost: day.cost ?? 0,+ }));++ const config: ChartConfig =+ measure === 'tokens'+ ? {+ input: { label: t('series.input'), color: SERIES_COLOR.input },+ output: { label: t('series.output'), color: SERIES_COLOR.output },+ }+ : { cost: { label: t('measure.cost'), color: SERIES_COLOR.input } };+ const keys = measure === 'tokens' ? (['input', 'output'] as const) : (['cost'] as const);++ return (+ <Panel+ title={t('overTime.title')}+ description={t('overTime.description')}+ value={measure === 'tokens' ? formatCount(tokens) : formatCost(data.totals.cost)}+ valueLabel={measure === 'tokens' ? t('totalTokens') : t('totalCost')}+ >+ <div className="space-y-3">+ <MeasureTabs value={measure} onChange={setMeasure} />+ {chartData.length === 0 ? (+ <PanelEmpty label={t('overTime.empty')} />+ ) : (+ // Recharts draws to absolute SVG coordinates and does not read the document+ // direction, so a mirrored chart would put its axes and series out of step.+ <ChartContainer dir="ltr" config={config} className="h-[200px] w-full">+ <LineChart data={chartData}>+ <CartesianGrid vertical={false} />+ <XAxis+ dataKey="label"+ tickLine={false}+ axisLine={false}+ tickMargin={8}+ fontSize={11}+ />+ <ChartTooltip+ content={+ <ChartTooltipContent+ formatter={(value) =>+ measure === 'tokens' ? formatCount(Number(value)) : formatCost(Number(value))+ }+ />+ }+ />+ {keys.map((key) => (+ <Line+ key={key}+ dataKey={key}+ type="monotone"+ stroke={`var(--color-${key})`}+ strokeWidth={2}+ dot={false}+ />+ ))}+ </LineChart>+ </ChartContainer>+ )}+ </div>+ </Panel>+ );+}diff --git a/apps/web/src/features/agent-analytics/components/UsageBreakdown.tsx b/apps/web/src/features/agent-analytics/components/UsageBreakdown.tsxnew file mode 100644index 00000000..faebe118--- /dev/null+++ b/apps/web/src/features/agent-analytics/components/UsageBreakdown.tsx@@ -0,0 +1,61 @@+import { useState } from 'react';+import { useTranslations } from 'next-intl';+import type { AgentUsage } from '@/lib/api/endpoints/agentAnalytics';+import Panel from './Panel';+import BarList from './BarList';+import MeasureTabs, { type Measure } from './MeasureTabs';+import { formatCost, formatCount } from '../utils/format';++export interface UsageItem extends AgentUsage {+ key: string;+ label: string;+}++// What each item of the window used, largest first, read as tokens or as what they+// cost. An item whose models are unpriced drops out of the cost list rather than+// reading as zero.+export default function UsageBreakdown({+ title,+ description,+ empty,+ items,+ total,+ onSelect,+}: {+ title: string;+ description: string;+ empty: string;+ items: UsageItem[];+ total: AgentUsage;+ onSelect?: (key: string) => void;+}) {+ const t = useTranslations('agentAnalytics');+ const [measure, setMeasure] = useState<Measure>('tokens');+ const tokensOf = (usage: AgentUsage) => usage.inputTokens + usage.outputTokens;++ const rows =+ measure === 'tokens'+ ? items.map((item) => ({+ ...item,+ value: tokensOf(item),+ trailing: formatCount(tokensOf(item)),+ }))+ : items+ .filter((item) => item.cost != null)+ .map((item) => ({ ...item, value: item.cost ?? 0, trailing: formatCost(item.cost) }))+ .sort((a, b) => b.value - a.value);++ return (+ <Panel+ title={title}+ description={description}+ value={measure === 'tokens' ? formatCount(tokensOf(total)) : formatCost(total.cost)}+ valueLabel={measure === 'tokens' ? t('totalTokens') : t('totalCost')}+ >+ <div className="space-y-3">+ <MeasureTabs value={measure} onChange={setMeasure} />+ <BarList rows={rows} empty={empty} onSelect={onSelect} />+ </div>+ </Panel>+ );+}diff --git a/apps/web/src/features/agent-analytics/components/WindowSelect.tsx b/apps/web/src/features/agent-analytics/components/WindowSelect.tsxnew file mode 100644index 00000000..36cf6410--- /dev/null+++ b/apps/web/src/features/agent-analytics/components/WindowSelect.tsx@@ -0,0 +1,35 @@+import { useTranslations } from 'next-intl';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';++const WINDOWS = [1, 7, 30, 90] as const;++// The number of days back from now a dashboard reads.+export default function WindowSelect({+ value,+ onChange,+}: {+ value: number;+ onChange: (days: number) => void;+}) {+ const t = useTranslations('agentAnalytics');+ return (+ <Select value={String(value)} onValueChange={(next) => onChange(Number(next))}>+ <SelectTrigger className="w-40" size="sm">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {WINDOWS.map((days) => (+ <SelectItem key={days} value={String(days)}>+ {t('window', { days })}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+}diff --git a/apps/web/src/features/agent-analytics/utils/format.ts b/apps/web/src/features/agent-analytics/utils/format.tsnew file mode 100644index 00000000..604c33e0--- /dev/null+++ b/apps/web/src/features/agent-analytics/utils/format.ts@@ -0,0 +1,48 @@+import { formatShortDate, formatTime } from '@/utils/dates';++// 1200 reads as "1.2K", 1_400_000 as "1.4M": short enough to sit beside a cost on one+// line of a panel.+export function formatCount(value: number): string {+ return new Intl.NumberFormat(undefined, {+ notation: 'compact',+ maximumFractionDigits: 1,+ }).format(value);+}++// An amount in USD. A run of a small model costs fractions of a cent, so an amount under+// a cent keeps enough digits to be read rather than rounding to $0.00. Null is what the+// API sends for a model the price table does not name.+export function formatCost(value: number | null): string {+ if (value == null) return '—';+ const digits = value !== 0 && value < 0.01 ? 4 : 2;+ return new Intl.NumberFormat(undefined, {+ style: 'currency',+ currency: 'USD',+ minimumFractionDigits: 2,+ maximumFractionDigits: digits,+ }).format(value);+}++// How far a figure moved from the same span before it. Null when a previous period of+// zero leaves nothing to compare against.+export function changeRatio(current: number, previous: number): number | null {+ if (previous === 0) return null;+ return (current - previous) / previous;+}++export function formatPercent(ratio: number): string {+ return new Intl.NumberFormat(undefined, {+ style: 'percent',+ maximumFractionDigits: 1,+ signDisplay: 'exceptZero',+ }).format(ratio);+}++// The x-axis label of a chart point. A window of a day is bucketed by the hour, so its+// points are told apart by the time rather than the date. A day bucket starts at the+// database's midnight, so it is labelled by its date and not moved into the viewer's+// zone, where it would read as the day before west of it.+export function bucketLabel(window: { from: string; to: string }, value: string): string {+ const hourly = new Date(window.to).getTime() - new Date(window.from).getTime() <= 25 * 3_600_000;+ return hourly ? formatTime(value) : formatShortDate(value.slice(0, 10));+}diff --git a/apps/web/src/features/god/GodGeneralPage.tsx b/apps/web/src/features/god/GodGeneralPage.tsxindex 75399acb..3b73aca5 100644--- a/apps/web/src/features/god/GodGeneralPage.tsx+++ b/apps/web/src/features/god/GodGeneralPage.tsx@@ -5,24 +5,40 @@ import { useTranslations } from 'next-intl';import SettingsCard from '@/components/common/page/SettingsCard';import SettingsRow from '@/components/common/page/SettingsRow';import SettingsSection from '@/components/common/page/SettingsSection';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';import { Switch } from '@/components/ui/switch';import GodSectionPage from './components/GodSectionPage';import GodSettingsGate from './components/GodSettingsGate';import {+ useInstanceAgentSettingsQuery,useInstanceAuthSettingsQuery,useInstanceProjectDefaultsQuery,+ useUpdateInstanceAgentSettings,useUpdateInstanceAuthSettings,useUpdateInstanceProjectDefaults,} from './services/god.service';-import type { InstanceAuthSettings } from '@/lib/api/endpoints/god';+import type { AgentSettings, InstanceAuthSettings } from '@/lib/api/endpoints/god';import type { ProjectDefaults } from '@/lib/api/endpoints/projects';+// The trace windows offered; a window stored through the API outside them is offered too.+const TRACE_DAYS = [7, 30, 90, 365];+export default function GodGeneralPage() {const defaults = useInstanceProjectDefaultsQuery().data;const auth = useInstanceAuthSettingsQuery().data;+ const agents = useInstanceAgentSettingsQuery().data;return (- <GodSettingsGate slug="general" data={defaults && auth ? { defaults, auth } : undefined}>+ <GodSettingsGate+ slug="general"+ data={defaults && auth && agents ? { defaults, auth, agents } : undefined}+ >{(data) => <GeneralForm {...data} />}</GodSettingsGate>);@@ -33,13 +49,19 @@ export default function GodGeneralPage() {function GeneralForm({defaults,auth,+ agents,}: {defaults: ProjectDefaults;auth: InstanceAuthSettings;+ agents: AgentSettings;}) {const t = useTranslations('god.general');const update = useUpdateInstanceProjectDefaults();const updateAuth = useUpdateInstanceAuthSettings();+ const updateAgents = useUpdateInstanceAgentSettings();+ const traceDays = [...new Set([...TRACE_DAYS, agents.traceRetentionDays])]+ .filter((days) => days > 0)+ .sort((a, b) => a - b);// Single toggles, so each saves on change rather than behind a Save button.async function setMcpEnabled(mcpEnabled: boolean) {@@ -60,6 +82,15 @@ function GeneralForm({}}+ async function setTraceRetention(traceRetentionDays: number) {+ try {+ await updateAgents.mutateAsync({ traceRetentionDays });+ toast.success(t('agentsSaved'));+ } catch {+ // The failure already surfaced through the global mutation error toast.+ }+ }+return (<GodSectionPage slug="general"><div className="space-y-10">@@ -94,6 +125,34 @@ function GeneralForm({/></SettingsCard></SettingsSection>++ <SettingsSection title={t('agents')}>+ <SettingsCard>+ <SettingsRow+ title={t('traceRetention')}+ description={t('traceRetentionHint')}+ control={+ <Select+ value={String(agents.traceRetentionDays)}+ disabled={updateAgents.isPending}+ onValueChange={(value) => void setTraceRetention(Number(value))}+ >+ <SelectTrigger className="w-36" size="sm">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {traceDays.map((days) => (+ <SelectItem key={days} value={String(days)}>+ {t('traceDays', { days })}+ </SelectItem>+ ))}+ <SelectItem value="0">{t('traceForever')}</SelectItem>+ </SelectContent>+ </Select>+ }+ />+ </SettingsCard>+ </SettingsSection></div></GodSectionPage>);diff --git a/apps/web/src/features/god/services/god.service.ts b/apps/web/src/features/god/services/god.service.tsindex 5822bae0..8eaa5b01 100644--- a/apps/web/src/features/god/services/god.service.ts+++ b/apps/web/src/features/god/services/god.service.ts@@ -12,6 +12,7 @@ import type { ProjectDefaults } from '@/lib/api/endpoints/projects';import { nextPageParam, type PageParams } from '@/lib/api/core/paging';import { DEFAULT_PAGE_SIZE } from '@/hooks/usePaging';import {+ type AgentSettings,type InstanceAuthSettingsPatch,type InstanceEmailSettingsPatch,type InstanceGoogleSettingsPatch,@@ -31,6 +32,8 @@ import {updateInstanceTelegramSettings,getInstanceProjectDefaults,updateInstanceProjectDefaults,+ getInstanceAgentSettings,+ updateInstanceAgentSettings,getInstanceStorageSettings,updateInstanceStorageSettings,listInstanceUsers,@@ -168,6 +171,22 @@ export function useUpdateInstanceProjectDefaults() {});}+// What applies to every team's agents: how long their run traces are kept.+export function useInstanceAgentSettingsQuery() {+ return useQuery({+ queryKey: qk.instanceAgentSettings,+ queryFn: () => getInstanceAgentSettings(),+ });+}++export function useUpdateInstanceAgentSettings() {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: (body: AgentSettings) => updateInstanceAgentSettings(body),+ onSuccess: (data) => qc.setQueryData(qk.instanceAgentSettings, data),+ });+}+// The upload limits: file sizes, accepted attachment types, and the per-project// storage quota.export function useInstanceStorageSettingsQuery() {diff --git a/apps/web/src/features/settings/components/schedules/SettingsScheduleRow.tsx b/apps/web/src/features/settings/components/schedules/SettingsScheduleRow.tsxindex f0c5217d..1d3f180b 100644--- a/apps/web/src/features/settings/components/schedules/SettingsScheduleRow.tsx+++ b/apps/web/src/features/settings/components/schedules/SettingsScheduleRow.tsx@@ -2,6 +2,7 @@ import {Ban,Bot,History,+ Lock,MessageSquareText,MoreHorizontal,Pause,@@ -24,6 +25,7 @@ import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popoverimport { TableCell, TableRow } from '@/components/ui/table';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';import { cn } from '@/lib/utils';+import { PRO_URL } from '@/utils/app';import SettingsIconButton from '../SettingsIconButton';import { useSettingsCan } from '../../context/settingsPermission';import { formatUtc } from '../../utils/cronSchedule';@@ -53,13 +55,18 @@ export function SettingsScheduleRow({}) {const t = useTranslations('settings.schedules');const can = useSettingsCan();+ // An unsupported schedule shows what it was set up to do and can be deleted, nothing more.+ const canEdit = can('edit') && schedule.supported;return (<TableRow className="group/item cursor-pointer" onClick={onHistory}><TableCell className="px-3 py-4 align-top whitespace-normal"><div className="flex min-w-0 items-start gap-2.5"><span- className={cn('mt-[7px] size-2 shrink-0 rounded-full', statusDotClass(schedule.status))}- title={schedule.status === 'active' ? t('statusActive') : t('statusPaused')}+ className={cn(+ 'mt-[7px] size-2 shrink-0 rounded-full',+ statusDotClass(schedule.supported ? schedule.status : 'paused'),+ )}+ title={t(statusTitleKey(schedule))}/>{schedule.prompt && (<Popover>@@ -96,15 +103,22 @@ export function SettingsScheduleRow({</TableCell><TableCell className="px-3 py-4 align-top whitespace-normal"><SettingsScheduleWhen schedule={schedule} columnName={columnName} />+ {!schedule.supported && (+ <a+ href={PRO_URL}+ target="_blank"+ rel="noreferrer"+ title={t('unavailableHint')}+ className="mt-1.5 inline-flex items-center gap-1 text-xs font-medium text-amber-600 hover:underline dark:text-amber-500"+ onClick={(e) => e.stopPropagation()}+ >+ <Lock className="size-3.5" />+ {t('unavailable')}+ </a>+ )}</TableCell><TableCell className="px-3 py-4 align-top text-sm whitespace-nowrap tabular-nums">- {schedule.nextRunAt ? (- formatUtc(schedule.nextRunAt)- ) : (- <span className="text-xs whitespace-normal text-muted-foreground">- {schedule.type === 'status' ? t('nextRunOnStatus') : t('nextRunOnTrigger')}- </span>- )}+ <NextRun schedule={schedule} /></TableCell><TableCell className="px-3 py-4 align-top whitespace-normal">{schedule.lastRunStatus ? (@@ -127,7 +141,7 @@ export function SettingsScheduleRow({</TableCell><TableCell className="px-3 py-3 align-top"><div className="flex items-center justify-end gap-1" onClick={(e) => e.stopPropagation()}>- {can('edit') && (+ {canEdit && (<SettingsIconButtontitle={schedule.status === 'active' ? t('pause') : t('resume')}onClick={onToggle}@@ -159,7 +173,7 @@ export function SettingsScheduleRow({<TooltipContent>{t('moreActions')}</TooltipContent></Tooltip><DropdownMenuContent align="end">- {can('edit') && schedule.type === 'cron' && (+ {canEdit && schedule.type === 'cron' && (<DropdownMenuItemclassName="min-h-11 sm:min-h-8"disabled={running}@@ -175,13 +189,13 @@ export function SettingsScheduleRow({{t('cancelPending', { count: schedule.pendingRuns })}</DropdownMenuItem>)}- {can('edit') && (+ {canEdit && (<DropdownMenuItem className="min-h-11 sm:min-h-8" onSelect={onEdit}><Pencil />{t('edit')}</DropdownMenuItem>)}- {can('delete') && can('edit') && <DropdownMenuSeparator />}+ {can('delete') && canEdit && <DropdownMenuSeparator />}{can('delete') && (<DropdownMenuItemclassName="min-h-11 sm:min-h-8"@@ -201,6 +215,22 @@ export function SettingsScheduleRow({);}+function NextRun({ schedule }: { schedule: AgentSchedule }) {+ const t = useTranslations('settings.schedules');+ if (!schedule.supported) return <span className="text-xs text-muted-foreground">—</span>;+ if (schedule.nextRunAt) return formatUtc(schedule.nextRunAt);+ return (+ <span className="text-xs whitespace-normal text-muted-foreground">+ {schedule.type === 'status' ? t('nextRunOnStatus') : t('nextRunOnTrigger')}+ </span>+ );+}++function statusTitleKey(schedule: AgentSchedule) {+ if (!schedule.supported) return 'unavailableHint';+ return schedule.status === 'active' ? 'statusActive' : 'statusPaused';+}+function statusDotClass(status: AgentSchedule['status']): string {return status === 'active' ? 'bg-emerald-500' : 'bg-muted-foreground/40';}diff --git a/apps/web/src/features/teams/ManageTeamsLayout.tsx b/apps/web/src/features/teams/ManageTeamsLayout.tsxindex 5f542a48..6a40d964 100644--- a/apps/web/src/features/teams/ManageTeamsLayout.tsx+++ b/apps/web/src/features/teams/ManageTeamsLayout.tsx@@ -39,19 +39,20 @@ export default function ManageTeamsLayout({ children }: { children: ReactNode })}list={<div className="space-y-6">- {workspace && (- <div className="flex items-baseline gap-2 px-2 pt-1">- <h2 dir="auto" className="min-w-0 truncate text-[15px] font-semibold">- {workspace.name}- </h2>- {workspace.role && (+ {/* Only its owner and its admins have anything of the workspace to open. */}+ {workspace?.role && (+ <>+ <div className="flex items-baseline gap-2 px-2 pt-1">+ <h2 dir="auto" className="min-w-0 truncate text-[15px] font-semibold">+ {workspace.name}+ </h2><span className="shrink-0 text-xs text-muted-foreground">{tw(`roles.${workspace.role}`)}</span>- )}- </div>+ </div>+ <WorkspaceSectionNav workspace={workspace} />+ </>)}- {workspace?.role && <WorkspaceSectionNav workspace={workspace} />}<TeamsRailteams={workspace ? teams.filter((team) => team.workspaceId === workspace.id) : teams}isPending={isPending}diff --git a/apps/web/src/features/teams/WorkspaceLayout.tsx b/apps/web/src/features/teams/WorkspaceLayout.tsxindex 10a50695..99c646ae 100644--- a/apps/web/src/features/teams/WorkspaceLayout.tsx+++ b/apps/web/src/features/teams/WorkspaceLayout.tsx@@ -2,21 +2,25 @@import { useEffect, type ReactNode } from 'react';import { useRouter } from 'next/navigation';-import { manageTeamsPath } from '@/utils/paths';+import { manageTeamsPath, teamPath } from '@/utils/paths';+import { useTeamsQuery } from '@/services/teams.service';import { useWorkspacesQuery } from '@/services/workspaces.service';import { useRouteWorkspaceId } from './hooks/useRouteWorkspaceId';// One workspace the caller manages, as the section open beside the rails. A workspace-// they do not manage falls back to the teams.+// they do not manage opens their first team in it, or the teams when they have none.export default function WorkspaceLayout({ children }: { children: ReactNode }) {const router = useRouter();const workspaceId = useRouteWorkspaceId();const { data } = useWorkspacesQuery();+ const teams = useTeamsQuery().data;const workspace = data?.find((entry) => entry.id === workspaceId && entry.role !== null);useEffect(() => {- if (data && !workspace) router.replace(manageTeamsPath());- }, [data, workspace, router]);+ if (!data || workspace || !teams) return;+ const first = teams.find((team) => team.workspaceId === workspaceId);+ router.replace(first ? teamPath(first.ref) : manageTeamsPath());+ }, [data, workspace, teams, workspaceId, router]);return <div className="flex min-w-0 flex-1 flex-col">{workspace && children}</div>;}diff --git a/apps/web/src/features/teams/components/TeamSectionNav.tsx b/apps/web/src/features/teams/components/TeamSectionNav.tsxindex 82251720..3e2e0139 100644--- a/apps/web/src/features/teams/components/TeamSectionNav.tsx+++ b/apps/web/src/features/teams/components/TeamSectionNav.tsx@@ -7,6 +7,7 @@ import {BookText,Bot,ChevronRight,+ Coins,FolderKanban,GitBranch,Info,@@ -37,11 +38,11 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip// The sections of the open team, as the page's last rail: the team itself, its// projects, the roles they assign from and its members, then the AI group — the// integration credentials the agents run on, the agents themselves, the skills they-// load and the tools they can call — with what MCP clients reach and the notification-// providers last. The counts come with the team list, so each is shown before its-// section is opened. A section the caller may not read is left out, and the AI group with it-// once none of its four is readable. Collapsed, the rail shows the icons of every-// section, the AI group's included, without the group.+// load, the tools they can call and what they spent — with what MCP clients reach and+// the notification providers last. The counts come with the team list, so each is shown+// before its section is opened. A section the caller may not read is left out, and the+// AI group with it once none of them is readable. Collapsed, the rail shows the icons of+// every section, the AI group's included, without the group.export default function TeamSectionNav({team,collapsed,@@ -71,13 +72,12 @@ export default function TeamSectionNav({};}+ const runsTeam = team.role === 'owner' || team.role === 'manager';const top = [section('info', t('info.title'), Info),section('projects', t('projects.title'), FolderKanban, team.projectCount),// The roles are managed by the team's owner and managers, so the section is theirs.- ...(team.role === 'owner' || team.role === 'manager'- ? [section('roles', t('roles.title'), ShieldCheck, team.roleCount)]- : []),+ ...(runsTeam ? [section('roles', t('roles.title'), ShieldCheck, team.roleCount)] : []),section('members', t('members.title'), Users, team.memberCount),];const ai = [@@ -93,10 +93,15 @@ export default function TeamSectionNav({...(permissions?.agent_tools.read? [section('agent-tools', t('agentTools.title'), Wrench, team.toolCount)]: []),+ // Whoever runs the team reads every project there, anyone else the projects where+ // their role grants agent_usage.+ ...(runsTeam || permissions?.agent_usage.read+ ? [section('analytics', t('analytics.title'), Coins)]+ : []),];// The notification providers are the owner's: nobody else reads or writes them.const bottom = [- ...(team.role === 'owner' || team.role === 'manager' ? [section('git', 'Git', GitBranch)] : []),+ ...(runsTeam ? [section('git', 'Git', GitBranch)] : []),section('mcp', t('mcp.title'), Radio),...(team.role === 'owner' ? [section('notifications', t('notifications.title'), Bell)] : []),];diff --git a/apps/web/src/features/teams/components/workspace/WorkspaceSectionNav.tsx b/apps/web/src/features/teams/components/workspace/WorkspaceSectionNav.tsxindex 946f1765..0c5f2487 100644--- a/apps/web/src/features/teams/components/workspace/WorkspaceSectionNav.tsx+++ b/apps/web/src/features/teams/components/workspace/WorkspaceSectionNav.tsx@@ -1,32 +1,71 @@'use client';+import { useState } from 'react';import { usePathname } from 'next/navigation';import { useTranslations } from 'next-intl';+import { ChevronRight, Settings } from 'lucide-react';import type { WorkspaceSummary } from '@/lib/api/endpoints/workspaces';+import { cn } from '@/lib/utils';import { workspacePath } from '@/utils/paths';import { useWorkspaceSettingsSections } from '../../hooks/useWorkspaceSettingsSections';-import { SectionNav, type SectionNavItem } from '@/components/common/page/SectionNav';+import type { WorkspaceSectionGroup } from '../../types/workspaceSection';+import {+ SectionNav,+ sectionNavIdleClass,+ sectionNavItemClass,+ type SectionNavItem,+} from '@/components/common/page/SectionNav';+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';+// The overview sections at the top of the menu, then the settings folded into a group,+// as the team menu folds its AI sections. With no overview to sit under there is nothing+// to fold, and the settings are listed as they are.export default function WorkspaceSectionNav({ workspace }: { workspace: WorkspaceSummary }) {const t = useTranslations('teams.workspace');const pathname = usePathname();- const sections: SectionNavItem[] = useWorkspaceSettingsSections(workspace).map(- ({ id, label, icon, badge }) => ({- id,- label,- icon,- badge,- href: workspacePath(workspace.id, id),- }),- );- const activeId = sections.find((entry) => entry.href === pathname)?.id ?? null;+ const sections = useWorkspaceSettingsSections(workspace);+ const items = (group: WorkspaceSectionGroup): SectionNavItem[] =>+ sections+ .filter((section) => section.group === group)+ .map(({ id, label, icon, badge }) => ({+ id,+ label,+ icon,+ badge,+ href: workspacePath(workspace.id, id),+ }));+ const overview = items('overview');+ const settings = items('settings');+ const activeId = [...overview, ...settings].find((entry) => entry.href === pathname)?.id ?? null;+ // Null until the user opens or closes the group themselves; until then it follows+ // whichever section is open.+ const [toggled, setToggled] = useState<boolean | null>(null);+ const settingsOpen = toggled ?? settings.some((entry) => entry.id === activeId);++ if (overview.length === 0) {+ return <SectionNav sections={settings} activeId={activeId} label={workspace.name} />;+ }return (- <div className="space-y-2">- <h2 className="truncate px-2 text-xs font-medium tracking-wide text-muted-foreground uppercase">- {t('info.title')}- </h2>- <SectionNav sections={sections} activeId={activeId} label={workspace.name} />+ <div className="space-y-0.5">+ <SectionNav sections={overview} activeId={activeId} label={workspace.name} />+ {settings.length > 0 && (+ <Collapsible open={settingsOpen} onOpenChange={setToggled}>+ <CollapsibleTrigger className={cn(sectionNavItemClass, sectionNavIdleClass)}>+ <Settings className="size-4 shrink-0 text-muted-foreground" />+ <span className="min-w-0 flex-1 truncate">{t('settingsGroup')}</span>+ <ChevronRight+ className={cn(+ 'size-4 shrink-0 text-muted-foreground transition-transform duration-150',+ settingsOpen && 'rotate-90',+ )}+ />+ </CollapsibleTrigger>+ <CollapsibleContent className="ps-4">+ <SectionNav sections={settings} activeId={activeId} label={t('settingsGroup')} />+ </CollapsibleContent>+ </Collapsible>+ )}</div>);}diff --git a/apps/web/src/features/teams/hooks/useWorkspaceSettingsSections.ts b/apps/web/src/features/teams/hooks/useWorkspaceSettingsSections.tsindex 9c5d2833..17a7172c 100644--- a/apps/web/src/features/teams/hooks/useWorkspaceSettingsSections.ts+++ b/apps/web/src/features/teams/hooks/useWorkspaceSettingsSections.ts@@ -1,20 +1,29 @@-import { Info, ShieldCheck } from 'lucide-react';+import { Coins, Info, ShieldCheck } from 'lucide-react';import { useTranslations } from 'next-intl';import { useWorkspaceSections } from '@/cloud';import type { WorkspaceSummary } from '@/lib/api/endpoints/workspaces';-import type { WorkspaceSection } from '../types/workspaceSection';+import { WORKSPACE_SECTION_GROUPS, type WorkspaceSection } from '../types/workspaceSection';import { useWorkspaceQuery } from '@/services/workspaces.service';+// Grouped in menu order, so the first entry, the page a workspace opens on+// (WorkspaceFirstSection), is the first of the top group.+// Only the workspace's owner and its admins open them (WorkspaceLayout), and both read+// what the agents spent.export function useWorkspaceSettingsSections(workspace: WorkspaceSummary): WorkspaceSection[] {const t = useTranslations('teams.workspace');const detail = useWorkspaceQuery(workspace.id).data;- return useWorkspaceSections(workspace, [- { id: 'info', label: t('general'), icon: Info },+ const sections = useWorkspaceSections(workspace, [+ { id: 'agent-usage', label: t('agentUsage.title'), icon: Coins, group: 'overview' },+ { id: 'info', label: t('general'), icon: Info, group: 'settings' },{id: 'managers',label: t('managers.title'),icon: ShieldCheck,+ group: 'settings',badge: detail && String(detail.managerCount),},]);+ return WORKSPACE_SECTION_GROUPS.flatMap((group) =>+ sections.filter((section) => section.group === group),+ );}diff --git a/apps/web/src/features/teams/types/workspaceSection.ts b/apps/web/src/features/teams/types/workspaceSection.tsindex 2fe6a13f..6d4631e6 100644--- a/apps/web/src/features/teams/types/workspaceSection.ts+++ b/apps/web/src/features/teams/types/workspaceSection.ts@@ -1,13 +1,18 @@import type { ComponentType } from 'react';import type { LucideIcon } from 'lucide-react';+export const WORKSPACE_SECTION_GROUPS = ['overview', 'settings'] as const;++export type WorkspaceSectionGroup = (typeof WORKSPACE_SECTION_GROUPS)[number];+// An entry in a workspace's settings menu, opened at workspacePath(workspaceId, id). The// core's entries have routes of their own; one the hosted build adds carries its page in-// `Component`.+// `Component`. The menu lists what the workspace shows before what is set in it.export interface WorkspaceSection {id: string;label: string;icon: LucideIcon;+ group: WorkspaceSectionGroup;badge?: string;Component?: ComponentType<{ workspaceId: number }>;}diff --git a/apps/web/src/i18n/messages.ts b/apps/web/src/i18n/messages.tsindex 5405b769..4338fbf3 100644--- a/apps/web/src/i18n/messages.ts+++ b/apps/web/src/i18n/messages.ts@@ -1,4 +1,5 @@import account from '../../messages/en/account.json';+import agentAnalytics from '../../messages/en/agentAnalytics.json';import aiChat from '../../messages/en/aiChat.json';import apiKeys from '../../messages/en/apiKeys.json';import auth from '../../messages/en/auth.json';@@ -69,6 +70,7 @@ const coreMessages = {god,newProject,teams,+ agentAnalytics,updates,whatsNew,};diff --git a/apps/web/src/lib/api/endpoints/agentAnalytics.ts b/apps/web/src/lib/api/endpoints/agentAnalytics.tsnew file mode 100644index 00000000..f4a140f3--- /dev/null+++ b/apps/web/src/lib/api/endpoints/agentAnalytics.ts@@ -0,0 +1,47 @@+import { request } from '@/lib/api/core/client';++// What a group of model calls read, wrote and cost. `cost` is USD, and null where the+// price table names none of the models the group used.+export interface AgentUsage {+ inputTokens: number;+ outputTokens: number;+ cost: number | null;+}++export interface AgentAnalyticsTotals extends AgentUsage {+ runs: number;+ errors: number;+}++export interface AgentAnalytics {+ from: string;+ to: string;+ totals: AgentAnalyticsTotals;+ // The same span before the window, which every headline figure is compared against.+ previous: AgentAnalyticsTotals;+ models: (AgentUsage & { provider: string; model: string; calls: number })[];+ agents: (AgentAnalyticsTotals & { agentId: number; name: string })[];+ projects: (AgentAnalyticsTotals & { projectId: number; name: string })[];+ teams: (AgentAnalyticsTotals & { teamId: number; name: string })[];+ tokensPerDay: (AgentUsage & { day: string })[];+}++// What a dashboard reads: one team, all of it or one project of it, or every team of a+// workspace.+export type AgentAnalyticsScope =+ { teamId: number; projectId: number | null } | { workspaceId: number };++// A team's dashboard, with the projects the caller reads it for: what `projectId`+// narrows it to.+export interface TeamAgentAnalytics extends AgentAnalytics {+ readableProjects: { projectId: number; name: string }[];+}++export const getTeamAgentAnalytics = (teamId: number, days: number, projectId: number | null) => {+ const q = new URLSearchParams({ days: String(days) });+ if (projectId != null) q.set('projectId', String(projectId));+ return request<TeamAgentAnalytics>(`/teams/${teamId}/agent-analytics?${q}`);+};++export const getWorkspaceAgentAnalytics = (workspaceId: number, days: number) =>+ request<AgentAnalytics>(`/workspaces/${workspaceId}/agent-analytics?days=${days}`);diff --git a/apps/web/src/lib/api/endpoints/agentSchedules.ts b/apps/web/src/lib/api/endpoints/agentSchedules.tsindex 4086aaf5..7f56b8eb 100644--- a/apps/web/src/lib/api/endpoints/agentSchedules.ts+++ b/apps/web/src/lib/api/endpoints/agentSchedules.ts@@ -32,6 +32,9 @@ export interface AgentSchedule {// False when the agent's runner is scoped to another member, who alone may run or// stop it.canTrigger: boolean;+ // False for a schedule set up with Cloud or Pro, whose type or options this instance+ // lacks: kept as it is, it starts no run and can only be deleted.+ supported: boolean;createdAt: string;updatedAt: string;}diff --git a/apps/web/src/lib/api/endpoints/god.ts b/apps/web/src/lib/api/endpoints/god.tsindex 65f08aa0..340570d0 100644--- a/apps/web/src/lib/api/endpoints/god.ts+++ b/apps/web/src/lib/api/endpoints/god.ts@@ -265,6 +265,20 @@ export const updateInstanceProjectDefaults = (body: ProjectDefaults) =>body: JSON.stringify(body),});+// What applies to every team's agents on this instance.+export interface AgentSettings {+ // Days a run trace is kept for. 0 keeps traces until they are deleted by hand.+ traceRetentionDays: number;+}++export const getInstanceAgentSettings = () => request<AgentSettings>('/god/agent-settings');++export const updateInstanceAgentSettings = (body: AgentSettings) =>+ request<AgentSettings>('/god/agent-settings', {+ method: 'PUT',+ body: JSON.stringify(body),+ });+export const getInstanceStorageSettings = () => request<StorageSettings>('/god/storage-settings');export const updateInstanceStorageSettings = (patch: StorageSettingsPatch) =>diff --git a/apps/web/src/lib/api/endpoints/roles.ts b/apps/web/src/lib/api/endpoints/roles.tsindex 45547e56..44ca4b71 100644--- a/apps/web/src/lib/api/endpoints/roles.ts+++ b/apps/web/src/lib/api/endpoints/roles.ts@@ -21,6 +21,7 @@ export type PermissionResource =| 'integrations'| 'agent_skills'| 'agent_tools'+ | 'agent_usage'| 'custom_fields'| 'issue_templates'| 'workflow_config'diff --git a/apps/web/src/services/agentAnalytics.service.ts b/apps/web/src/services/agentAnalytics.service.tsnew file mode 100644index 00000000..46839775--- /dev/null+++ b/apps/web/src/services/agentAnalytics.service.ts@@ -0,0 +1,27 @@+import { keepPreviousData, useQuery } from '@tanstack/react-query';+import {+ getTeamAgentAnalytics,+ getWorkspaceAgentAnalytics,+} from '@/lib/api/endpoints/agentAnalytics';+import { qk } from '@/services/queryKeys';++export function useTeamAgentAnalyticsQuery(+ teamId: number | null,+ days: number,+ projectId: number | null,+) {+ return useQuery({+ queryKey: qk.agentAnalytics(teamId ?? 0, days, projectId),+ queryFn: () => getTeamAgentAnalytics(teamId!, days, projectId),+ enabled: teamId != null,+ placeholderData: keepPreviousData,+ });+}++export function useWorkspaceAgentAnalyticsQuery(workspaceId: number, days: number) {+ return useQuery({+ queryKey: qk.workspaceAgentAnalytics(workspaceId, days),+ queryFn: () => getWorkspaceAgentAnalytics(workspaceId, days),+ placeholderData: keepPreviousData,+ });+}diff --git a/apps/web/src/services/queryKeys.ts b/apps/web/src/services/queryKeys.tsindex 321eaa80..0413372a 100644--- a/apps/web/src/services/queryKeys.ts+++ b/apps/web/src/services/queryKeys.ts@@ -109,6 +109,10 @@ export const qk = {['noteBoards', projectKey, 'board', boardId] as const,noteBoardAccessCandidates: (projectKey: string) =>['noteBoards', projectKey, 'accessCandidates'] as const,+ agentAnalytics: (teamId: number, days: number, projectId: number | null) =>+ ['agentAnalytics', teamId, days, projectId] as const,+ workspaceAgentAnalytics: (workspaceId: number, days: number) =>+ ['workspaceAgentAnalytics', workspaceId, days] as const,analytics: (projectKey: string, kind: string, params?: unknown) =>['analytics', projectKey, kind, params ?? {}] as const,analyticsForProject: (projectKey: string) => ['analytics', projectKey] as const,@@ -285,6 +289,7 @@ export const qk = {instanceOidcSettings: ['instanceOidcSettings'] as const,instanceTelegramSettings: ['instanceTelegramSettings'] as const,instanceProjectDefaults: ['instanceProjectDefaults'] as const,+ instanceAgentSettings: ['instanceAgentSettings'] as const,instanceStorageSettings: ['instanceStorageSettings'] as const,// The upload limits as read by the upload UI (open to any signed-in user).storageSettings: ['storageSettings'] as const,diff --git a/apps/web/src/utils/app.ts b/apps/web/src/utils/app.tsindex 0108ff8d..d8208b5a 100644--- a/apps/web/src/utils/app.ts+++ b/apps/web/src/utils/app.ts@@ -7,6 +7,9 @@ export const APP_NAME = "It's a Plan";// The product site. The product mark on the public share pages links to it.export const APP_SITE_URL = 'https://itsaplan.dev/';+// The page about Cloud and self-hosted Pro, linked wherever the app names what they add.+export const PRO_URL = 'https://itsaplan.dev/pro';+// The legal document URLs, linked from the logged-out screens: Google requires the// privacy policy and terms registered for the OAuth client to be reachable before// consent is given. Each instance points these at its own documents through itsdiff --git a/apps/web/src/utils/paths.ts b/apps/web/src/utils/paths.tsindex 617ac54b..61477b95 100644--- a/apps/web/src/utils/paths.ts+++ b/apps/web/src/utils/paths.ts@@ -157,6 +157,7 @@ export type TeamSection =| 'ai-agents'| 'agent-skills'| 'agent-tools'+ | 'analytics'| 'notifications';// A team's settings, under the team's ref (Team.ref): /acme/settings.diff --git a/apps/web/src/utils/permissions.ts b/apps/web/src/utils/permissions.tsindex ea2da64b..f6dfaf67 100644--- a/apps/web/src/utils/permissions.ts+++ b/apps/web/src/utils/permissions.ts@@ -84,7 +84,10 @@ const GROUP_DEFS: PermissionGroup[] = [{ key: 'dashboards', resources: ['dashboards'] },{ key: 'documents', resources: ['documents'] },{ key: 'notes', resources: ['note_boards'] },- { key: 'ai', resources: ['ai_agents', 'integrations', 'agent_skills', 'agent_tools'] },+ {+ key: 'ai',+ resources: ['ai_agents', 'integrations', 'agent_skills', 'agent_tools', 'agent_usage'],+ },{key: 'configuration',resources: [diff --git a/bun.lock b/bun.lockindex 9ad2c5db..99991d27 100644--- a/bun.lock+++ b/bun.lock@@ -27,6 +27,7 @@"@firecrawl/pdf-inspector": "^1.17.0","@mastra/core": "^1.58.0","@mastra/memory": "^1.26.1",+ "@mastra/observability": "^1.17.6","@mastra/pg": "^1.20.0","@modelcontextprotocol/sdk": "^1.30.0","@repo/agent-tools": "workspace:*",@@ -716,6 +717,8 @@"@mastra/memory": ["@mastra/[email protected]", "", { "dependencies": { "@mastra/schema-compat": "1.3.6", "async-mutex": "^0.5.0", "diff": "^8.0.3", "json-schema": "^0.4.0", "lru-cache": "^11.2.7", "probe-image-size": "^7.2.3", "tokenx": "^1.3.0", "xxhash-wasm": "^1.1.0", "zod": "^4.4.3" }, "peerDependencies": { "@mastra/core": ">=1.4.1-0 <2.0.0-0" } }, "sha512-hKZCSEvfQJ9QWQY5gt0x9vLR4mnRValb325ZRL+ctxbuMTNKO4A8ssmFi5gdmDOpnQ5SWiQ/BPibrFcGNbA2Mg=="],+ "@mastra/observability": ["@mastra/[email protected]", "", { "peerDependencies": { "@mastra/core": ">=1.16.0-0 <2.0.0-0", "zod": "^3.25.0 || ^4.0.0" } }, "sha512-41T4v4ydBkpof36rpqKcJ64GS65RVHI/VN0/V2Peg1YS8KDAYqBkzLSv022TILZldC/dA9DqivPq7BqGMwrr+w=="],+"@mastra/pg": ["@mastra/[email protected]", "", { "dependencies": { "async-mutex": "^0.5.0", "pg": "^8.22.0", "pg-connection-string": "^2.12.0", "xxhash-wasm": "^1.1.0" }, "peerDependencies": { "@mastra/core": ">=1.53.0-0 <2.0.0-0" } }, "sha512-cuThEP0TdvgWW70KEkaONAaeiny/l/VOLz3nUIltQBm64TlPBu9iGN1cJdt0gWYXTfPWjTgqc7r0hOB34ay3bQ=="],"@mastra/schema-compat": ["@mastra/[email protected]", "", { "dependencies": { "json-schema-to-zod": "^2.7.0", "zod-from-json-schema": "^0.5.2" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" } }, "sha512-Dfis6eme6S9+b4Bf8TQjROvkET0Mz+S/bNfoExJPUcGafHX9u1lr80ilBN02D72K7eMFrbP78VbXq3rCMKv3NA=="],diff --git a/packages/db/src/permissions.ts b/packages/db/src/permissions.tsindex 1238c2c6..6f79025c 100644--- a/packages/db/src/permissions.ts+++ b/packages/db/src/permissions.ts@@ -19,6 +19,7 @@ export const PERMISSION_RESOURCES = ['integrations','agent_skills','agent_tools',+ 'agent_usage','custom_fields','issue_templates','workflow_config',@@ -39,14 +40,15 @@ export type Permissions = Record<PermissionResource, ResourcePermissions>;// Resources that do not carry the whole CRUD set: the danger zone is the project's// settings page and its deletion, the workflow config is read and written, an invite-// is created and revoked but never edited, and the repository settings are shown only-// to whoever may change them. A resource left out here supports every-// action. Unsupported cells stay present and false, so a caller reads any cell-// without a lookup.+// is created and revoked but never edited, the repository settings are shown only to+// whoever may change them, and what the agents spent is only read. A resource left out+// here supports every action. Unsupported cells stay present and false, so a caller+// reads any cell without a lookup.const RESOURCE_ACTIONS: Partial<Record<PermissionResource, readonly PermissionAction[]>> = {danger_zone: ['read', 'delete'],workflow_config: ['read', 'edit'],repositories: ['edit'],+ agent_usage: ['read'],members_invite: ['read', 'create', 'delete'],};