feat(sessions): show token usage and estimated cost in logs (#557)

* feat(sessions): show token usage and estimated cost in logs

* fix(sessions): compact the usage footer

* fix(ci): bypass Bun cache for Windows ARM64
This commit is contained in:
Yiling-J
2026-12-01 20:49:07 +08:00
committed by GitHub
parent e3fe5792b9
commit bfeabb8244
16 changed files with 292 additions and 60 deletions
+6 -5
View File
@@ -1,11 +1,12 @@
import type { EntryRecord } from '@earendil-works/pi-durable'
import type { AgentSessionLogs } from '@shumai/dtos'
import type { TypedResponse } from 'hono'
/** Pi records are already JSON; retain their public types without recursively remapping SDK schemas. */
export function agentEntriesResponse(
entries: EntryRecord[],
): Response & TypedResponse<EntryRecord[], 200, 'json'> {
return new Response(JSON.stringify(entries), {
export function agentEntriesResponse<T extends EntryRecord[] | AgentSessionLogs>(
body: T,
): Response & TypedResponse<T, 200, 'json'> {
return new Response(JSON.stringify(body), {
headers: { 'Content-Type': 'application/json; charset=UTF-8' },
}) as Response & TypedResponse<EntryRecord[], 200, 'json'>
}) as Response & TypedResponse<T, 200, 'json'>
}
+57 -8
View File
@@ -2,12 +2,14 @@ import { ROOT_CONVERSATION_ID, type EntryId, type EntryRecord } from '@earendil-
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { HTTPException } from 'hono/http-exception'
import { agentService } from '@shumai/core/src/agent/agent'
import { agentSessionService } from '@shumai/core/src/agent/session-service'
import { authzService } from '@shumai/core/src/authz/authz'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import type { AgentInfo } from '@shumai/dtos'
import app from './agent'
vi.mock('@shumai/core/src/agent/agent')
vi.mock('@shumai/core/src/agent/session-service')
vi.mock('@shumai/core/src/authz/authz')
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: {
@@ -352,15 +354,16 @@ describe('Agent API', () => {
})
describe('GET /agent-sessions/:sessionId/entries', () => {
const mockEntries: EntryRecord[] = [
{
id: 7 as EntryId,
conversationId: ROOT_CONVERSATION_ID,
kind: 'pi.user',
model: [{ role: 'user', content: 'Step 1', timestamp: 1 }],
},
]
it('returns entries of agent session if user is admin', async () => {
const mockEntries: EntryRecord[] = [
{
id: 7 as EntryId,
conversationId: ROOT_CONVERSATION_ID,
kind: 'pi.user',
model: [{ role: 'user', content: 'Step 1', timestamp: 1 }],
},
]
vi.mocked(agentService.getSessionEntries).mockResolvedValue(mockEntries)
const res = await app.request('/agent-sessions/session1/entries', {
@@ -373,6 +376,7 @@ describe('Agent API', () => {
expect(data[0].id).toBe(7)
expect(data[0].kind).toBe('pi.user')
expect(data[0].model[0].content).toBe('Step 1')
expect(agentSessionService.getLogs).not.toHaveBeenCalled()
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: undefined,
permission: 'Admin',
@@ -381,6 +385,51 @@ describe('Agent API', () => {
})
})
it.each([
{
inputTokens: 12800,
outputTokens: 1580,
cacheReadTokens: 10000,
totalTokens: 24380,
cost: 0.014,
},
null,
])('includes requested usage with the session entries (%j)', async (usage) => {
vi.mocked(agentSessionService.getLogs).mockResolvedValue({ entries: mockEntries, usage })
const res = await app.request('/agent-sessions/session1/entries?includeUsage=true')
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ entries: mockEntries, usage })
expect(agentSessionService.getLogs).toHaveBeenCalledWith('session1')
expect(agentService.getSessionEntries).not.toHaveBeenCalled()
})
it('checks session admin permission before loading requested usage', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValue(
new HTTPException(403, { message: 'Forbidden' }),
)
const res = await app.request('/agent-sessions/session1/entries?includeUsage=true')
expect(res.status).toBe(403)
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: undefined,
permission: 'Admin',
type: 'agentSession',
id: 'session1',
})
expect(agentSessionService.getLogs).not.toHaveBeenCalled()
})
it('rejects invalid includeUsage values', async () => {
const res = await app.request('/agent-sessions/session1/entries?includeUsage=invalid')
expect(res.status).toBe(400)
expect(agentSessionService.getLogs).not.toHaveBeenCalled()
expect(agentService.getSessionEntries).not.toHaveBeenCalled()
})
it('denies access if user is not admin', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValue(new Error('Forbidden'))
+22 -12
View File
@@ -1,5 +1,6 @@
import { zValidator } from '@hono/zod-validator'
import { agentService } from '@shumai/core/src/agent/agent'
import { agentSessionService } from '@shumai/core/src/agent/session-service'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import {
AgentInfo,
@@ -11,6 +12,7 @@ import {
} from '@shumai/dtos'
import { Hono } from 'hono'
import { HTTPException } from 'hono/http-exception'
import { z } from 'zod'
import { agentEntriesResponse } from './agent-entries'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
@@ -18,6 +20,8 @@ import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
const sessionEntriesQuerySchema = z.object({ includeUsage: z.enum(['true', 'false']).optional() })
const route = new Hono<{ Variables: { user: User } }>()
.get('/teams/:teamId/agents', async (c) => {
const teamId = c.req.param('teamId')
@@ -208,20 +212,26 @@ const route = new Hono<{ Variables: { user: User } }>()
return new Response(null, { status: 204 })
})
.get('/agent-sessions/:sessionId/entries', async (c) => {
const sessionId = c.req.param('sessionId')
const userReq = c.get('user')
.get(
'/agent-sessions/:sessionId/entries',
zValidator('query', sessionEntriesQuerySchema),
async (c) => {
const sessionId = c.req.param('sessionId')
const userReq = c.get('user')
await authzService.hasPermission({
user: userReq,
permission: Permission.Admin,
type: ResourceType.AgentSession,
id: sessionId,
})
await authzService.hasPermission({
user: userReq,
permission: Permission.Admin,
type: ResourceType.AgentSession,
id: sessionId,
})
const entries = await agentService.getSessionEntries({ sessionId })
return agentEntriesResponse(entries)
})
if (c.req.valid('query').includeUsage === 'true') {
return agentEntriesResponse(await agentSessionService.getLogs(sessionId))
}
return agentEntriesResponse(await agentService.getSessionEntries({ sessionId }))
},
)
.get('/teams/:teamId/agent-sessions', zValidator('query', paginationParamsSchema), async (c) => {
const teamId = c.req.param('teamId')
const userReq = c.get('user')