mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 00:19:26 +00:00
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:
@@ -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 } } },
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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 })
|
||||
}
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user