refactor(agent)!: migrate to Pi Durable and embed the agent queue (#525)

* refactor(agent)!: migrate sessions to Pi Durable

Replace patched AgentHarness storage with per-session SQLite and PostgreSQL commit mirroring. Migrate legacy history automatically and run agent queues with the main server.

BREAKING CHANGE: Remove standalone agent workers and return native Pi entry records from chat history APIs.

* fix(agent): constrain session log dialog scrolling

Keep the header visible and wrap long output while log entries and expanded records scroll within the dialog. Cover desktop and narrow viewports through the dashboard Sessions flow.

* fix(agent): hide entry IDs from session log card headers

Retain internal entry IDs in expanded raw records for debugging. Verify that card headers omit the IDs while raw JSON preserves them.

* test(e2e): handle browser wheel limits in session log checks

Verify that a normal wheel event moves the viewport before explicitly scrolling to the final record. Keep the dialog bounds, fixed header, wrapping, and expanded-record assertions.

* fix(agent): select model providers without inheriting unrelated auth

* fix(webui): prevent resize feedback when toggling agent panel

* test(agent): reproduce concurrent comment session races

* fix(agent): serialize comment sessions and deduplicate history

* docs(changelog): consolidate Pi Durable changes into one entry
This commit is contained in:
Yiling-J
2026-11-11 16:05:18 +08:00
committed by GitHub
parent 843a56304c
commit 35a0e82284
120 changed files with 7593 additions and 5972 deletions
+30 -73
View File
@@ -1,7 +1,8 @@
import { describe, expect, test } from 'vitest'
import { AgentService } from './agent'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { describe, expect, test } from 'vitest'
import { AgentService } from './agent'
import { appendSessionEntries } from './session-test-utils'
describe('AgentService', () => {
setupTestDbHooks()
@@ -477,56 +478,23 @@ describe('AgentService', () => {
expect(agents[0].modelRef).toBeDefined()
})
test('getSessionEntries follows parentId across shared sessions', async () => {
const db = prisma
const svc = new AgentService()
const { agent } = await setupTestData(db)
const mainSession = await db.agentSession.create({
data: {
agentId: agent.id,
type: 'comment',
cwd: '/tmp',
},
test('getSessionEntries reads independent native session transcripts', async () => {
const { agent } = await setupTestData(prisma)
const main = await prisma.agentSession.create({
data: { agentId: agent.id, type: 'comment', cwd: '/tmp' },
})
const threadSession = await db.agentSession.create({
data: {
agentId: agent.id,
type: 'comment',
cwd: '/tmp',
},
const thread = await prisma.agentSession.create({
data: { agentId: agent.id, type: 'comment', cwd: '/tmp' },
})
const entry1 = await db.agentSessionEntry.create({
data: {
id: '01ENTRY0000000000000000001',
sessionId: mainSession.id,
type: 'message',
parentId: null,
data: { text: 'Main Entry 1' },
},
})
const entry2 = await db.agentSessionEntry.create({
data: {
id: '01ENTRY0000000000000000002',
sessionId: threadSession.id,
type: 'message',
parentId: entry1.id,
data: { text: 'Thread Entry 2' },
},
})
await db.agentSession.update({
where: { id: threadSession.id },
data: { leafId: entry2.id },
})
const entries = await svc.getSessionEntries({ sessionId: threadSession.id })
expect(entries).toHaveLength(2)
expect(entries[0].id).toBe(entry1.id)
expect(entries[1].id).toBe(entry2.id)
await appendSessionEntries(main.id, [
{ kind: 'pi.user', model: [{ role: 'user', content: 'main', timestamp: 1 }] },
])
const records = await appendSessionEntries(thread.id, [
{ kind: 'pi.user', model: [{ role: 'user', content: 'copied context', timestamp: 1 }] },
{ kind: 'pi.user', model: [{ role: 'user', content: 'thread', timestamp: 2 }] },
])
await prisma.agentSession.delete({ where: { id: main.id } })
expect(await new AgentService().getSessionEntries({ sessionId: thread.id })).toEqual(records)
})
test('getSessionEntries dynamically attaches details.thread on custom_message entries with replies', async () => {
@@ -577,34 +545,23 @@ describe('AgentService', () => {
},
})
const entry = await db.agentSessionEntry.create({
data: {
id: rootComment.id,
sessionId: session.id,
type: 'custom_message',
parentId: null,
await appendSessionEntries(session.id, [
{
kind: 'shumai.message',
data: {
customType: 'shumai_message',
content: 'Top-level comment',
display: true,
details: { user: { id: user.id, name: user.name } },
displayText: 'Top-level comment',
timestamp: 1,
context: { id: rootComment.id, thread: { id: rootComment.id, replyCount: 1 } },
sourceCommentId: rootComment.id,
},
model: [{ role: 'user', content: 'Top-level comment', timestamp: 1 }],
},
})
await db.agentSession.update({
where: { id: session.id },
data: { leafId: entry.id },
})
])
const entries = await svc.getSessionEntries({ sessionId: session.id })
expect(entries).toHaveLength(1)
expect(entries[0].id).toBe(rootComment.id)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const entryDetails = (entries[0].entry as any).details
expect(entryDetails?.thread).toEqual({
id: rootComment.id,
replyCount: 1,
expect(entries[0]).toMatchObject({
kind: 'shumai.message',
data: { context: { thread: { id: rootComment.id, replyCount: 1 } } },
})
})
})
+17 -104
View File
@@ -1,28 +1,29 @@
import { prisma, type Prisma, type TeamMemberRole } from '@shumai/db'
import {
CreateAgentParams,
DeleteAgentParams,
ListAgentsParams,
UpdateAgentParams,
AgentSessionInfo,
AgentInfo,
AgentType,
DEFAULT_DENIED_TOOLS,
} from '@shumai/dtos'
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
import {
paginateQuery,
type PaginatedData,
type PaginationParams,
} from '@shumai/core/src/pagination'
import '@shumai/db/src/prisma-json-types'
import { s3Service } from '@shumai/core/src/s3/s3'
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
import { getAllowedAgentRoles } from './permissions'
import { isPresetAvatarId, getPresetAvatarBuffer, getPresetAvatarStorageKey } from './presets'
import { prisma, type Prisma, type TeamMemberRole } from '@shumai/db'
import '@shumai/db/src/prisma-json-types'
import {
AgentInfo,
AgentSessionInfo,
AgentType,
CreateAgentParams,
DEFAULT_DENIED_TOOLS,
DeleteAgentParams,
ListAgentsParams,
UpdateAgentParams,
} from '@shumai/dtos'
import AdmZip from 'adm-zip'
import * as fs from 'fs'
import * as path from 'path'
import { getAllowedAgentRoles } from './permissions'
import { getPresetAvatarBuffer, getPresetAvatarStorageKey, isPresetAvatarId } from './presets'
import { agentSessionService } from './session-service'
const agentInclude = {
user: true,
@@ -572,95 +573,7 @@ export class AgentService {
}
async getSessionEntries(params: { sessionId: string }) {
const session = await this.prismaClient.agentSession.findUnique({
where: { id: params.sessionId },
select: { leafId: true },
})
if (!session?.leafId) {
return []
}
interface EntryRow {
id: string
// eslint-disable-next-line @typescript-eslint/naming-convention
session_id: string | null
type: string | null
// eslint-disable-next-line @typescript-eslint/naming-convention
parent_id: string | null
// eslint-disable-next-line @typescript-eslint/naming-convention
created_at: Date
data: unknown
}
const rows = await this.prismaClient.$queryRaw<EntryRow[]>`
WITH RECURSIVE entry_path AS (
SELECT id, session_id, type, parent_id, created_at, data, 1 AS depth
FROM agent_session_entries
WHERE id = ${session.leafId}
UNION ALL
SELECT e.id, e.session_id, e.type, e.parent_id, e.created_at, e.data, ep.depth + 1
FROM agent_session_entries e
INNER JOIN entry_path ep ON e.id = ep.parent_id
)
SELECT id, session_id, type, parent_id, created_at, data
FROM entry_path
ORDER BY depth DESC;
`
const entryIds = rows.map((r) => r.id)
const threadReplyCountMap = new Map<string, number>()
if (entryIds.length > 0) {
const threadCounts = await this.prismaClient.assetComment.groupBy({
by: ['replyToId'],
where: {
replyToId: { in: entryIds },
message: { not: '__CHAT__' },
},
_count: {
id: true,
},
})
for (const tc of threadCounts) {
if (tc.replyToId) {
threadReplyCountMap.set(tc.replyToId, tc._count.id)
}
}
}
return rows.map((r) => {
const payload = (r.data as Record<string, unknown>) || {}
const count = threadReplyCountMap.get(r.id)
let details = payload.details as Record<string, unknown> | undefined
if (count !== undefined && count > 0 && r.type === 'custom_message') {
details = {
...details,
thread: {
id: r.id,
replyCount: count,
},
}
}
const entryObj = {
id: r.id,
type: r.type || 'message',
parentId: r.parent_id,
timestamp: r.created_at.toISOString(),
...payload,
...(details ? { details } : {}),
}
return {
id: r.id,
sessionId: r.session_id || params.sessionId,
type: r.type,
parentId: r.parent_id,
data: details !== payload.details ? { ...payload, details } : r.data,
createdAt: r.created_at,
entry: entryObj,
}
})
return agentSessionService.getEntries(params.sessionId)
}
async listSessions(
+116
View File
@@ -0,0 +1,116 @@
import { BACKGROUND_CONTEXT } from '@earendil-works/chord/context'
import type { Seq, StorageWrite } from '@earendil-works/pi-durable'
import { openNodeSqliteStorage } from '@earendil-works/pi-durable/storage/sqlite/node'
import { prisma } from '@shumai/db'
import { randomUUID } from 'node:crypto'
import { mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
// Process-owned copies prevent an API replica from replacing a live writer's SQLite files.
const instance = randomUUID()
const root = join(
process.env.AGENT_SESSION_CACHE_DIR || join(tmpdir(), 'shumai-sessions'),
instance,
)
export async function openSessionCache(sessionId: string, mode: 'read' | 'write') {
const directory = join(root, mode, encodeURIComponent(sessionId))
await mkdir(directory, { recursive: true, mode: 0o700 })
const path = join(directory, 'session.sqlite')
const marker = join(directory, 'sync.json')
const latest = await prisma.agentSessionCommit.findFirst({
where: { sessionId },
orderBy: { seq: 'desc' },
select: { seq: true },
})
const head = Number(latest?.seq ?? 0)
if (!Number.isSafeInteger(head))
throw new Error('Session commit sequence exceeds the supported range')
let seq = 0
let reusable = false
try {
if (!(await stat(path)).isFile()) throw new Error('SQLite cache missing')
const value: unknown = JSON.parse(await readFile(marker, 'utf8'))
if (
value &&
typeof value === 'object' &&
'seq' in value &&
typeof value.seq === 'number' &&
'clean' in value &&
value.clean === true &&
value.seq <= head
) {
seq = value.seq
reusable = true
}
} catch {
/* A missing/uncertain marker requires rebuilding the disposable copy. */
}
const save = async (clean: boolean) => {
await writeFile(`${marker}.tmp`, JSON.stringify({ clean, seq }), { mode: 0o600 })
await rename(`${marker}.tmp`, marker)
}
const remove = async () => {
for (const suffix of ['', '-wal', '-shm']) await rm(`${path}${suffix}`, { force: true })
seq = 0
}
if (!reusable) await remove()
let storage
try {
storage = await openNodeSqliteStorage(path)
} catch (error) {
if (!reusable) throw error
await remove()
storage = await openNodeSqliteStorage(path)
}
try {
await save(false)
while (seq < head) {
const commits = await prisma.agentSessionCommit.findMany({
where: { sessionId, seq: { gt: BigInt(seq), lte: BigInt(head) } },
orderBy: { seq: 'asc' },
take: 100,
})
if (commits.length === 0) throw new Error(`Session ${sessionId} has a commit gap`)
const writes = commits.map(({ data }) => {
if (data.version !== 1 || !Array.isArray(data.writes))
throw new Error('Unsupported session commit format')
return data.writes as unknown as StorageWrite[]
})
const receipts: Array<{ index: number; seq: Seq }> = []
const result = await storage.commit(
writes,
(index, storedSeq) => {
receipts.push({ index, seq: storedSeq })
},
BACKGROUND_CONTEXT,
)
for (const receipt of receipts) {
if (Number(commits[receipt.index].seq) !== receipt.seq)
throw new Error('Session commit sequence mismatch')
seq = receipt.seq
}
if (result.stored !== commits.length)
throw result.refused ?? new Error('Session restoration refused')
}
await save(true)
} catch (error) {
await storage.close(BACKGROUND_CONTEXT)
throw error
}
return {
storage,
seq,
path,
dirty: () => save(false),
clean: async (next?: Seq) => {
if (next !== undefined) seq = next
await save(true)
},
}
}
export async function removeSessionCaches() {
await rm(root, { recursive: true, force: true })
}
+165
View File
@@ -0,0 +1,165 @@
import type { ImageContent, Message, ToolResultMessage } from '@earendil-works/pi-ai'
import type { Cursor, EntryRecord, HookApi, StorageWrite } from '@earendil-works/pi-durable'
import { serializeContextToXml, shumaiMessageContextSchema } from '@shumai/dtos'
import { s3Service } from '../s3/s3'
import { agentService } from './agent'
export const S3_PLACEHOLDER = '__S3_DATA__'
export const SKILL_PLACEHOLDER = '__SKILL_CONTENT__'
function contentReferences(value: unknown): { sourceKeys: string[]; skillId?: string } {
if (!value || typeof value !== 'object') return { sourceKeys: [] }
const record = value as Record<string, unknown>
return {
sourceKeys: Array.isArray(record.sourceKeys)
? record.sourceKeys.filter((key): key is string => typeof key === 'string')
: [],
skillId: typeof record.skillId === 'string' ? record.skillId : undefined,
}
}
function compactMessage(message: Message, entryData: unknown): Message {
if (message.role !== 'toolResult' && message.role !== 'user') return message
const refs = contentReferences(message.role === 'toolResult' ? message.details : entryData)
if (typeof message.content === 'string') return message
let imageIndex = 0
return {
...message,
content: message.content.map((block) => {
if (block.type === 'image') {
const key = refs.sourceKeys[imageIndex++]
return key ? { ...block, data: S3_PLACEHOLDER } : block
}
if (
message.role === 'toolResult' &&
message.toolName === 'read_skill' &&
!message.isError &&
refs.skillId &&
block.type === 'text'
)
return { ...block, text: SKILL_PLACEHOLDER }
return block
}),
}
}
/** Only immutable entries are rewritten. Durable's document deltas keep their original bases. */
export function compactSessionWrites(writes: readonly StorageWrite[]): StorageWrite[] {
return writes.map((write) =>
write.type === 'entry'
? {
...write,
value: {
...write.value,
model: write.value.model?.map((m) => compactMessage(m, write.value.data)),
},
}
: write,
)
}
export async function hydrateMessages(
messages: readonly Message[],
entryData?: unknown,
): Promise<Message[]> {
return Promise.all(
messages.map(async (message): Promise<Message> => {
if (message.role !== 'toolResult' && message.role !== 'user') return message
if (typeof message.content === 'string') return message
const refs = contentReferences(message.role === 'toolResult' ? message.details : entryData)
let imageIndex = 0
const skillText =
message.role === 'toolResult' &&
message.toolName === 'read_skill' &&
!message.isError &&
refs.skillId
? await agentService.getSkillContent(refs.skillId)
: undefined
const content = await Promise.all(
message.content.map(async (block) => {
if (block.type === 'image') {
const key = refs.sourceKeys[imageIndex++]
if (block.data === S3_PLACEHOLDER && key) {
const { buffer } = await s3Service.getObject(process.env.S3_BUCKET || 'shumai', key)
return { ...block, data: buffer.toString('base64') } satisfies ImageContent
}
}
if (block.type === 'text' && skillText !== undefined) return { ...block, text: skillText }
return block
}),
)
return { ...message, content } as ToolResultMessage | Extract<Message, { role: 'user' }>
}),
)
}
export async function hydrateEntry(entry: EntryRecord): Promise<EntryRecord> {
if (!entry.model) return entry
let model = await hydrateMessages(entry.model, entry.data)
if (
entry.kind === 'shumai.message' &&
entry.data &&
typeof entry.data === 'object' &&
!Array.isArray(entry.data)
) {
const parsed = shumaiMessageContextSchema.safeParse(entry.data.context)
if (parsed.success) {
const xml = serializeContextToXml(parsed.data)
model = model.map((message) => {
if (message.role !== 'user') return message
const content =
typeof message.content === 'string'
? message.content
: message.content
.filter((b) => b.type === 'text')
.map((b) => b.text)
.join('\n')
if (!xml || content.includes('<context>')) return message
return {
...message,
content:
typeof message.content === 'string'
? `${message.content}\n\n${xml}`
: [...message.content, { type: 'text' as const, text: xml }],
}
})
}
}
return { ...entry, model }
}
/** An admitted input may still be in Durable's warm context before its first storage read. */
export async function hydrateRequest(
messages: readonly Message[],
api: HookApi,
context: import('@earendil-works/chord/context').Context,
) {
const waiting = new Set(
messages
.filter(
(m) =>
m.role === 'user' &&
Array.isArray(m.content) &&
m.content.some((b) => b.type === 'image' && b.data === S3_PLACEHOLDER),
)
.map((m) => m.timestamp),
)
const references = new Map<number, unknown>()
let cursor: Cursor | undefined
while (waiting.size) {
const page = await api.entries({ order: 'descending' }, 100, cursor, context)
for (const entry of page.items) {
for (const message of entry.model ?? []) {
if (message.role === 'user' && waiting.delete(message.timestamp))
references.set(message.timestamp, entry.data)
}
}
if (!page.next) break
cursor = page.next
}
return (
await Promise.all(
messages.map((message) => hydrateMessages([message], references.get(message.timestamp))),
)
).flat()
}
@@ -0,0 +1,240 @@
import { openSessionCache } from './session-cache'
import { BACKGROUND_CONTEXT as context } from '@earendil-works/chord/context'
import { createModels, fauxAssistantMessage, fauxProvider } from '@earendil-works/pi-ai'
import { Harness, createRegistry, UsageDoc } from '@earendil-works/pi-durable'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { readFile } from 'node:fs/promises'
import { describe, expect, it } from 'vitest'
import { agentSessionService } from './session-service'
const migration = new URL(
'../../../db/prisma/migrations/20261110070817_pi_durable_session_commits/migration.sql',
import.meta.url,
)
async function backfill() {
const sql = await readFile(migration, 'utf8')
const start = sql.indexOf('DO $migration$')
const checkpoint = await readFile(
new URL(
'../../../db/prisma/migrations/20261110072953_agent_session_usage_checkpoint/migration.sql',
import.meta.url,
),
'utf8',
)
await prisma.$transaction(async (tx) => {
await tx.$executeRawUnsafe(sql.slice(start, sql.lastIndexOf('COMMIT;')))
await tx.$executeRawUnsafe(checkpoint.slice(checkpoint.indexOf('-- Historical')))
const preserve = await readFile(
new URL(
'../../../db/prisma/migrations/20261110094140_preserve_session_json_nulls/migration.sql',
import.meta.url,
),
'utf8',
)
await tx.$executeRawUnsafe(
preserve.slice(preserve.indexOf('CREATE FUNCTION'), preserve.lastIndexOf('COMMIT;')),
)
})
}
describe('SQL migration to Pi Durable', () => {
setupTestDbHooks()
async function fixture() {
const team = await prisma.team.create({ data: { name: 'Migration team' } })
const user = await prisma.user.create({
data: { name: 'Migration agent', email: 'pi-migration@example.test', type: 'agent' },
})
const agent = await prisma.agent.create({
data: {
id: user.id,
teamId: team.id,
type: 'chat',
config: { provider: 'faux', model: 'faux-1' },
},
})
const parent = await prisma.agentSession.create({
data: { agentId: agent.id, cwd: '/migration', leafId: 'legacy-root' },
})
const child = await prisma.agentSession.create({
data: { agentId: agent.id, cwd: '/migration', leafId: 'legacy-reply' },
})
await prisma.agentSessionEntry.createMany({
data: [
{
id: 'legacy-root',
sessionId: parent.id,
type: 'custom_message',
data: {
customType: 'shumai_message',
content: 'Original question',
details: {
annotation: true,
annotations: [{ type: 'line' }],
currentAsset: { id: 'asset', name: 'Image', type: 'file' },
},
},
},
{
id: 'legacy-reply',
sessionId: child.id,
parentId: 'legacy-root',
type: 'custom_message',
data: { customType: 'shumai_message', content: 'Follow-up', details: {} },
},
],
})
return { team, parent, child }
}
it('copies inherited records, preserves annotations and opens as a continuable native session', async () => {
const { parent, child } = await fixture()
await backfill()
expect(await agentSessionService.getEntries(parent.id)).toHaveLength(1)
const entries = await agentSessionService.getEntries(child.id)
expect(entries.map((entry) => entry.id)).toEqual([7, 9])
expect(entries[0].data).toMatchObject({
displayText: 'Original question',
context: { annotation: true, id: `chat:${child.id}:legacy-legacy-root` },
})
expect(
await agentSessionService.getEntryForRequest(child.id, 'legacy-legacy-root'),
).toMatchObject({ id: 7 })
const faux = fauxProvider()
faux.setResponses([fauxAssistantMessage('Continued migrated conversation')])
const models = createModels()
models.setProvider(faux.provider)
await agentSessionService.withWriter(child.id, async (storage) => {
const harness = await Harness.open(storage, { models, registry: createRegistry() }, context)
try {
const root = await harness.root(context)
await root.configure(
{ model: { provider: faux.provider.id, modelId: faux.getModel().id } },
context,
)
const settled = await (
await root.submit({ type: 'input', content: 'Continue', requestId: 'continued' }, context)
).wait(context)
expect(settled.status).toBe('done')
} finally {
await harness.close(context)
}
})
const count = await prisma.agentSessionCommit.count({ where: { sessionId: child.id } })
await backfill()
expect(await prisma.agentSessionCommit.count({ where: { sessionId: child.id } })).toBe(count)
})
it('preserves compact tool results, remaps annotation references, compaction boundaries and historical usage', async () => {
const { child } = await fixture()
const assistant = fauxAssistantMessage([
{
type: 'toolCall',
id: 'read',
name: 'read_asset',
arguments: { annotationId: 'legacy-root' },
},
])
assistant.usage = {
input: 10,
output: 5,
cacheRead: 2,
cacheWrite: 0,
totalTokens: 17,
cost: { input: 0.1, output: 0.1, cacheRead: 0, cacheWrite: 0, total: 0.2 },
}
await prisma.agentSessionEntry.createMany({
data: [
{
id: 'legacy-call',
parentId: 'legacy-reply',
sessionId: child.id,
type: 'message',
data: { message: assistant },
},
{
id: 'legacy-tool',
parentId: 'legacy-call',
sessionId: child.id,
type: 'message',
data: {
message: {
role: 'toolResult',
toolCallId: 'read',
toolName: 'read_asset',
content: [{ type: 'image', data: '__S3_DATA__', mimeType: 'image/png' }],
details: { sourceKeys: ['historical-image'], exitCode: null },
isError: false,
timestamp: 1,
},
},
},
{
id: 'legacy-compact',
parentId: 'legacy-tool',
sessionId: child.id,
type: 'compaction',
data: { summary: 'Earlier discussion', firstKeptEntryId: 'legacy-call' },
},
{
id: 'legacy-branch',
parentId: 'legacy-compact',
sessionId: child.id,
type: 'branch_summary',
data: { summary: 'Copied branch context' },
},
],
})
await prisma.agentSession.update({ where: { id: child.id }, data: { leafId: 'legacy-branch' } })
await backfill()
const entries = await agentSessionService.getEntries(child.id)
expect(entries[2].model?.[0]).toMatchObject({
content: [{ arguments: { annotationId: `chat:${child.id}:legacy-legacy-root` } }],
})
expect(entries[3].model?.[0]).toMatchObject({
content: [{ data: '__S3_DATA__' }],
details: { sourceKeys: ['historical-image'], exitCode: null },
})
expect(entries[4]).toMatchObject({ kind: 'pi.compaction', head: entries[2].id })
expect(JSON.stringify(entries[5].model)).toContain('Copied branch context')
expect(
(await prisma.agentSession.findUniqueOrThrow({ where: { id: child.id } })).accountedUsage,
).toMatchObject({ totalTokens: 17, cost: 0.2 })
// Read the native ledger without hydrating image references.
const cache = await openSessionCache(child.id, 'read')
const harness = await Harness.open(
cache.storage,
{ models: createModels(), registry: createRegistry() },
context,
)
try {
expect(
(await harness.snapshot(UsageDoc, (await harness.root(context)).id, context))?.models[
'faux/faux-1'
].totalTokens,
).toBe(17)
} finally {
await harness.close(context)
}
})
it('rejects missing ancestry before writing any converted records', async () => {
const { child } = await fixture()
await prisma.agentSessionEntry.update({
where: { id: 'legacy-reply' },
data: { parentId: 'missing' },
})
await expect(backfill()).rejects.toThrow('ancestor is missing')
expect(await prisma.agentSessionCommit.count({ where: { sessionId: child.id } })).toBe(0)
})
it('rejects cyclic ancestry', async () => {
await fixture()
await prisma.agentSessionEntry.update({
where: { id: 'legacy-root' },
data: { parentId: 'legacy-reply' },
})
await expect(backfill()).rejects.toThrow('cyclic history')
})
})
@@ -0,0 +1,196 @@
import { BACKGROUND_CONTEXT as context } from '@earendil-works/chord/context'
import { createModels, fauxAssistantMessage, fauxProvider } from '@earendil-works/pi-ai'
import { Harness, UsageDoc, createRegistry } from '@earendil-works/pi-durable'
import { prisma } from '@shumai/db'
import { acquireAdvisoryLock } from '@shumai/db/src/advisory-lock'
import { setupTestDbHooks } from '@shumai/db/test'
import { rm, writeFile } from 'node:fs/promises'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { openSessionCache } from './session-cache'
import { agentSessionService } from './session-service'
import { appendSessionEntries } from './session-test-utils'
describe('Native session storage and PostgreSQL synchronization', () => {
setupTestDbHooks()
afterEach(async () => {
vi.restoreAllMocks()
await agentSessionService.closeAll()
})
async function fixture() {
const team = await prisma.team.create({ data: { name: 'Storage team' } })
const user = await prisma.user.create({
data: { name: 'Agent', email: 'storage@example.test', type: 'agent' },
})
const agent = await prisma.agent.create({
data: {
id: user.id,
teamId: team.id,
type: 'chat',
config: { provider: 'faux', model: 'faux-1' },
},
})
const session = await prisma.agentSession.create({ data: { agentId: agent.id, cwd: '/test' } })
return { team, session }
}
it('reconstructs missing SQLite files and preserves native IDs, ordering and pagination', async () => {
const { session } = await fixture()
const entries = await appendSessionEntries(
session.id,
Array.from({ length: 25 }, (_, i) => ({
kind: 'pi.user',
model: [{ role: 'user' as const, content: `message ${i}`, timestamp: i }],
})),
)
await agentSessionService.closeAll()
expect(await agentSessionService.getEntries(session.id)).toEqual(entries)
const first = await agentSessionService.listEntries(session.id)
expect(first.items).toHaveLength(20)
const next = await agentSessionService.listEntries(session.id, {
after: first.items.at(-1)!.id,
})
expect(next.items).toEqual(entries.slice(20))
const cursor = await agentSessionService.listEntries(session.id, { cursor: first.next })
expect(cursor.items).toEqual(next.items)
expect(await prisma.agentSessionEntry.count({ where: { sessionId: session.id } })).toBe(0)
})
it.each(['missing', 'corrupt', 'dirty'] as const)(
'rebuilds a %s local cache from mirrored commits',
async (failure) => {
const { session } = await fixture()
const entries = await appendSessionEntries(session.id, [
{ kind: 'pi.user', model: [{ role: 'user', content: 'safe', timestamp: 1 }] },
])
const cache = await openSessionCache(session.id, 'read')
await cache.storage.close(context)
if (failure === 'missing') await rm(cache.path)
else if (failure === 'corrupt') await writeFile(cache.path, 'invalid sqlite')
else await cache.dirty()
expect(await agentSessionService.getEntries(session.id)).toEqual(entries)
},
)
it('holds the session ownership lock until close and permits cancellation while waiting', async () => {
const { session } = await fixture()
const writer = await agentSessionService.openWriter(session.id)
const abort = new AbortController()
const waiting = acquireAdvisoryLock(`agent-session:${session.id}`, abort.signal)
abort.abort(new Error('cancelled'))
await expect(waiting).rejects.toThrow('cancelled')
await writer.storage.close(context)
const next = await acquireAdvisoryLock(`agent-session:${session.id}`)
await next.release()
})
it('refuses a fenced writer and rebuilds its unacknowledged SQLite commit', async () => {
const { session } = await fixture()
const writer = await agentSessionService.openWriter(session.id)
await prisma.agentSession.update({
where: { id: session.id },
data: { writerVersion: { increment: 1 } },
})
await expect(
writer.storage.commit(
[
[
{
type: 'conversation',
value: { id: 1 as import('@earendil-works/pi-durable').ConversationId },
},
],
],
() => {
throw new Error('must not acknowledge')
},
context,
),
).rejects.toThrow('ownership was lost')
await writer.storage.close(context)
expect(await agentSessionService.getEntries(session.id)).toEqual([])
})
it('commits usage and transcript together, and does not bill replay or completed request recovery', async () => {
const { team, session } = await fixture()
const faux = fauxProvider()
const answer = fauxAssistantMessage('paid answer')
answer.usage = {
input: 12,
output: 7,
cacheRead: 3,
cacheWrite: 0,
totalTokens: 22,
cost: { input: 0.1, output: 0.2, cacheRead: 0, cacheWrite: 0, total: 0.3 },
}
faux.setResponses([answer])
const models = createModels()
models.setProvider(faux.provider)
const run = async () => {
const writer = await agentSessionService.openWriter(session.id, context, { teamId: team.id })
const harness = await Harness.open(
writer.storage,
{ models, registry: createRegistry() },
context,
)
try {
const root = await harness.root(context)
await root.configure(
{ model: { provider: faux.provider.id, modelId: faux.getModel().id } },
context,
)
return await (
await root.submit({ type: 'input', requestId: 'once', content: 'question' }, context)
).wait(context)
} finally {
await harness.close(context)
}
}
const receipt = await run()
await agentSessionService.closeAll()
expect(await run()).toEqual(receipt)
const usage = await prisma.aiUsage.findFirstOrThrow({ where: { teamId: team.id } })
const checkpoint = (await prisma.agentSession.findUniqueOrThrow({ where: { id: session.id } }))
.accountedUsage!
expect(Number(usage.totalTokens)).toBeGreaterThan(0)
expect(Number(usage.totalTokens)).toBe(checkpoint.totalTokens)
expect(Number(usage.cost)).toBe(checkpoint.cost)
})
it('rolls back usage if PostgreSQL cannot persist the native commit', async () => {
const { team, session } = await fixture()
const writer = await agentSessionService.openWriter(session.id, context, { teamId: team.id })
const harness = await Harness.open(
writer.storage,
{ models: createModels(), registry: createRegistry() },
context,
)
const root = await harness.root(context)
const failure = vi
.spyOn(prisma.agentSessionCommit, 'createMany')
.mockRejectedValueOnce(new Error('mirror unavailable'))
await expect(
root.commit(async (tx) => {
const usage = await tx.doc(UsageDoc, root.id)
usage.models['faux/test'] = fauxAssistantMessage('answer').usage
usage.models['faux/test'].totalTokens = 25
await tx.appendEntry(root.id, {
kind: 'pi.assistant',
model: [fauxAssistantMessage('answer')],
})
}, context),
).rejects.toThrow('mirror unavailable')
failure.mockRestore()
await harness.close(context)
expect(await prisma.aiUsage.count({ where: { teamId: team.id } })).toBe(0)
expect(await agentSessionService.getEntries(session.id)).toEqual([])
})
it('deletes mirrored records with their session and rejects subsequent history reads', async () => {
const { session } = await fixture()
await appendSessionEntries(session.id, [{ kind: 'pi.user', data: {} }])
await prisma.agentSession.delete({ where: { id: session.id } })
expect(await prisma.agentSessionCommit.count({ where: { sessionId: session.id } })).toBe(0)
await expect(agentSessionService.getEntries(session.id)).rejects.toThrow('Session not found')
})
})
+248
View File
@@ -0,0 +1,248 @@
import { BACKGROUND_CONTEXT, type Context } from '@earendil-works/chord/context'
import {
ROOT_CONVERSATION_ID,
type Cursor,
type EntryId,
type EntryRecord,
type Storage,
type UsageState,
} from '@earendil-works/pi-durable'
import { prisma, type Prisma, type TeamMemberRole } from '@shumai/db'
import { acquireAdvisoryLock } from '@shumai/db/src/advisory-lock'
import { AiUsageService } from '../ai-usage/ai-usage'
import { quotaService } from '../quota/quota-service'
import { openSessionCache, removeSessionCaches } from './session-cache'
import { hydrateStorage, synchronizeStorage, type CommitReceipt } from './session-storage'
type UsageOwner = { teamId: string; userId?: string; role?: TeamMemberRole | null }
export async function readSessionUsage(storage: Storage): Promise<PrismaJson.AgentSessionUsage> {
const doc = await storage.findDocument(
{ kind: 'pi.usage', scope: { kind: 'conversation', conversationId: ROOT_CONVERSATION_ID } },
'current',
BACKGROUND_CONTEXT,
)
const stored = doc ? await storage.document(doc.id, 'current', BACKGROUND_CONTEXT) : undefined
const state = stored?.value as unknown as UsageState | undefined
const totals = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, totalTokens: 0, cost: 0 }
for (const usage of Object.values(state?.models ?? {})) {
totals.inputTokens += usage.input
totals.outputTokens += usage.output
totals.cacheReadTokens += usage.cacheRead
totals.totalTokens += usage.totalTokens
totals.cost += usage.cost.total
}
return totals
}
export class AgentSessionService {
private readonly readers = new Map<string, Promise<unknown>>()
private readonly writers = new Set<Storage>()
async openWriter(sessionId: string, context: Context = BACKGROUND_CONTEXT, owner?: UsageOwner) {
const lock = await acquireAdvisoryLock(`agent-session:${sessionId}`, context.abortSignal)
let storage: Storage | undefined
try {
const session = await prisma.agentSession.update({
where: { id: sessionId },
data: { writerVersion: { increment: 1 } },
})
const cache = await openSessionCache(sessionId, 'write')
let head = cache.seq
storage = hydrateStorage(
synchronizeStorage(cache.storage, {
dirty: cache.dirty,
clean: cache.clean,
persist: async (commits: readonly CommitReceipt[]) => {
lock.signal.throwIfAborted()
if (!commits.length) return
await prisma.$transaction(async (tx) => {
const rows = await tx.$queryRaw<
Array<{ writerVersion: number }>
>`SELECT writer_version AS "writerVersion" FROM agent_sessions WHERE id = ${sessionId} FOR UPDATE`
if (rows[0]?.writerVersion !== session.writerVersion)
throw new Error('Session writer ownership was lost')
const latest = await tx.agentSessionCommit.findFirst({
where: { sessionId },
orderBy: { seq: 'desc' },
select: { seq: true },
})
if (Number(latest?.seq ?? 0) !== head)
throw new Error('Session changed while writing')
if (owner)
await this.recordUsage(sessionId, await readSessionUsage(cache.storage), owner, tx)
await tx.agentSessionCommit.createMany({
data: commits.map(({ seq, writes }) => ({
sessionId,
seq: BigInt(seq),
data: JSON.parse(
JSON.stringify({ version: 1, writes }),
) as PrismaJson.AgentSessionCommitData,
})),
})
})
head = commits[commits.length - 1].seq
},
}),
)
const close = storage.close.bind(storage)
let closed = false
const owned = storage
owned.close = async (context) => {
if (closed) return
closed = true
this.writers.delete(owned)
try {
await close(context)
} finally {
await lock.release()
}
}
this.writers.add(owned)
return { storage: owned, signal: lock.signal }
} catch (error) {
try {
await storage?.close(BACKGROUND_CONTEXT)
} finally {
await lock.release()
}
throw error
}
}
async withWriter<T>(
sessionId: string,
use: (storage: Storage, signal: AbortSignal) => Promise<T>,
context: Context = BACKGROUND_CONTEXT,
): Promise<T> {
const opened = await this.openWriter(sessionId, context)
try {
return await use(opened.storage, opened.signal)
} finally {
await opened.storage.close(BACKGROUND_CONTEXT)
}
}
async closeAll() {
await Promise.allSettled([...this.writers].map((storage) => storage.close(BACKGROUND_CONTEXT)))
await Promise.allSettled(this.readers.values())
await removeSessionCaches()
}
private async read<T>(sessionId: string, use: (storage: Storage) => Promise<T>): Promise<T> {
const previous = this.readers.get(sessionId)
const current = (async () => {
await previous?.catch(() => {})
const session = await prisma.agentSession.findUnique({
where: { id: sessionId },
select: { id: true },
})
if (!session) throw new Error('Session not found')
const cache = await openSessionCache(sessionId, 'read')
try {
return await use(cache.storage)
} finally {
await cache.storage.close(BACKGROUND_CONTEXT)
}
})()
this.readers.set(sessionId, current)
try {
return await current
} finally {
if (this.readers.get(sessionId) === current) this.readers.delete(sessionId)
}
}
async listEntries(
sessionId: string,
options: { after?: EntryId; limit?: number; cursor?: Cursor } = {},
) {
return this.read(sessionId, async (storage) => {
if (!(await storage.conversation(ROOT_CONVERSATION_ID, BACKGROUND_CONTEXT)))
return { items: [], next: undefined }
return storage.scanEntries(
{
conversationId: ROOT_CONVERSATION_ID,
order: 'ascending',
...(options.after === undefined ? {} : { minEntryId: (options.after + 1) as EntryId }),
},
options.limit ?? 20,
options.cursor,
BACKGROUND_CONTEXT,
)
})
}
async getEntries(sessionId: string): Promise<EntryRecord[]> {
return this.read(sessionId, async (storage) => {
const entries: EntryRecord[] = []
if (!(await storage.conversation(ROOT_CONVERSATION_ID, BACKGROUND_CONTEXT))) return entries
let cursor: Cursor | undefined
do {
const page = await storage.scanEntries(
{ conversationId: ROOT_CONVERSATION_ID, order: 'ascending' },
100,
cursor,
BACKGROUND_CONTEXT,
)
entries.push(...page.items)
cursor = page.next
} while (cursor)
return entries
})
}
async getEntryForRequest(sessionId: string, requestId: string) {
return this.read(sessionId, async (storage) => {
const submission = await storage.submissionByRequest(
ROOT_CONVERSATION_ID,
requestId,
BACKGROUND_CONTEXT,
)
return submission?.entry === undefined
? undefined
: (await storage.entry(submission.entry, BACKGROUND_CONTEXT))?.entry
})
}
async recordUsage(
sessionId: string,
totals: PrismaJson.AgentSessionUsage,
owner: UsageOwner,
transaction?: Prisma.TransactionClient,
): Promise<PrismaJson.AgentSessionUsage> {
const account = async (tx: Prisma.TransactionClient) => {
await tx.$queryRaw`SELECT id FROM agent_sessions WHERE id = ${sessionId} FOR UPDATE`
const session = await tx.agentSession.findUniqueOrThrow({
where: { id: sessionId },
select: { accountedUsage: true },
})
const previous = session.accountedUsage
const delta = {
inputTokens: Math.max(0, totals.inputTokens - (previous?.inputTokens ?? 0)),
outputTokens: Math.max(0, totals.outputTokens - (previous?.outputTokens ?? 0)),
cacheReadTokens: Math.max(0, totals.cacheReadTokens - (previous?.cacheReadTokens ?? 0)),
totalTokens: Math.max(0, totals.totalTokens - (previous?.totalTokens ?? 0)),
cost: Math.max(0, totals.cost - (previous?.cost ?? 0)),
}
if (delta.totalTokens || delta.cost) {
await new AiUsageService(tx).recordUsage({
teamId: owner.teamId,
userId: owner.userId,
...delta,
})
await quotaService.consumeQuota(
{ ...owner, resource: 'agent_total_tokens' },
delta.totalTokens,
tx,
)
await quotaService.consumeQuota({ ...owner, resource: 'agent_cost' }, delta.cost, tx)
}
await tx.agentSession.update({ where: { id: sessionId }, data: { accountedUsage: totals } })
return delta
}
return transaction ? account(transaction) : prisma.$transaction(account)
}
}
export const agentSessionService = new AgentSessionService()
@@ -0,0 +1,187 @@
import { hydrateRequest } from './session-content'
import { BACKGROUND_CONTEXT as context } from '@earendil-works/chord/context'
import {
createModels,
fauxAssistantMessage,
fauxProvider,
fauxToolCall,
} from '@earendil-works/pi-ai'
import {
createRegistry,
defineExtension,
Harness,
GenerationTask,
hook,
type StorageWrite,
} from '@earendil-works/pi-durable'
import { openNodeSqliteStorage } from '@earendil-works/pi-durable/storage/sqlite/node'
import { setupTestDbHooks } from '@shumai/db/test'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { s3Service } from '../s3/s3'
import { agentService } from './agent'
import { hydrateStorage, synchronizeStorage } from './session-storage'
describe('native Durable content storage', () => {
setupTestDbHooks()
afterEach(() => vi.restoreAllMocks())
it('hydrates generation and compaction after reopening while both persisted copies stay compact', async () => {
const directory = await mkdtemp(join(tmpdir(), 'shumai-content-'))
const path = join(directory, 'session.sqlite')
const commits: StorageWrite[][] = []
const text = 'Resolved skill instructions '.repeat(100)
vi.spyOn(agentService, 'getSkillContent').mockResolvedValue(text)
vi.spyOn(s3Service, 'getObject').mockResolvedValue({
buffer: Buffer.from('image bytes'),
contentType: 'image/png',
})
const faux = fauxProvider({
models: [{ id: 'test', input: ['text', 'image'], contextWindow: 100000, maxTokens: 1024 }],
})
const models = createModels()
models.setProvider(faux.provider)
const registry = createRegistry()
registry.install(
defineExtension({
name: 'shumai',
hooks: [
hook(GenerationTask, {
beforeRequest: async ({ messages }, api, context) => ({
messages: await hydrateRequest(messages, api, context),
}),
}),
],
tools: [
{
name: 'read_skill',
description: 'Read a skill',
parameters: { type: 'object', properties: {} },
execute: async () => ({
output: [{ type: 'text', text }],
details: { skillId: 'skill' },
}),
},
{
name: 'read_asset',
description: 'Read an image',
parameters: { type: 'object', properties: {} },
execute: async () => ({
output: [
{
type: 'image',
data: Buffer.from('image bytes').toString('base64'),
mimeType: 'image/png',
},
],
details: { sourceKeys: ['image-key'] },
}),
},
],
}),
)
const open = async () =>
Harness.open(
hydrateStorage(
synchronizeStorage(await openNodeSqliteStorage(path), {
dirty: async () => {},
clean: async () => {},
persist: async (accepted) => {
commits.push(
...accepted.map(
({ writes }) => JSON.parse(JSON.stringify(writes)) as StorageWrite[],
),
)
},
}),
),
{ models, registry, settings: () => ({ compaction: { keepRecentTokens: 1 } }) },
context,
)
let harness = await open()
try {
faux.setResponses([
(input) => {
expect(JSON.stringify(input.messages)).toContain(
Buffer.from('image bytes').toString('base64'),
)
return fauxAssistantMessage(
[fauxToolCall('read_skill', {}), fauxToolCall('read_asset', {})],
{ stopReason: 'toolUse' },
)
},
(input) => {
expect(JSON.stringify(input.messages)).toContain('Resolved skill instructions')
expect(JSON.stringify(input.messages)).toContain(
Buffer.from('image bytes').toString('base64'),
)
return fauxAssistantMessage('First answer')
},
])
let root = await harness.root(context, {
agent: { model: { provider: faux.provider.id, modelId: 'test' } },
})
expect(
(
await (
await root.submit(
{
type: 'input',
content: [
{ type: 'text', text: 'Read the skill and image' },
{ type: 'image', data: '__S3_DATA__', mimeType: 'image/png' },
],
entry: {
kind: 'shumai.message',
data: {
displayText: 'Read the skill and image',
timestamp: 1,
context: {},
sourceKeys: ['image-key'],
},
},
},
context,
)
).wait(context)
).status,
).toBe('done')
await harness.close(context)
expect(JSON.stringify(commits)).toContain('__S3_DATA__')
expect(JSON.stringify(commits)).toContain('__SKILL_CONTENT__')
expect(JSON.stringify(commits)).not.toContain(text)
expect(JSON.stringify(commits)).not.toContain(Buffer.from('image bytes').toString('base64'))
harness = await open()
root = await harness.root(context)
faux.setResponses([
(input) => {
expect(JSON.stringify(input.messages)).toContain('Resolved skill instructions')
expect(JSON.stringify(input.messages)).not.toContain('__SKILL_CONTENT__')
return fauxAssistantMessage('Summary')
},
])
const compact = await root.compact(undefined, context)
expect((await harness.waitForTask(compact, context)).state.status).toBe('terminal')
await harness.close(context)
const native = await openNodeSqliteStorage(path)
try {
const entries = await native.scanEntries(
{ conversationId: root.id },
100,
undefined,
context,
)
const stored = JSON.stringify(entries.items)
expect(stored).toContain('__SKILL_CONTENT__')
expect(stored).not.toContain(text)
} finally {
await native.close(context)
}
} finally {
await harness.close(context)
await rm(directory, { recursive: true, force: true })
}
})
})
@@ -0,0 +1,64 @@
import type { Context } from '@earendil-works/chord/context'
import type {
ConversationId,
EntryId,
Seq,
Storage,
StorageWrite,
} from '@earendil-works/pi-durable'
import { compactSessionWrites, hydrateEntry } from './session-content'
export interface CommitReceipt {
seq: Seq
writes: readonly StorageWrite[]
}
/** Decorate the native instance; every query and ID rule remains implemented by Pi. */
export function synchronizeStorage(
storage: Storage,
callbacks: {
dirty(): Promise<void>
persist(commits: readonly CommitReceipt[]): Promise<void>
clean(seq?: Seq): Promise<void>
},
): Storage {
const commit = storage.commit.bind(storage)
storage.commit = async (batches, receive, context) => {
await callbacks.dirty()
const compact = batches.map(compactSessionWrites)
const receipts: Array<{ index: number; seq: Seq }> = []
const result = await commit(compact, (index, seq) => receipts.push({ index, seq }), context)
await callbacks.persist(receipts.map(({ index, seq }) => ({ seq, writes: compact[index] })))
await callbacks.clean(receipts.at(-1)?.seq)
for (const { index, seq } of receipts) receive(index, seq)
return result
}
return storage
}
/** Runtime reads hydrate detached entries; API reads use the compact native instance. */
export function hydrateStorage(storage: Storage): Storage {
const entry = storage.entry.bind(storage)
const scan = storage.scanEntries.bind(storage)
const head = storage.findLatestHeadMarker.bind(storage)
storage.entry = (async (
first: EntryId | ConversationId,
second: EntryId | Context,
third?: Context,
) => {
const record =
third === undefined
? await entry(first as EntryId, second as Context)
: await entry(first as ConversationId, second as EntryId, third)
return record ? { ...record, entry: await hydrateEntry(record.entry) } : undefined
}) as Storage['entry']
storage.scanEntries = async (...args) => {
const page = await scan(...args)
return { ...page, items: await Promise.all(page.items.map(hydrateEntry)) }
}
storage.findLatestHeadMarker = async (...args) => {
const found = await head(...args)
return found ? { ...(await hydrateEntry(found)), head: found.head } : undefined
}
return storage
}
@@ -0,0 +1,25 @@
import { BACKGROUND_CONTEXT } from '@earendil-works/chord/context'
import { createModels } from '@earendil-works/pi-ai'
import { Harness, createRegistry, type EntryDraft } from '@earendil-works/pi-durable'
import { agentSessionService } from './session-service'
/** Seed real native records through the same writer used by the application. */
export async function appendSessionEntries(sessionId: string, drafts: EntryDraft[]) {
return agentSessionService.withWriter(sessionId, async (storage) => {
const harness = await Harness.open(
storage,
{ models: createModels(), registry: createRegistry() },
BACKGROUND_CONTEXT,
)
try {
const root = await harness.root(BACKGROUND_CONTEXT)
return await root.commit(async (tx) => {
const entries = []
for (const draft of drafts) entries.push(await tx.appendEntry(root.id, draft))
return entries
}, BACKGROUND_CONTEXT)
} finally {
await harness.close(BACKGROUND_CONTEXT)
}
})
}
@@ -0,0 +1,66 @@
import { BACKGROUND_CONTEXT } from '@earendil-works/chord/context'
import { OutputBuffer } from '@earendil-works/chord/output'
import type {
Harness,
JsonObject,
ToolExecutionApi,
ToolExecutionResult,
ToolRegistration,
} from '@earendil-works/pi-durable'
/** Exercise a tool with the native execution API while keeping assertions focused on its result. */
export async function invokeTool<T extends ToolRegistration>(
tool: T,
callId: string,
args: Parameters<T['execute']>[0],
signal?: AbortSignal,
onUpdate?: (update: {
content: NonNullable<ToolExecutionResult['output']>
details?: unknown
}) => void,
) {
const buffer = new OutputBuffer({
maxBytes: tool.outputLimits?.maxBytes ?? 50000,
maxLines: tool.outputLimits?.maxLines ?? 2000,
retain: tool.outputLimits?.retain ?? 'head',
})
let details: unknown
const notify = () =>
onUpdate?.({
content: buffer.snapshot().text ? [{ type: 'text', text: buffer.snapshot().text }] : [],
details,
})
const api = {
callId,
output: (chunk: string | Uint8Array) => {
buffer.push(chunk)
notify()
},
details: async (value: unknown) => {
details = value
notify()
},
retainedOutput: () => ({ text: buffer.snapshot().text, truncated: false }),
diagnostic: () => {},
} as unknown as ToolExecutionApi
const result = await tool.execute(args, api, { ...BACKGROUND_CONTEXT, abortSignal: signal })
return {
...result,
details: result.details as Awaited<ReturnType<T['execute']>>['details'],
content: result.output ?? [{ type: 'text' as const, text: buffer.snapshot().text }],
}
}
export async function getAgentTools(harness: Harness) {
return (await (await harness.root(BACKGROUND_CONTEXT)).agent(BACKGROUND_CONTEXT)).tools
}
export async function getAgentPrompt(harness: Harness) {
return (
(await (await harness.root(BACKGROUND_CONTEXT)).agent(BACKGROUND_CONTEXT)).instructions ?? ''
)
}
export function jsonData(value: unknown): JsonObject {
return JSON.parse(JSON.stringify(value)) as JsonObject
}
+8 -7
View File
@@ -20,6 +20,7 @@ export interface GetTeamUsageStatsParams {
}
export class AiUsageService {
constructor(private readonly prismaClient: Prisma.TransactionClient = prisma) {}
private async incrementBucket(params: {
teamId: string
userId: string | null
@@ -31,7 +32,7 @@ export class AiUsageService {
cost: number
}): Promise<void> {
if (params.userId !== null) {
await prisma.aiUsage.upsert({
await this.prismaClient.aiUsage.upsert({
where: {
// eslint-disable-next-line @typescript-eslint/naming-convention
teamId_userId_periodStart: {
@@ -59,7 +60,7 @@ export class AiUsageService {
},
})
} else {
const existing = await prisma.aiUsage.findFirst({
const existing = await this.prismaClient.aiUsage.findFirst({
where: {
teamId: params.teamId,
userId: null,
@@ -68,7 +69,7 @@ export class AiUsageService {
})
if (existing) {
await prisma.aiUsage.update({
await this.prismaClient.aiUsage.update({
where: { id: existing.id },
data: {
inputTokens: { increment: params.inputTokens },
@@ -80,7 +81,7 @@ export class AiUsageService {
})
} else {
try {
await prisma.aiUsage.create({
await this.prismaClient.aiUsage.create({
data: {
teamId: params.teamId,
userId: null,
@@ -94,7 +95,7 @@ export class AiUsageService {
})
} catch (err) {
if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') {
await prisma.aiUsage.updateMany({
await this.prismaClient.aiUsage.updateMany({
where: {
teamId: params.teamId,
userId: null,
@@ -173,7 +174,7 @@ export class AiUsageService {
if (!params.userId) {
// Return Team-Level Usage (userId = null)
const teamRecords = await prisma.aiUsage.findMany({
const teamRecords = await this.prismaClient.aiUsage.findMany({
where: {
teamId: params.teamId,
userId: null,
@@ -219,7 +220,7 @@ export class AiUsageService {
throw new HTTPException(404, { message: 'Team member not found' })
}
const memberRecords = await prisma.aiUsage.findMany({
const memberRecords = await this.prismaClient.aiUsage.findMany({
where: {
teamId: params.teamId,
userId: params.userId,
+10 -11
View File
@@ -1,7 +1,8 @@
import { prisma } from '@shumai/db'
import type { ShumaiMessageContext } from '@shumai/dtos'
import { HTTPException } from 'hono/http-exception'
import { degreeToSecond } from '@shumai/core/src/utils/model3d'
import { prisma } from '@shumai/db'
import { getShumaiMessage } from '@shumai/dtos'
import { HTTPException } from 'hono/http-exception'
import { agentSessionService } from '../agent/session-service'
/**
* Resolve the visual markup referenced by an annotation ID: a comment (comments mode) or an
@@ -32,15 +33,13 @@ export async function resolveAnnotationsById(
return { annotations, timestamp: comment.second }
}
// 2. Check AgentSessionEntry table (1-on-1 Chat Mode)
const entry = await prisma.agentSessionEntry.findUnique({
where: { id: annotationId },
select: { assetId: true, data: true },
})
const reference = /^chat:([^:]+):(.+)$/.exec(annotationId)
const entry = reference
? await agentSessionService.getEntryForRequest(reference[1], reference[2])
: undefined
if (entry) {
const details = (entry.data as Record<string, unknown> | null)?.details as
ShumaiMessageContext | undefined
const entryAssetId = entry.assetId || details?.currentAsset?.id
const details = getShumaiMessage(entry)?.context
const entryAssetId = details?.currentAsset?.id
if (entryAssetId && entryAssetId !== assetId) {
throw new HTTPException(400, {
message: `Annotation "${annotationId}" belongs to asset "${entryAssetId}", not target asset "${assetId}".`,
+31 -365
View File
@@ -1,8 +1,10 @@
import { fauxAssistantMessage } from '@earendil-works/pi-ai'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { chatService, buildSessionMessages, mapEntryToMessage, type PathEntry } from './chat'
import { describe, expect, it, vi } from 'vitest'
import { workflowService } from '@shumai/workflow-core'
import { describe, expect, it, vi } from 'vitest'
import { appendSessionEntries } from '../agent/session-test-utils'
import { chatService } from './chat'
describe('ChatService', () => {
setupTestDbHooks()
@@ -340,141 +342,33 @@ describe('ChatService', () => {
expect(list.data).toHaveLength(2)
})
it('should list messages mapped correctly', async () => {
it('returns native entries with structured context and model messages', async () => {
const { user, team, project } = await setupBasicData()
const { sessionId } = await chatService.startOrContinueChat(user, team.id, {
agentId: 'test-agent-id',
textPrompt: 'hello',
projectId: project.id,
})
// Manually insert a test entry representing user message
await prisma.agentSessionEntry.create({
data: {
id: 'test-entry-id',
sessionId,
type: 'message',
parentId: null,
data: {
message: {
role: 'user',
content: [{ type: 'text', text: 'hello' }],
timestamp: Date.now(),
},
} as PrismaJson.PiSessionEntryData,
await appendSessionEntries(sessionId, [
{
kind: 'shumai.message',
data: { displayText: 'hello', timestamp: 1, context: {} },
model: [{ role: 'user', content: 'hello', timestamp: 1 }],
},
})
await prisma.agentSession.update({
where: { id: sessionId },
data: { leafId: 'test-entry-id' },
})
{ kind: 'pi.assistant', model: [fauxAssistantMessage('answer')] },
{ kind: 'pi.compaction', data: { reason: 'manual' } },
])
const messages = await chatService.listMessages(user.id, team.id, sessionId)
expect(messages).toHaveLength(1)
// Casting to any to access properties of union in test assertions
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const msg = messages[0] as any
expect(msg.role).toBe('user')
expect(msg.content).toEqual([{ type: 'text', text: 'hello' }])
})
it('should hide customType context messages', async () => {
const { user, team, project } = await setupBasicData()
const { sessionId } = await chatService.startOrContinueChat(user, team.id, {
agentId: 'test-agent-id',
textPrompt: 'hello',
projectId: project.id,
expect(messages.map((entry) => entry.kind)).toEqual([
'shumai.message',
'pi.assistant',
'pi.compaction',
])
expect(messages[0]).toMatchObject({
data: { displayText: 'hello' },
model: [{ role: 'user', content: 'hello' }],
})
// 1. Manually insert a test entry representing user message
await prisma.agentSessionEntry.create({
data: {
id: 'test-entry-1-user',
sessionId,
type: 'message',
parentId: null,
data: {
message: {
role: 'user',
content: [{ type: 'text', text: 'hello' }],
timestamp: Date.now(),
},
} as PrismaJson.PiSessionEntryData,
},
})
// 2. Manually insert a test entry representing a custom context message
await prisma.agentSessionEntry.create({
data: {
id: 'test-entry-2-context',
sessionId,
type: 'custom_message',
parentId: 'test-entry-1-user',
data: {
customType: 'context',
content: 'some context',
display: 'chat',
} as PrismaJson.PiSessionEntryData,
},
})
// 3. Manually insert a test entry representing a custom thinking level change
await prisma.agentSessionEntry.create({
data: {
id: 'test-entry-3-thinking',
sessionId,
type: 'thinking_level_change',
parentId: 'test-entry-2-context',
data: {
thinkingLevel: 'deep',
} as PrismaJson.PiSessionEntryData,
},
})
// 4. Manually insert a test entry representing custom context_display_info entry
await prisma.agentSessionEntry.create({
data: {
id: 'test-entry-4-display',
sessionId,
type: 'custom',
parentId: 'test-entry-3-thinking',
data: {
customType: 'context_display_info',
data: {
assets: [{ id: 'a1', name: 'File A', type: 'file' }],
},
} as PrismaJson.PiSessionEntryData,
},
})
await prisma.agentSession.update({
where: { id: sessionId },
data: { leafId: 'test-entry-4-display' },
})
// Verify listMessages returns only the user, thinking level change and custom display entry message
const messages = await chatService.listMessages(user.id, team.id, sessionId)
expect(messages).toHaveLength(3)
expect(messages[0].id).toBe('test-entry-1-user')
expect(messages[1].id).toBe('test-entry-3-thinking')
expect(messages[2].id).toBe('test-entry-4-display')
expect(messages[2].role).toBe('custom')
expect((messages[2] as { customType?: string }).customType).toBe('context_display_info')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((messages[2] as any).details).toEqual({
assets: [{ id: 'a1', name: 'File A', type: 'file' }],
})
// Verify mapEntryToMessage returns null for context message
const contextRecord = await prisma.agentSessionEntry.findUnique({
where: { id: 'test-entry-2-context' },
})
expect(contextRecord).not.toBeNull()
const mapped = mapEntryToMessage(contextRecord!)
expect(mapped).toBeNull()
expect(typeof messages[0].id).toBe('number')
})
it('should delete session and cascade', async () => {
@@ -499,167 +393,6 @@ describe('ChatService', () => {
expect(entries).toHaveLength(0)
})
it('should build session messages correctly handling compaction and custom messages', () => {
const pathEntries = [
{
id: 'entry-1',
type: 'message',
timestamp: '2026-07-07T00:00:00.000Z',
message: {
role: 'user',
content: 'first message',
},
},
{
id: 'entry-compaction',
type: 'compaction',
timestamp: '2026-07-07T00:01:00.000Z',
summary: 'Compacted conversation history',
tokensBefore: 200,
firstKeptEntryId: 'entry-2',
},
{
id: 'entry-2',
type: 'message',
timestamp: '2026-07-07T00:02:00.000Z',
message: {
role: 'assistant',
content: 'kept message',
},
},
{
id: 'entry-3',
type: 'thinking_level_change',
timestamp: '2026-07-07T00:03:00.000Z',
thinkingLevel: 'high',
},
{
id: 'entry-4',
type: 'branch_summary',
timestamp: '2026-07-07T00:04:00.000Z',
summary: 'Branch summary details',
fromId: 'entry-old',
},
]
const messages = buildSessionMessages(pathEntries as unknown as PathEntry[])
expect(messages).toHaveLength(4)
// 1. Compaction summary message
// Casting to any to access properties of union in test assertions
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const msg0 = messages[0] as any
expect(msg0.role).toBe('custom')
expect(msg0.customType).toBe('compaction-summary')
expect(msg0.content).toBe('Compacted conversation history')
expect((msg0.details as Record<string, unknown>).tokensBefore).toBe(200)
// 2. Kept entry (entry-2)
// Casting to any to access properties of union in test assertions
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const msg1 = messages[1] as any
expect(msg1.id).toBe('entry-2')
expect(msg1.role).toBe('assistant')
expect(msg1.content).toBe('kept message')
// 3. Thinking level change (entry-3)
// Casting to any to access properties of union in test assertions
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const msg2 = messages[2] as any
expect(msg2.role).toBe('thinking_level_change')
expect(msg2.content).toContain('Thinking level changed to high')
// 4. Branch summary (entry-4)
// Casting to any to access properties of union in test assertions
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const msg3 = messages[3] as any
expect(msg3.role).toBe('custom')
expect(msg3.customType).toBe('branch-summary')
expect(msg3.content).toBe('Branch summary details')
expect((msg3.details as Record<string, unknown>).fromId).toBe('entry-old')
})
it('should render active_tools_change entries as custom messages', () => {
const pathEntries = [
{
id: 'entry-tools',
type: 'active_tools_change',
timestamp: '2026-07-07T00:05:00.000Z',
activeToolNames: ['read_skill', 'bash'],
},
]
const messages = buildSessionMessages(pathEntries as unknown as PathEntry[])
expect(messages).toHaveLength(1)
// Casting to any to access properties of union in test assertions
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const msg = messages[0] as any
expect(msg.role).toBe('custom')
expect(msg.customType).toBe('active-tools-change')
expect(msg.content).toBe('Active tools: read_skill, bash')
expect(msg.details).toEqual({ activeToolNames: ['read_skill', 'bash'] })
})
it('should return null for entry types without a chat representation instead of an empty message', () => {
const leafRecord = {
id: 'entry-leaf',
type: 'leaf',
parentId: null,
createdAt: new Date('2026-07-07T00:05:00.000Z'),
data: { targetId: 'some-entry' },
} as unknown as Parameters<typeof mapEntryToMessage>[0]
expect(mapEntryToMessage(leafRecord)).toBeNull()
})
it('should map shumai_message custom_message entries with clean text and structured details', () => {
const entryRecord = {
id: 'entry-shumai-msg',
type: 'custom_message',
parentId: null,
createdAt: new Date('2026-07-07T00:05:00.000Z'),
data: {
customType: 'shumai_message',
content: 'Please adjust color grading',
display: true,
details: {
user: { id: 'u1', name: 'Alice', role: 'editor' },
currentAsset: { id: 'a1', name: 'video.mp4', type: 'file' },
position: { type: 'time', seconds: 12.5 },
},
},
} as unknown as Parameters<typeof mapEntryToMessage>[0]
const msg = mapEntryToMessage(entryRecord)
expect(msg).toBeDefined()
expect(msg?.id).toBe('entry-shumai-msg')
expect(msg?.role).toBe('custom')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((msg as any)?.customType).toBe('shumai_message')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((msg as any)?.content).toBe('Please adjust color grading')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((msg as any)?.details?.user?.name).toBe('Alice')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((msg as any)?.details?.position?.seconds).toBe(12.5)
})
it('should skip legacy context custom_message in mapEntryToMessage', () => {
const entryRecord = {
id: 'entry-legacy-context',
type: 'custom_message',
parentId: null,
createdAt: new Date('2026-07-07T00:05:00.000Z'),
data: {
customType: 'context',
content: 'System context prompt...',
},
} as unknown as Parameters<typeof mapEntryToMessage>[0]
expect(mapEntryToMessage(entryRecord)).toBeNull()
})
describe('getNewSessionMessages', () => {
it('returns new messages and lastEntryId', async () => {
const { user, team, project } = await setupBasicData()
@@ -669,53 +402,27 @@ describe('ChatService', () => {
projectId: project.id,
})
// Insert two entries
const entry1 = await prisma.agentSessionEntry.create({
data: {
id: 'entry-id-1',
sessionId,
type: 'message',
parentId: null,
data: {
message: {
role: 'user',
content: [{ type: 'text', text: 'msg 1' }],
},
} as PrismaJson.PiSessionEntryData,
},
})
const entry2 = await prisma.agentSessionEntry.create({
data: {
id: 'entry-id-2',
sessionId,
type: 'message',
parentId: 'entry-id-1',
data: {
message: {
role: 'assistant',
content: [{ type: 'text', text: 'msg 2' }],
},
} as PrismaJson.PiSessionEntryData,
},
})
const [entry1, entry2] = await appendSessionEntries(sessionId, [
{ kind: 'pi.user', model: [{ role: 'user', content: 'msg 1', timestamp: 1 }] },
{ kind: 'pi.assistant', model: [fauxAssistantMessage('msg 2')] },
])
// 1. Get all messages
const res1 = await chatService.getNewSessionMessages(sessionId)
expect(res1.messages).toHaveLength(2)
expect(res1.lastEntryId).toBe(entry2.id)
expect(res1.lastEntryId).toBe(String(entry2.id))
expect(res1.messages[0].id).toBe(entry1.id)
// 2. Get with lastEntryId
const res2 = await chatService.getNewSessionMessages(sessionId, entry1.id)
const res2 = await chatService.getNewSessionMessages(sessionId, String(entry1.id))
expect(res2.messages).toHaveLength(1)
expect(res2.lastEntryId).toBe(entry2.id)
expect(res2.lastEntryId).toBe(String(entry2.id))
expect(res2.messages[0].id).toBe(entry2.id)
// 3. Get with latest lastEntryId
const res3 = await chatService.getNewSessionMessages(sessionId, entry2.id)
const res3 = await chatService.getNewSessionMessages(sessionId, String(entry2.id))
expect(res3.messages).toHaveLength(0)
expect(res3.lastEntryId).toBe(entry2.id)
expect(res3.lastEntryId).toBe(String(entry2.id))
})
})
@@ -948,47 +655,6 @@ describe('ChatService', () => {
).rejects.toThrow(/Insufficient role/)
})
it('safely maps entries without message object or with customType shumai_message', () => {
// 1. Entry with type: 'message' but customType: 'shumai_message'
const legacyEntry = {
id: 'legacy-1',
sessionId: 'sess-1',
assetId: null,
parentId: null,
type: 'message',
data: {
customType: 'shumai_message',
content: 'Hello legacy',
display: true,
details: { user: { id: 'u1', name: 'User 1' } },
},
createdAt: new Date(),
}
const msg1 = mapEntryToMessage(legacyEntry)
expect(msg1).toBeDefined()
expect(msg1?.role).toBe('custom')
if (msg1 && msg1.role === 'custom') {
expect(msg1.customType).toBe('shumai_message')
expect(msg1.content).toBe('Hello legacy')
expect(msg1.details).toEqual({ user: { id: 'u1', name: 'User 1' } })
}
// 2. Entry with type: 'message' but empty data / no message
const emptyEntry = {
id: 'empty-1',
sessionId: 'sess-1',
assetId: null,
parentId: null,
type: 'message',
data: {},
createdAt: new Date(),
}
const msg2 = mapEntryToMessage(emptyEntry)
expect(msg2).toBeNull()
})
it('should forward annotations and second to workflow task payload', async () => {
const { user, team, project } = await setupBasicData()
+29 -204
View File
@@ -1,170 +1,20 @@
import { prisma } from '@shumai/db'
import type { Prisma } from '@shumai/db'
import type { EntryId, EntryRecord } from '@earendil-works/pi-durable'
import { getAgentRequiredLevel, getRoleLevel } from '@shumai/core/src/agent/permissions'
import {
authzService,
Permission,
ResourceType,
resolveEffectiveRole,
ResourceType,
} from '@shumai/core/src/authz/authz'
import { paginateQuery, type PaginatedData } from '@shumai/core/src/pagination'
import type { ChatRequest, ChatSessionInfo, ChatMessage } from '@shumai/dtos'
import type { SessionTreeEntry } from '@earendil-works/pi-agent-core'
import type { Prisma } from '@shumai/db'
import { prisma } from '@shumai/db'
import type { ChatRequest, ChatSessionInfo } from '@shumai/dtos'
import { workflowService } from '@shumai/workflow-core'
import { agentService } from '@shumai/core/src/agent/agent'
import { getAgentRequiredLevel, getRoleLevel } from '@shumai/core/src/agent/permissions'
import { agentSessionService } from '../agent/session-service'
type User = Prisma.UserGetPayload<Record<string, never>>
export type PathEntry = SessionTreeEntry & { id: string }
export function buildSessionMessages(pathEntries: PathEntry[]): ChatMessage[] {
let compaction: (SessionTreeEntry & { type: 'compaction' } & { id: string }) | null = null
for (const entry of pathEntries) {
if (entry.type === 'compaction') {
compaction = entry as SessionTreeEntry & { type: 'compaction' } & { id: string }
}
}
const messages: ChatMessage[] = []
const appendMessage = (entry: PathEntry) => {
const timestampMs = new Date(entry.timestamp).getTime()
if (entry.type === 'message') {
if ((entry as unknown as { customType?: string }).customType === 'shumai_message') {
const customEntry = entry as unknown as {
customType: string
content: string
display?: boolean
details?: Record<string, unknown>
}
messages.push({
id: entry.id,
role: 'custom',
customType: customEntry.customType,
content: customEntry.content,
display: customEntry.display,
details: customEntry.details,
timestamp: timestampMs,
} as unknown as ChatMessage)
return
}
if (entry.message) {
messages.push({
...entry.message,
id: entry.id,
timestamp: entry.message.timestamp || timestampMs,
} as unknown as ChatMessage)
}
} else if (entry.type === 'custom_message') {
if (entry.customType === 'context') return
messages.push({
id: entry.id,
role: 'custom',
customType: entry.customType,
content: entry.content,
display: entry.display,
details: entry.details as Record<string, unknown> | undefined,
timestamp: timestampMs,
} as unknown as ChatMessage)
} else if (entry.type === 'custom') {
messages.push({
id: entry.id,
role: 'custom',
customType: entry.customType,
details: (entry as { data?: unknown }).data as Record<string, unknown> | undefined,
timestamp: timestampMs,
} as unknown as ChatMessage)
} else if (entry.type === 'branch_summary') {
messages.push({
id: entry.id,
role: 'custom',
customType: 'branch-summary',
content: entry.summary,
details: { fromId: entry.fromId },
timestamp: timestampMs,
} as unknown as ChatMessage)
} else if (entry.type === 'thinking_level_change') {
messages.push({
id: entry.id,
role: 'thinking_level_change',
content: `Thinking level changed to ${entry.thinkingLevel}`,
timestamp: timestampMs,
} as unknown as ChatMessage)
} else if (entry.type === 'active_tools_change') {
messages.push({
id: entry.id,
role: 'custom',
customType: 'active-tools-change',
content: `Active tools: ${entry.activeToolNames.join(', ')}`,
details: { activeToolNames: entry.activeToolNames },
timestamp: timestampMs,
} as unknown as ChatMessage)
}
}
if (compaction) {
const compactionTimestamp = new Date(compaction.timestamp).getTime()
messages.push({
id: compaction.id,
role: 'custom',
customType: 'compaction-summary',
content: compaction.summary,
details: { tokensBefore: compaction.tokensBefore },
timestamp: compactionTimestamp,
} as unknown as ChatMessage)
const compactionIdx = pathEntries.findIndex(
(e) => e.type === 'compaction' && e.id === compaction?.id,
)
let foundFirstKept = false
for (let i = 0; i < compactionIdx; i++) {
const entry = pathEntries[i]
if (entry.id === compaction.firstKeptEntryId) foundFirstKept = true
if (foundFirstKept) appendMessage(entry)
}
for (let i = compactionIdx + 1; i < pathEntries.length; i++) {
appendMessage(pathEntries[i])
}
} else {
for (const entry of pathEntries) {
appendMessage(entry)
}
}
return messages
}
export function mapEntryToMessage(
entryRecord: Prisma.AgentSessionEntryGetPayload<Record<string, never>>,
): ChatMessage | null {
const payload = (entryRecord.data as Record<string, unknown>) || {}
let type = (entryRecord.type || 'message') as SessionTreeEntry['type']
if (type === 'message' && payload.customType === 'shumai_message') {
type = 'custom_message'
}
const entryObj = {
id: entryRecord.id,
type,
parentId: entryRecord.parentId,
timestamp: entryRecord.createdAt.toISOString(),
...payload,
} as unknown as SessionTreeEntry
if (
entryObj.type === 'custom_message' &&
(entryObj as { customType?: string }).customType === 'context'
) {
return null
}
const pathEntries = [entryObj]
const messages = buildSessionMessages(pathEntries)
if (messages.length > 0) {
return messages[0]
}
// Entry types that have no chat representation (e.g. leaf, label, model_change,
// or any unknown/unsupported type) are skipped rather than rendered as an empty message.
return null
}
export class ChatService {
constructor(private readonly prismaClient: typeof prisma = prisma) {}
@@ -454,7 +304,7 @@ export class ChatService {
)
}
async listMessages(userId: string, teamId: string, sessionId: string): Promise<ChatMessage[]> {
async listMessages(userId: string, teamId: string, sessionId: string): Promise<EntryRecord[]> {
const session = await this.prismaClient.agentSession.findUnique({
where: { id: sessionId },
})
@@ -465,28 +315,8 @@ export class ChatService {
throw new Error('Unauthorized session access')
}
const entries = await agentService.getSessionEntries({ sessionId })
const pathEntries = entries.map(
(e: {
id: string
type: string | null
parentId: string | null
createdAt: Date
data: unknown
}) => {
const payload = (e.data as Record<string, unknown>) || {}
return {
id: e.id,
type: (e.type || 'message') as SessionTreeEntry['type'],
parentId: e.parentId,
timestamp: e.createdAt.toISOString(),
...payload,
} as unknown as SessionTreeEntry
},
)
return buildSessionMessages(pathEntries)
const entries = await agentSessionService.getEntries(sessionId)
return entries.filter((entry) => entry.kind !== 'pi.system')
}
async deleteSession(userId: string, teamId: string, sessionId: string): Promise<void> {
@@ -507,31 +337,26 @@ export class ChatService {
async getNewSessionMessages(
sessionId: string,
lastEntryId?: string,
): Promise<{ messages: ChatMessage[]; lastEntryId: string | null }> {
const entries = await this.prismaClient.agentSessionEntry.findMany({
where: {
sessionId,
...(lastEntryId ? { id: { gt: lastEntryId } } : {}),
},
orderBy: { id: 'asc' },
})
if (entries.length === 0) {
return { messages: [], lastEntryId: lastEntryId ?? null }
}
const messages: ChatMessage[] = []
for (const entry of entries) {
const message = mapEntryToMessage(entry)
if (message) {
messages.push(message)
): Promise<{ messages: EntryRecord[]; lastEntryId: string | null }> {
const after = lastEntryId ? Number(lastEntryId) : undefined
if (after !== undefined && (!Number.isSafeInteger(after) || after < 0))
throw new Error('Invalid entry cursor')
const messages: EntryRecord[] = []
let cursor: import('@earendil-works/pi-durable').Cursor | undefined
let last = lastEntryId ?? null
do {
const page = await agentSessionService.listEntries(sessionId, {
after: after as EntryId | undefined,
limit: 100,
cursor,
})
for (const entry of page.items) {
last = String(entry.id)
if (entry.kind !== 'pi.system') messages.push(entry)
}
}
return {
messages,
lastEntryId: entries[entries.length - 1].id,
}
cursor = page.next
} while (cursor)
return { messages, lastEntryId: last }
}
async getChatWorkflowStatus(
+8 -6
View File
@@ -8,9 +8,12 @@
* discovery/auth/status and for tools not in direct mode.
*/
import { Type } from '@sinclair/typebox'
import type { AgentTool, AgentToolResult } from '@earendil-works/pi-agent-core'
import type {
ToolRegistration as AgentTool,
ToolExecutionResult as AgentToolResult,
} from '@earendil-works/pi-durable'
import '@shumai/db/src/prisma-json-types'
import { Type } from '@sinclair/typebox'
import type { ToolMetadata } from './mcp-tool-registry'
import { isToolAllowed } from './mcp-tool-registry'
import { toToolParameters } from './mcp-tool-schema'
@@ -24,7 +27,7 @@ export interface DirectToolCallOptions {
args: Record<string, unknown>,
): Promise<{
ok: boolean
content: AgentToolResult<Record<string, unknown>>['content']
content: NonNullable<AgentToolResult['output']>
}>
}
@@ -63,18 +66,17 @@ export function buildDirectTools(
const parameters = toToolParameters(tool.inputSchema)
tools.push({
name: tool.name,
label: tool.name,
description:
tool.description || `Call ${tool.originalName} on MCP server ${opts.serverName}.`,
parameters: parameters as unknown as import('typebox').TSchema,
execute: async (_toolCallId, args): Promise<AgentToolResult<Record<string, unknown>>> => {
execute: async (args): Promise<AgentToolResult> => {
const result = await opts.callTool(
opts.serverId,
tool.originalName,
args as Record<string, unknown>,
)
return {
content: result.content,
output: result.content,
details: { server: opts.serverName, tool: tool.originalName },
}
},
+13 -10
View File
@@ -7,12 +7,15 @@
* server(list) > status.
*/
import { Type } from '@sinclair/typebox'
import type { AgentTool, AgentToolResult } from '@earendil-works/pi-agent-core'
import type {
ToolRegistration as AgentTool,
ToolExecutionResult as AgentToolResult,
} from '@earendil-works/pi-durable'
import { Type } from 'typebox'
import type { McpToolRegistry, ToolMetadata } from './mcp-tool-registry'
import { formatSchema } from './mcp-tool-schema'
type ProxyToolResult = AgentToolResult<Record<string, unknown>>
type ProxyToolResult = AgentToolResult
/** Truncated instructions head baked into the proxy tool description (L1). */
const INSTRUCTIONS_SNIPPET_LENGTH = 150
@@ -45,7 +48,7 @@ export type ConnectionOutcome =
export interface CallToolOutcome {
ok: boolean
content: AgentToolResult<Record<string, unknown>>['content']
content: NonNullable<AgentToolResult['output']>
}
export interface McpProxyToolContext {
@@ -167,7 +170,7 @@ function parseArgs(raw: unknown): Record<string, unknown> {
}
function contentText(text: string): ProxyToolResult {
return { content: [{ type: 'text', text }], details: {} }
return { output: [{ type: 'text', text }], details: {} }
}
/** Transform MCP content blocks into model content blocks. */
@@ -181,7 +184,7 @@ export function transformMcpContent(
uri?: string
name?: string
}>,
): AgentToolResult<Record<string, unknown>>['content'] {
): NonNullable<AgentToolResult['output']> {
return content.map((c) => {
if (c.type === 'text') {
return { type: 'text', text: c.text ?? '' }
@@ -331,10 +334,10 @@ function renderServerListing(
export function buildProxyTool(ctx: McpProxyToolContext): AgentTool<typeof proxyToolSchema> {
return {
name: 'mcp',
label: 'MCP Tools',
description: buildProxyDescription(ctx.servers),
parameters: proxyToolSchema,
execute: async (_toolCallId, params): Promise<ProxyToolResult> => {
execute: async (params): Promise<ProxyToolResult> => {
const action = params.action
const server = params.server
const tool = params.tool
@@ -396,10 +399,10 @@ export function buildProxyTool(ctx: McpProxyToolContext): AgentTool<typeof proxy
parseArgs(params.args),
)
if (outcome.ok) {
return { content: outcome.content, details: {} }
return { output: outcome.content, details: {} }
}
return {
content: outcome.content,
output: outcome.content,
details: { error: 'tool_call_failed', tool, server: resolved.serverId },
}
}
+26 -51
View File
@@ -1,11 +1,12 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import '@shumai/db/src/prisma-json-types'
import { setupTestDbHooks } from '@shumai/db/test'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { invokeTool } from '../agent/tool-test-utils'
import { McpService } from './mcp-service'
import {
startTestMcpServer,
standardTestTools,
startTestMcpServer,
type RunningTestMcpServer,
type TestMcpToolDef,
} from './mcp-test-server'
@@ -62,11 +63,6 @@ const AIRTABLE_TOOLS: TestMcpToolDef[] = [
},
]
type ProxyExecute = (
id: string,
params: unknown,
) => Promise<{ content: Array<{ type: string; text?: string }> }>
describe('McpService', () => {
setupTestDbHooks()
@@ -199,7 +195,7 @@ describe('McpService', () => {
const agent = await seedAgentAndUser(teamId, 'Meta Name Agent')
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: server.id } })
const agentTools = await service.buildAgentTools(agent.id, teamId)
const search = await (agentTools[0].execute as ProxyExecute)('meta-1', { search: 'echo' })
const search = await invokeTool(agentTools[0], 'meta-1', { search: 'echo' })
expect(JSON.stringify(search.content)).toContain('Meta_Server_echo')
} finally {
await metaSrv.stop()
@@ -337,14 +333,14 @@ describe('McpService', () => {
expect(proxy.description).not.toContain(instructionsText)
// L2: longer preview at the end of the server listing + full-text hint.
const list = await (proxy.execute as ProxyExecute)('list-1', { server: 'inst-srv' })
const list = await invokeTool(proxy, 'list-1', { server: 'inst-srv' })
const listText = JSON.stringify(list.content)
expect(listText).toContain('Server instructions:')
expect(listText).toContain('for the full text')
expect(listText).not.toContain(instructionsText)
// L3: full text via the instructions mode.
const full = await (proxy.execute as ProxyExecute)('inst-1', { instructions: 'inst-srv' })
const full = await invokeTool(proxy, 'inst-1', { instructions: 'inst-srv' })
const fullText = JSON.stringify(full.content)
expect(fullText).toContain(instructionsText)
expect(fullText).toContain('inst-srv instructions:')
@@ -364,9 +360,9 @@ describe('McpService', () => {
// No L1 block, no L2 preview, and L3 says so explicitly.
expect(proxy.description).not.toContain('Server instructions (truncated')
const list = await (proxy.execute as ProxyExecute)('list-1', { server: 'test-mcp-server' })
const list = await invokeTool(proxy, 'list-1', { server: 'test-mcp-server' })
expect(JSON.stringify(list.content)).not.toContain('Server instructions:')
const full = await (proxy.execute as ProxyExecute)('inst-1', {
const full = await invokeTool(proxy, 'inst-1', {
instructions: 'test-mcp-server',
})
expect(JSON.stringify(full.content)).toContain('does not provide instructions')
@@ -386,7 +382,7 @@ describe('McpService', () => {
const agent = await seedAgentAndUser(teamId, 'Cache Agent')
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: server.id } })
const tools = await service.buildAgentTools(agent.id, teamId)
const full = await (tools[0].execute as ProxyExecute)('inst-1', {
const full = await invokeTool(tools[0], 'inst-1', {
instructions: 'cache-srv',
})
expect(JSON.stringify(full.content)).toContain('Always use the read-only API.')
@@ -661,12 +657,11 @@ describe('McpService', () => {
expect(tools[0].description).toContain('test-mcp-server')
// Executing the proxy's call mode hits the real server.
const result = await (
tools[0].execute as (
id: string,
params: unknown,
) => Promise<{ content: Array<{ type: string; text?: string }> }>
)('call-1', { server: 'test-mcp-server', tool: 'echo', args: { text: 'via-proxy' } })
const result = await invokeTool(tools[0], 'call-1', {
server: 'test-mcp-server',
tool: 'echo',
args: { text: 'via-proxy' },
})
expect(JSON.stringify(result.content)).toContain('echo:via-proxy')
})
@@ -704,7 +699,7 @@ describe('McpService', () => {
try {
// The agent only has tavily assigned. Asking for a tool that does not
// exist on tavily must not surface airtable's tool names as suggestions.
const result = await (proxy.execute as ProxyExecute)('leak-1', {
const result = await invokeTool(proxy, 'leak-1', {
server: 'tavily-mcp',
tool: 'search',
})
@@ -721,7 +716,7 @@ describe('McpService', () => {
it('does not resolve, search or describe tools of unassigned servers', async () => {
const { proxy, tavilySrv, airtableSrv } = await seedAgentWithUnassignedServer()
try {
const execute = proxy.execute as ProxyExecute
const execute = (id: string, args: Record<string, unknown>) => invokeTool(proxy, id, args)
// 1. Direct tool call with the unassigned server's prefixed tool name
// (no server param) must not execute airtable's handler.
@@ -758,10 +753,10 @@ describe('McpService', () => {
where: { agentId: agent.id, mcpServerId: airtable.id },
})
tools = await service.buildAgentTools(agent.id, teamId)
const search = await (tools[0].execute as ProxyExecute)('leak-5', { search: 'records' })
const search = await invokeTool(tools[0], 'leak-5', { search: 'records' })
expect(JSON.stringify(search.content)).not.toContain('airtable')
const call = await (tools[0].execute as ProxyExecute)('leak-6', {
const call = await invokeTool(tools[0], 'leak-6', {
tool: 'airtable_mcp_server_search_records',
})
expect(JSON.stringify(call.content)).not.toContain('AIRTABLE-SECRET-DATA')
@@ -836,12 +831,7 @@ describe('McpService', () => {
// Direct tool executes through callMcpTool.
const echo = tools.find((t) => t.name === 'test_mcp_server_echo')!
const result = await (
echo.execute as (
id: string,
params: unknown,
) => Promise<{ content: Array<{ type: string; text?: string }> }>
)('call-2', { text: 'direct' })
const result = await invokeTool(echo, 'call-2', { text: 'direct' })
expect(JSON.stringify(result.content)).toContain('echo:direct')
})
@@ -867,15 +857,15 @@ describe('McpService', () => {
)
expect(proxy.description).toContain('test-mcp-server (1 tools, status:')
const list = await (proxy.execute as ProxyExecute)('excl-list-1', {
const list = await invokeTool(proxy, 'excl-list-1', {
server: 'test-mcp-server',
})
expect(JSON.stringify(list.content)).not.toContain('test_mcp_server_add')
const search = await (proxy.execute as ProxyExecute)('excl-search-1', { search: 'add' })
const search = await invokeTool(proxy, 'excl-search-1', { search: 'add' })
expect(JSON.stringify(search.content)).not.toContain('test_mcp_server_add')
const call = await (proxy.execute as ProxyExecute)('excl-call-1', {
const call = await invokeTool(proxy, 'excl-call-1', {
server: 'test-mcp-server',
tool: 'add',
args: { a: 1, b: 2 },
@@ -987,29 +977,14 @@ describe('McpService', () => {
expect(tools.length).toBe(1) // only the proxy
const proxy = tools[0]
const callA = await (
proxy.execute as (
id: string,
params: unknown,
) => Promise<{ content: Array<{ type: string; text?: string }> }>
)('c1', { server: 'srvA', tool: 'shared' })
const callA = await invokeTool(proxy, 'c1', { server: 'srvA', tool: 'shared' })
expect(JSON.stringify(callA.content)).toContain('from-A')
const callB = await (
proxy.execute as (
id: string,
params: unknown,
) => Promise<{ content: Array<{ type: string; text?: string }> }>
)('c2', { server: 'srvB', tool: 'shared' })
const callB = await invokeTool(proxy, 'c2', { server: 'srvB', tool: 'shared' })
expect(JSON.stringify(callB.content)).toContain('from-B')
// Prefixed names also resolve without the server parameter.
const prefixed = await (
proxy.execute as (
id: string,
params: unknown,
) => Promise<{ content: Array<{ type: string; text?: string }> }>
)('c3', { tool: 'srvA_get' })
const prefixed = await invokeTool(proxy, 'c3', { tool: 'srvA_get' })
expect(JSON.stringify(prefixed.content)).toContain('A')
} finally {
await srvA.stop()
+9 -6
View File
@@ -2,8 +2,14 @@
* McpService — CRUD, discovery, OAuth, and agent integration for MCP servers.
*/
import type {
ToolRegistration as AgentTool,
ToolExecutionResult as AgentToolResult,
} from '@earendil-works/pi-durable'
import { auth } from '@modelcontextprotocol/client'
import type { AgentTool, AgentToolResult } from '@earendil-works/pi-agent-core'
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
import { logger } from '@shumai/core/src/logger'
import { quotaService } from '@shumai/core/src/quota/quota-service'
import { prisma, type TeamMemberRole } from '@shumai/db'
import '@shumai/db/src/prisma-json-types'
import type {
@@ -12,20 +18,17 @@ import type {
McpServerInfo,
UpdateMcpServerRequest,
} from '@shumai/dtos'
import { logger } from '@shumai/core/src/logger'
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
import { quotaService } from '@shumai/core/src/quota/quota-service'
import { mcpDbStore, type PendingAuth } from './mcp-db-store'
import { buildDirectTools, isDirectTool } from './mcp-direct-tools'
import { McpOauthProvider, type McpOauthConfig } from './mcp-oauth-provider'
import { buildProxyTool, transformMcpContent, type McpProxyToolContext } from './mcp-proxy-tool'
import { McpServerManager, type McpServerDefinition } from './mcp-server-manager'
import {
formatToolName,
McpToolRegistry,
sanitizeServerPrefix,
type ToolMetadata,
} from './mcp-tool-registry'
import { McpServerManager, type McpServerDefinition } from './mcp-server-manager'
const ROLE_HIERARCHY: Record<string, number> = {
owner: 3,
@@ -39,7 +42,7 @@ export interface McpToolCallContext {
projectId?: string
}
export type McpToolCallContent = AgentToolResult<Record<string, unknown>>['content']
export type McpToolCallContent = NonNullable<AgentToolResult['output']>
export interface McpToolCallResult {
ok: boolean
@@ -1,13 +1,3 @@
import {
getEffortThinkingLevelMap,
type ModelsDevReasoningOption,
} from './models-dev-reasoning-options.ts'
import {
CLOUDFLARE_AI_GATEWAY_ANTHROPIC_BASE_URL,
CLOUDFLARE_AI_GATEWAY_COMPAT_BASE_URL,
CLOUDFLARE_AI_GATEWAY_OPENAI_BASE_URL,
CLOUDFLARE_WORKERS_AI_BASE_URL,
} from '@earendil-works/pi-ai/api/cloudflare'
import type {
AnthropicMessagesCompat,
Api,
@@ -17,6 +7,16 @@ import type {
OpenAICompletionsCompat,
OpenAIResponsesCompat,
} from '@earendil-works/pi-ai'
import {
CLOUDFLARE_AI_GATEWAY_ANTHROPIC_BASE_URL,
CLOUDFLARE_AI_GATEWAY_COMPAT_BASE_URL,
CLOUDFLARE_AI_GATEWAY_OPENAI_BASE_URL,
CLOUDFLARE_WORKERS_AI_BASE_URL,
} from '@earendil-works/pi-ai/api/cloudflare'
import {
getEffortThinkingLevelMap,
type ModelsDevReasoningOption,
} from './models-dev-reasoning-options.ts'
export interface GeneratorOptions {
strict?: boolean
@@ -1951,7 +1951,6 @@ async function loadModelsDevData(): Promise<Model<any>[]> {
const compat = isKimiK3 ? { ...moonshotCompat } : moonshotCompat
if (isKimiK3) {
compat.requiresReasoningContentOnAssistantMessages = true
compat.deferredToolsMode = 'kimi'
compat.thinkingFormat = 'openai'
compat.supportsReasoningEffort = true
}
+17 -11
View File
@@ -8,17 +8,17 @@ import {
type TeamMemberRole,
} from '@shumai/db'
import {
type CreateQuotaRuleRequest,
type ListQuotaRulesResponse,
type QuotaRuleResponse,
type ListQuotaRecordsResponse,
type QuotaRecordResponse,
type UpdateQuotaRuleRequest,
normalizeQuotaPeriod,
bashResourceDataSchema,
formatQuotaPeriod,
mcpResourceDataSchema,
bashResourceDataSchema,
normalizeQuotaPeriod,
toolResourceDataSchema,
type CreateQuotaRuleRequest,
type ListQuotaRecordsResponse,
type ListQuotaRulesResponse,
type QuotaRecordResponse,
type QuotaRuleResponse,
type UpdateQuotaRuleRequest,
} from '@shumai/dtos'
import { HTTPException } from 'hono/http-exception'
@@ -765,7 +765,11 @@ export class QuotaService {
* Lazy resets the period window in-place when previous window has expired.
* Uses SELECT ... FOR UPDATE inside transactions for atomic concurrency protection.
*/
async consumeQuota(event: QuotaEvent, amount: number): Promise<void> {
async consumeQuota(
event: QuotaEvent,
amount: number,
transaction?: Prisma.TransactionClient,
): Promise<void> {
if (amount <= 0) return
const rules = await this.findMatchingRules(event)
@@ -776,7 +780,7 @@ export class QuotaService {
for (const rule of rules) {
const targetUserId = getQuotaRuleTargetUserId(rule, event)
await this.prismaClient.$transaction(async (tx) => {
const consume = async (tx: Prisma.TransactionClient) => {
if (targetUserId === null) {
// Serialize all_members (shared pool) creations and updates on the parent rule row
await tx.$queryRaw`SELECT id FROM quota_rules WHERE id = ${rule.id} FOR UPDATE`
@@ -851,7 +855,9 @@ export class QuotaService {
})
}
}
})
}
if (transaction) await consume(transaction)
else await this.prismaClient.$transaction(consume)
}
}
}