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
File diff suppressed because it is too large Load Diff
+211 -569
View File
@@ -1,13 +1,18 @@
import { type AgentMessage, type AgentTool } from '@earendil-works/pi-agent-core'
import { BACKGROUND_CONTEXT as piContext } from '@earendil-works/chord/context'
import type { AssistantMessage } from '@earendil-works/pi-ai'
import { type ImageContent } from '@earendil-works/pi-ai'
import type { ToolRegistration as AgentTool, JsonObject } from '@earendil-works/pi-durable'
import { getAgentRequiredLevel, getRoleLevel } from '@shumai/core/src/agent/permissions'
import { S3_PLACEHOLDER } from '@shumai/core/src/agent/session-content'
import { agentSessionService } from '@shumai/core/src/agent/session-service'
import { assetService } from '@shumai/core/src/asset/asset'
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
import { logger } from '@shumai/core/src/logger'
import { mcpService } from '@shumai/core/src/mcp/mcp-service'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { s3Service } from '@shumai/core/src/s3/s3'
import { getAgentRequiredLevel, getRoleLevel } from '@shumai/core/src/agent/permissions'
import { AssetType, prisma, Prisma, type Skill } from '@shumai/db'
import { serializeContextToXml, ShumaiMessageEntry } from '@shumai/dtos'
import {
ApplicationFailure,
defineStep,
@@ -15,23 +20,18 @@ import {
registerLocalCancelHandler,
unregisterLocalCancelHandler,
} from '@shumai/workflow-core'
import { DatabaseSessionStorage } from '../database-session-storage'
import { randomUUID } from 'node:crypto'
import { initializeCommentSession, synchronizeCommentContext } from '../comment-context'
import {
createAgentSession,
fieldsToTypeBoxSchema,
type AutofillField,
type DbProviderInfo,
} from '../index'
} from '../runtime'
import { aiUsageService } from '@shumai/core/src/ai-usage/ai-usage'
import { quotaService, QuotaExceededError } from '@shumai/core/src/quota/quota-service'
import { QuotaExceededError, quotaService } from '@shumai/core/src/quota/quota-service'
import { getProxyType } from '@shumai/core/src/utils/mime'
import { secondToDegree } from '@shumai/core/src/utils/model3d'
import {
UpdateAssetMetadataRequest,
type ShumaiMessageContext,
type ShumaiMediaPosition,
} from '@shumai/dtos'
import { UpdateAssetMetadataRequest, type ShumaiMessageContext } from '@shumai/dtos'
export interface Usage {
inputTokens: number
@@ -206,7 +206,30 @@ User messages may contain a <context> block detailing the user, active asset loc
)
: []
const { session, harness } = await createAgentSession({
// A workflow retry must reopen the same autofill session before submitting its stable request ID.
let persistedSessionId = params.sessionId
if (!persistedSessionId && params.taskId) {
persistedSessionId = await prisma.$transaction(async (tx) => {
await tx.$queryRaw`SELECT id FROM workflow_tasks WHERE id = ${params.taskId} FOR UPDATE`
const task = await tx.workflowTask.findUniqueOrThrow({ where: { id: params.taskId } })
if (task.sessionId) return task.sessionId
const record = await tx.agentSession.create({
data: {
agentId: params.agentId,
userId: params.userId,
cwd: process.cwd(),
assetId: params.assetId,
},
})
await tx.workflowTask.update({ where: { id: task.id }, data: { sessionId: record.id } })
return record.id
})
}
const {
session,
harness,
sessionId: activeSessionId,
} = await createAgentSession({
teamId: params.teamId,
agentId: params.agentId,
providerName,
@@ -220,7 +243,7 @@ User messages may contain a <context> block detailing the user, active asset loc
})),
enabledSkillIds,
allowedDomains,
sessionId: params.sessionId,
sessionId: persistedSessionId,
userId: params.userId,
projectId: params.projectId,
assetId: params.assetId,
@@ -237,225 +260,155 @@ User messages may contain a <context> block detailing the user, active asset loc
})),
})
const imagesToPass: ImageContent[] = []
if (params.images && params.images.length > 0) {
for (const key of params.images) {
const { buffer, contentType } = await s3Service.getObject(
process.env.S3_BUCKET || 'shumai',
key,
)
imagesToPass.push({
type: 'image',
data: buffer.toString('base64'),
mimeType: contentType,
})
}
}
const onAbort = () => {
harness.abort()
void session.abort(piContext).catch((err) => logger.error({ err }, 'Failed to stop agent'))
}
const abortSignal = getLocalTaskAbortSignal(params.taskId)
if (abortSignal) {
if (abortSignal.aborted) {
harness.abort()
} else {
abortSignal.addEventListener('abort', onAbort, { once: true })
}
} else if (params.taskId) {
registerLocalCancelHandler(params.taskId, () => {
harness.abort()
})
}
if (abortSignal) abortSignal.addEventListener('abort', onAbort, { once: true })
else if (params.taskId) registerLocalCancelHandler(params.taskId, onAbort)
try {
const storage = session.getStorage()
if (storage instanceof DatabaseSessionStorage && params.messageContext) {
storage.currentMessageContext = params.messageContext
}
let totalInputTokens = 0
let totalOutputTokens = 0
let totalCacheReadTokens = 0
let grandTotalTokens = 0
let totalCost = 0
if (abortSignal?.aborted)
throw ApplicationFailure.create({ message: 'Agent execution stopped.', nonRetryable: true })
const effectiveRole = params.userId
? await resolveEffectiveRole(params.teamId, params.projectId, params.userId)
: undefined
try {
await quotaService.checkQuota(
{
teamId: params.teamId,
userId: params.userId,
role: effectiveRole,
resource: 'agent_total_tokens',
},
0,
)
await quotaService.checkQuota(
{
teamId: params.teamId,
userId: params.userId,
role: effectiveRole,
resource: 'agent_cost',
},
0,
)
} catch (err) {
if (err instanceof QuotaExceededError) {
throw ApplicationFailure.create({
message: err.message,
nonRetryable: true,
})
for (const resource of ['agent_total_tokens', 'agent_cost'] as const) {
await quotaService.checkQuota(
{ teamId: params.teamId, userId: params.userId, role: effectiveRole, resource },
0,
)
}
} catch (err) {
if (err instanceof QuotaExceededError)
throw ApplicationFailure.create({ message: err.message, nonRetryable: true })
throw err
}
harness.subscribe(async (event) => {
if (event.type === 'message_end' && event.message.role === 'assistant') {
const assistantMsg = event.message
const u = assistantMsg.usage
if (u) {
const inputTokens = u.input || 0
const outputTokens = u.output || 0
const cacheReadTokens = u.cacheRead || 0
const totalTokens = u.totalTokens || inputTokens + outputTokens
const cost = u.cost?.total || 0
totalInputTokens += inputTokens
totalOutputTokens += outputTokens
totalCacheReadTokens += cacheReadTokens
grandTotalTokens += totalTokens
totalCost += cost
try {
await aiUsageService.recordUsage({
teamId: params.teamId,
userId: params.userId,
inputTokens,
outputTokens,
cacheReadTokens,
totalTokens,
cost,
})
} catch (err) {
logger.error({ err }, 'Failed to record AI usage')
}
try {
await quotaService.consumeQuota(
{
teamId: params.teamId,
userId: params.userId,
role: effectiveRole,
resource: 'agent_total_tokens',
},
totalTokens,
)
await quotaService.consumeQuota(
{
teamId: params.teamId,
userId: params.userId,
role: effectiveRole,
resource: 'agent_cost',
},
cost,
)
} catch (err) {
logger.error({ err }, 'Failed to record quota usage for AI call')
}
}
}
})
const assistantMessage = await harness.prompt(params.prompt, { images: imagesToPass })
if (totalInputTokens === 0 && totalOutputTokens === 0 && assistantMessage.usage) {
totalInputTokens = assistantMessage.usage.input || 0
totalOutputTokens = assistantMessage.usage.output || 0
totalCacheReadTokens = assistantMessage.usage.cacheRead || 0
grandTotalTokens = assistantMessage.usage.totalTokens || totalInputTokens + totalOutputTokens
totalCost = assistantMessage.usage.cost?.total || 0
try {
await quotaService.consumeQuota(
{
teamId: params.teamId,
userId: params.userId,
role: effectiveRole,
resource: 'agent_total_tokens',
},
grandTotalTokens,
)
await quotaService.consumeQuota(
{
teamId: params.teamId,
userId: params.userId,
role: effectiveRole,
resource: 'agent_cost',
},
totalCost,
)
} catch (err) {
logger.error({ err }, 'Failed to record fallback quota usage for AI call')
}
}
const sessionEntries = await session.getEntries()
sessionEntries.forEach((entry) => {
if (entry.type === 'message' && entry.message) {
const msg = entry.message
if (msg.role === 'toolResult') {
const logMsg = { ...msg, content: undefined }
logger.debug(logMsg, 'agent message')
} else {
logger.debug(msg, 'agent message')
}
}
})
let text = assistantMessage.content
.filter((c) => c.type === 'text')
.map((c) => {
if ('text' in c && typeof c.text === 'string') {
return c.text
}
return ''
if (params.userCommentId) {
await synchronizeCommentContext({
conversation: session,
sessionId: activeSessionId,
teamId: params.teamId,
agentId: params.agentId,
userCommentId: params.userCommentId,
})
.join('\n')
if (assistantMessage.stopReason === 'error' && assistantMessage.errorMessage) {
if (text) {
text += '\n\n'
}
text += `Error: ${assistantMessage.errorMessage}`
}
const requestId = params.taskId || params.userCommentId || randomUUID()
const context = {
...params.messageContext,
id: params.userCommentId || `chat:${activeSessionId}:${requestId}`,
}
const xml = serializeContextToXml(context)
const images: ImageContent[] = []
for (const key of params.images) {
const { contentType } = await s3Service.getObject(process.env.S3_BUCKET || 'shumai', key)
images.push({ type: 'image', data: S3_PLACEHOLDER, mimeType: contentType })
}
const submission = await session.submit(
{
type: 'input',
requestId,
content: [
{ type: 'text', text: xml ? `${params.prompt}\n\n${xml}` : params.prompt },
...images,
],
entry: {
kind: ShumaiMessageEntry.kind,
data: JSON.parse(
JSON.stringify({
displayText: params.prompt,
timestamp: Date.now(),
context,
sourceCommentId: params.userCommentId,
sourceKeys: params.images,
}),
) as JsonObject,
},
},
piContext,
)
const settled = await submission.wait(piContext)
if (settled.status !== 'done' || settled.type !== 'input') {
let detail = ''
const recent = await session.entries?.({ order: 'descending' }, 20, undefined, piContext)
for (const entry of recent?.items ?? []) {
const failure = entry.model?.find(
(message) => message.role === 'assistant' && message.errorMessage,
)
if (failure?.role === 'assistant') {
detail = `: ${failure.errorMessage}`
break
}
}
throw ApplicationFailure.create({
message: `Agent run ended without an answer: ${settled.status === 'unanswered' ? settled.reason : settled.status}${detail}`,
nonRetryable: true,
})
}
const answer = await session.commit((tx) => tx.entry(settled.answer), piContext)
const assistantMessage = answer?.model?.find(
(message): message is AssistantMessage => message.role === 'assistant',
)
if (!assistantMessage) throw new Error('Agent answer is missing')
if (assistantMessage.stopReason === 'error')
throw ApplicationFailure.create({
message: assistantMessage.errorMessage || 'Agent generation failed',
nonRetryable: true,
})
const totals = await harness.usage(piContext)
const usage: Usage = {
model: modelId,
inputTokens: totalInputTokens,
outputTokens: totalOutputTokens,
cacheReadTokens: totalCacheReadTokens,
totalTokens: grandTotalTokens,
cost: totalCost,
inputTokens: 0,
outputTokens: 0,
cacheReadTokens: 0,
totalTokens: 0,
cost: 0,
}
let sessionId = ''
if (storage instanceof DatabaseSessionStorage) {
sessionId = storage.sessionId
for (const value of Object.values(totals.models)) {
usage.inputTokens += value.input
usage.outputTokens += value.output
usage.cacheReadTokens += value.cacheRead
usage.totalTokens += value.totalTokens
usage.cost += value.cost.total
}
return { text, usage, sessionId }
// Accounting is committed with the native usage ledger; workflow reporting uses this request's entries.
if (session.entries) {
Object.assign(usage, {
inputTokens: 0,
outputTokens: 0,
cacheReadTokens: 0,
totalTokens: 0,
cost: 0,
})
let cursor: import('@earendil-works/pi-durable').Cursor | undefined
do {
const page = await session.entries(
{ order: 'ascending', minEntryId: settled.entry, maxEntryId: settled.answer },
100,
cursor,
piContext,
)
for (const entry of page.items)
for (const message of entry.model ?? [])
if (message.role === 'assistant') {
usage.inputTokens += message.usage.input
usage.outputTokens += message.usage.output
usage.cacheReadTokens += message.usage.cacheRead
usage.totalTokens += message.usage.totalTokens
usage.cost += message.usage.cost.total
}
cursor = page.next
} while (cursor)
}
const text = assistantMessage.content
.filter((block) => block.type === 'text')
.map((block) => block.text)
.join('\n')
return { text, usage, sessionId: activeSessionId }
} finally {
if (abortSignal) {
abortSignal.removeEventListener('abort', onAbort)
}
if (params.taskId) {
unregisterLocalCancelHandler(params.taskId)
}
abortSignal?.removeEventListener('abort', onAbort)
if (params.taskId) unregisterLocalCancelHandler(params.taskId)
await harness.close(piContext)
}
}
@@ -522,6 +475,7 @@ export const agentChatActivity = defineStep(async function agentChatActivity(
})
export interface AutofillAiParams {
taskId?: string
teamId: string
images?: string[]
fields: AutofillField[]
@@ -542,14 +496,13 @@ export const autofillAiActivity = defineStep(async function autofillAiActivity(
const autofillTool: AgentTool = {
name: 'autofill_metadata',
label: 'Autofill Metadata',
description: 'Provide the extracted metadata once you have analyzed the asset content.',
parameters: toolSchema,
execute: async (_toolCallId, toolParams) => {
execute: async (toolParams) => {
capturedData = toolParams as Record<string, unknown>
return {
content: [{ type: 'text', text: 'Metadata captured successfully.' }],
details: {},
output: [{ type: 'text', text: 'Metadata captured successfully.' }],
details: { metadata: toolParams as JsonObject },
}
},
}
@@ -592,6 +545,7 @@ export const autofillAiActivity = defineStep(async function autofillAiActivity(
const { agent } = params.context
const { usage, sessionId } = await executeAgentPrompt({
taskId: params.taskId,
teamId: params.teamId,
agentId: agent.id,
prompt: fullPrompt,
@@ -604,6 +558,24 @@ export const autofillAiActivity = defineStep(async function autofillAiActivity(
context: params.context,
})
if (!capturedData) {
for (const entry of await agentSessionService.getEntries(sessionId))
for (const message of entry.model ?? []) {
if (
message.role === 'toolResult' &&
message.toolName === 'autofill_metadata' &&
!message.isError &&
message.details &&
typeof message.details === 'object' &&
!Array.isArray(message.details) &&
'metadata' in message.details &&
message.details.metadata &&
typeof message.details.metadata === 'object' &&
!Array.isArray(message.details.metadata)
)
capturedData = Object.fromEntries(Object.entries(message.details.metadata))
}
}
return {
text: capturedData ? JSON.stringify(capturedData) : '{}',
usage,
@@ -611,355 +583,9 @@ export const autofillAiActivity = defineStep(async function autofillAiActivity(
}
})
export const initializeAgentSessionActivity = defineStep(
async function initializeAgentSessionActivity(params: {
teamId: string
agentId: string
userCommentId: string
userId?: string
}): Promise<string> {
const agentId = params.agentId === 'default' ? 'default' : params.agentId
// Ensure user exists for agent
const userExists = await prisma.user.findUnique({ where: { id: agentId } })
if (!userExists) {
await prisma.user.create({
data: {
id: agentId,
name: 'Ai Agent',
email: `${agentId}@shumai.ai`,
type: 'agent',
},
})
}
// Ensure agent exists
const agentExists = await prisma.agent.findUnique({ where: { id: agentId } })
if (!agentExists) {
await prisma.agent.create({
data: {
id: agentId,
teamId: params.teamId,
type: 'chat',
config: {
provider: 'openai',
model: 'gpt-4',
},
},
})
}
const userComment = await prisma.assetComment.findUnique({
where: { id: params.userCommentId },
include: { creator: true },
})
if (!userComment) {
throw new Error(`User comment ${params.userCommentId} not found`)
}
const rootCommentId = userComment.replyToId || userComment.id
const targetUserCommentId = rootCommentId
let session = await prisma.agentSession.findFirst({
where: {
assetId: userComment.assetId,
type: 'comment',
userCommentId: targetUserCommentId,
},
})
if (!session) {
session = await prisma.agentSession.create({
data: {
agentId,
userId: params.userId || null,
cwd: process.cwd(),
assetId: userComment.assetId,
userCommentId: targetUserCommentId,
type: 'comment',
},
})
}
const rootComment = await prisma.assetComment.findUnique({
where: { id: rootCommentId },
include: { creator: true },
})
if (!rootComment) {
throw new Error(`Root comment ${rootCommentId} not found`)
}
// Ensure preceding top-level comments up to rootCommentId are synced in Main Session first
let mainSession = await prisma.agentSession.findFirst({
where: {
assetId: userComment.assetId,
type: 'comment',
userCommentId: null,
},
})
if (!mainSession) {
mainSession = await prisma.agentSession.create({
data: {
agentId,
userId: params.userId || null,
cwd: process.cwd(),
assetId: userComment.assetId,
userCommentId: null,
type: 'comment',
},
})
}
// 1. Fetch top-level comments up to rootComment.createdAt sorted by id
const topLevelComments = await prisma.assetComment.findMany({
where: {
assetId: userComment.assetId,
replyToId: null,
createdAt: { lte: rootComment.createdAt },
},
orderBy: { id: 'asc' },
include: {
creator: true,
attachments: { include: { asset: true } },
},
})
// 2. Fetch thread replies up to userComment.createdAt excluding userComment itself
const threadReplies = userComment.replyToId
? await prisma.assetComment.findMany({
where: {
replyToId: rootCommentId,
createdAt: { lte: userComment.createdAt },
id: { not: userComment.id },
},
orderBy: { id: 'asc' },
include: {
creator: true,
attachments: { include: { asset: true } },
},
})
: []
const allCommentsToSync = [...topLevelComments, ...threadReplies]
// Resolve user mentions from IDs to names and roles
const mentionRegex = /<@([^>]+)>/g
const mentionedUserIds = new Set<string>()
for (const c of allCommentsToSync) {
if (c.message) {
const matches = [...c.message.matchAll(mentionRegex)]
for (const match of matches) {
mentionedUserIds.add(match[1])
}
}
}
const userIdToNameMap = new Map<string, string>()
if (mentionedUserIds.size > 0) {
const resolvedUsers = await prisma.user.findMany({
where: { id: { in: Array.from(mentionedUserIds) } },
select: { id: true, name: true },
})
for (const u of resolvedUsers) {
if (u.name) userIdToNameMap.set(u.id, u.name)
}
}
const userRoleMap = new Map<string, string>()
const humanCreatorIds = Array.from(
new Set(
allCommentsToSync
.filter((c) => c.creator?.type !== 'agent' && c.creatorId)
.map((c) => c.creatorId!),
),
)
if (humanCreatorIds.length > 0) {
const members = await prisma.teamMember.findMany({
where: {
teamId: params.teamId,
userId: { in: humanCreatorIds },
},
select: { userId: true, role: true },
})
for (const m of members) {
userRoleMap.set(m.userId, m.role)
}
}
const assetRecord = await prisma.asset.findUnique({
where: { id: userComment.assetId },
select: { media: true },
})
const proxyType = (assetRecord?.media as PrismaJson.MediaInfo | null)?.proxyType
function buildCommentEntry(c: (typeof allCommentsToSync)[0]) {
const isAgent = c.creator?.type === 'agent' || c.sessionId !== null
let messageContent = c.message || ''
messageContent = messageContent.replace(mentionRegex, (match, userId) => {
const resolvedName = userIdToNameMap.get(userId)
return resolvedName ? `<@${resolvedName}>` : match
})
if (isAgent) {
const message: AgentMessage = {
role: 'assistant',
content: [{ type: 'text', text: messageContent }],
api: 'custom',
provider: 'shumai',
model: 'agent',
usage: {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0,
totalTokens: 0,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
},
stopReason: 'stop',
timestamp: c.createdAt.getTime(),
}
return {
type: 'message' as const,
data: { message },
}
}
let userObj: ShumaiMessageContext['user'] = undefined
if (c.creator) {
const role = (c.creatorId ? userRoleMap.get(c.creatorId) : undefined) || 'user'
userObj = {
id: c.creator.id,
name: c.creator.name || 'Unknown',
role,
}
}
let position: ShumaiMediaPosition | undefined = undefined
if (c.second !== null && c.second !== undefined) {
if (proxyType === '3d') {
position = { type: 'degree', degree: secondToDegree(c.second) }
} else if (proxyType === 'pdf') {
position = { type: 'page', page: Math.round(c.second) }
} else {
position = { type: 'time', seconds: c.second }
}
}
const annotation = !!(c.annotation && Array.isArray(c.annotation) && c.annotation.length > 0)
const attachedFiles: ShumaiMessageContext['attachedFiles'] = []
if (c.attachments && c.attachments.length > 0) {
for (const att of c.attachments) {
if (att.asset) {
const attProxyType = (att.asset.media as PrismaJson.MediaInfo | null)?.proxyType
attachedFiles.push({
id: att.asset.id,
name: att.asset.name,
type: att.asset.type,
mediaType: attProxyType as
'image' | 'video' | 'pdf' | 'audio' | '3d' | 'other' | undefined,
mimeType: att.asset.mediaType || undefined,
})
}
}
}
const commentDetails: ShumaiMessageContext = {
id: c.id,
...(userObj ? { user: userObj } : {}),
...(position ? { position } : {}),
...(annotation
? {
annotation: true,
annotations: c.annotation as unknown as ShumaiMessageContext['annotations'],
}
: {}),
...(attachedFiles.length > 0 ? { attachedFiles } : {}),
}
return {
type: 'custom_message' as const,
data: {
customType: 'shumai_message',
content: messageContent,
display: true,
details: commentDetails,
},
}
}
// 3. Sync top-level comments into agent_session_entries (DAG spine)
let mainPrevId: string | null = null
for (const c of topLevelComments) {
const existingEntry = await prisma.agentSessionEntry.findUnique({
where: { id: c.id },
select: { id: true },
})
if (!existingEntry) {
const entryData = buildCommentEntry(c)
await prisma.agentSessionEntry.create({
data: {
id: c.id,
sessionId: mainSession.id,
assetId: userComment.assetId,
type: entryData.type,
parentId: mainPrevId,
createdAt: c.createdAt,
data: entryData.data as PrismaJson.PiSessionEntryData,
},
})
}
mainPrevId = c.id
}
if (mainPrevId) {
await prisma.agentSession.update({
where: { id: mainSession.id },
data: { leafId: mainPrevId },
})
}
// 4. Sync thread replies and set Thread Session leafId
let threadLeafId: string = rootCommentId
if (threadReplies.length > 0) {
let lastReplyParentId: string = rootCommentId
for (const reply of threadReplies) {
const existingReplyEntry = await prisma.agentSessionEntry.findUnique({
where: { id: reply.id },
select: { id: true },
})
if (!existingReplyEntry) {
const entryData = buildCommentEntry(reply)
await prisma.agentSessionEntry.create({
data: {
id: reply.id,
sessionId: session.id,
assetId: userComment.assetId,
type: entryData.type,
parentId: lastReplyParentId,
createdAt: reply.createdAt,
data: entryData.data as PrismaJson.PiSessionEntryData,
},
})
}
lastReplyParentId = reply.id
}
threadLeafId = lastReplyParentId
}
await prisma.agentSession.update({
where: { id: session.id },
data: { leafId: threadLeafId },
})
return session.id
},
)
export const initializeAgentSessionActivity = defineStep(initializeCommentSession, {
name: 'initializeAgentSessionActivity',
})
export const deleteCommentActivity = defineStep(async function deleteCommentActivity(
commentId: string,
@@ -1499,7 +1125,23 @@ export const generateSessionNameActivity = defineStep(async function generateSes
})
const promptToTitle = `Generate a short 2 to 4 word title for a session starting with this message:\n\n<user_message>\n${prompt}\n</user_message>`
const result = await harness.prompt(promptToTitle)
let result: AssistantMessage
try {
const conversation = await harness.root(piContext)
const settled = await (
await conversation.submit(
{ type: 'input', content: promptToTitle, requestId: 'title' },
piContext,
)
).wait(piContext)
if (settled.status !== 'done' || settled.type !== 'input') return
const entry = await conversation.commit((tx) => tx.entry(settled.answer), piContext)
const message = entry?.model?.find((m): m is AssistantMessage => m.role === 'assistant')
if (!message) return
result = message
} finally {
await harness.close(piContext)
}
if (result.stopReason === 'error' || result.stopReason === 'aborted' || result.errorMessage) {
logger.error(
+75 -214
View File
@@ -1,10 +1,13 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { BACKGROUND_CONTEXT } from '@earendil-works/chord/context'
import { createModels } from '@earendil-works/pi-ai'
import { Harness, createRegistry } from '@earendil-works/pi-durable'
import { agentSessionService } from '@shumai/core/src/agent/session-service'
import { resolveAnnotationsById } from '@shumai/core/src/asset-read/annotations'
import { degreeToSecond } from '@shumai/core/src/utils/model3d'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { resolveAnnotationsById } from '@shumai/core/src/asset-read/annotations'
import { DatabaseSessionStorage } from './database-session-storage'
import type { SessionTreeEntry } from '@earendil-works/pi-agent-core'
import { degreeToSecond } from '@shumai/core/src/utils/model3d'
import type { ShumaiMessageContext } from '@shumai/dtos'
import { beforeEach, describe, expect, it } from 'vitest'
describe('resolveAnnotationsById', () => {
setupTestDbHooks()
@@ -84,10 +87,10 @@ describe('resolveAnnotationsById', () => {
data: { name: 'Project', teamId: team.id },
})
const assetA = await prisma.asset.create({
data: { name: 'videoA.mp4', type: 'file', projectId: project.id, status: 'uploaded' },
data: { name: 'videoA.mp4', type: 'file', status: 'uploaded', projectId: project.id },
})
const assetB = await prisma.asset.create({
data: { name: 'videoB.mp4', type: 'file', projectId: project.id, status: 'uploaded' },
data: { name: 'videoB.mp4', type: 'file', status: 'uploaded', projectId: project.id },
})
const commentB = await prisma.assetComment.create({
@@ -113,236 +116,94 @@ describe('resolveAnnotationsById', () => {
)
})
it('resolves annotations and timestamp from AgentSessionEntry (1-on-1 Chat Mode)', async () => {
const user = await prisma.user.create({
data: { name: 'Chat User', email: 'chatuser@test.com', password: 'pw' },
})
const team = await prisma.team.create({
data: { name: 'Chat Team' },
})
const project = await prisma.project.create({
data: { name: 'Chat Project', teamId: team.id },
})
async function fixture() {
const team = await prisma.team.create({ data: { name: 'Native annotation team' } })
const project = await prisma.project.create({ data: { name: 'Project', teamId: team.id } })
const asset = await prisma.asset.create({
data: {
name: 'chat-video.mp4',
type: 'file',
projectId: project.id,
status: 'uploaded',
},
data: { name: 'video.mp4', type: 'file', status: 'uploaded', projectId: project.id },
})
const agentUser = await prisma.user.create({
data: { name: 'Chat Bot User', email: 'bot@example.com', type: 'agent' },
const other = await prisma.asset.create({
data: { name: 'other.mp4', type: 'file', status: 'uploaded', projectId: project.id },
})
const user = await prisma.user.create({
data: { name: 'Agent', email: 'native@test.com', type: 'agent' },
})
const agent = await prisma.agent.create({
data: {
id: agentUser.id,
id: user.id,
teamId: team.id,
type: 'chat',
config: { provider: 'test-provider', model: 'test-model' },
config: { provider: 'faux', model: 'faux-1' },
},
})
const session = await prisma.agentSession.create({ data: { agentId: agent.id, cwd: '/test' } })
return { session, asset, other }
}
// Create session storage
const storage = await DatabaseSessionStorage.create({
agentId: agent.id,
userId: user.id,
assetId: asset.id,
async function annotate(sessionId: string, requestId: string, context: ShumaiMessageContext) {
await 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)
await root.submit(
{
type: 'write',
requestId,
entry: {
kind: 'shumai.message',
data: JSON.parse(
JSON.stringify({ displayText: 'Check markup', timestamp: 1, context }),
),
},
},
BACKGROUND_CONTEXT,
)
} finally {
await harness.close(BACKGROUND_CONTEXT)
}
})
return `chat:${sessionId}:${requestId}`
}
// Set active message context with markup annotations and position
storage.currentMessageContext = {
currentAsset: {
id: asset.id,
name: asset.name,
type: 'file',
path: asset.name,
},
it('resolves annotations after a SQLite cache rebuild using the durable submission reference', async () => {
const { session, asset } = await fixture()
const id = await annotate(session.id, 'request', {
currentAsset: { id: asset.id, name: asset.name, type: 'file' },
position: { type: 'time', seconds: 12.34 },
annotation: true,
annotations: [
{
type: 'rectangle',
x: 100,
y: 200,
width: 50,
height: 50,
},
],
}
// User sends a message -> DatabaseSessionStorage.appendEntry is called
const userEntry: SessionTreeEntry = {
type: 'message',
id: '01JTESTENTRY1234567890',
parentId: null,
timestamp: new Date().toISOString(),
message: {
role: 'user',
content: 'Check this rectangle markup on video',
timestamp: Date.now(),
},
}
await storage.appendEntry(userEntry)
// Verify DatabaseSessionStorage persisted entry with details.id = entry.id
const dbEntry = await prisma.agentSessionEntry.findUnique({
where: { id: '01JTESTENTRY1234567890' },
annotations: [{ type: 'box' }],
})
await agentSessionService.closeAll()
expect(await resolveAnnotationsById(asset.id, id)).toEqual({
timestamp: 12.34,
annotations: [{ type: 'box' }],
})
expect(dbEntry).toBeDefined()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const details = (dbEntry?.data as any)?.details
expect(details.id).toBe('01JTESTENTRY1234567890')
expect(details.position).toEqual({ type: 'time', seconds: 12.34 })
expect(details.annotations).toHaveLength(1)
// Now resolveAnnotationsById directly with the entry id and matching asset.id
const result = await resolveAnnotationsById(asset.id, '01JTESTENTRY1234567890')
expect(result.timestamp).toBe(12.34)
expect(result.annotations).toEqual([
{
type: 'rectangle',
x: 100,
y: 200,
width: 50,
height: 50,
},
])
})
it('resolves annotations and degree position timestamp from 1-on-1 chat AgentSessionEntry for 3D assets', async () => {
const user = await prisma.user.create({
data: { name: 'User 3D', email: 'user3d@test.com', password: 'pw' },
})
const team = await prisma.team.create({
data: { name: 'Team 3D' },
})
const project = await prisma.project.create({
data: { name: 'Project 3D', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'robot.glb',
type: 'file',
projectId: project.id,
status: 'uploaded',
},
})
const agentUser = await prisma.user.create({
data: { name: 'Agent 3D', email: 'agent3d@example.com', type: 'agent' },
})
const agent = await prisma.agent.create({
data: {
id: agentUser.id,
teamId: team.id,
type: 'chat',
config: { provider: 'test-provider', model: 'test-model' },
},
})
const storage = await DatabaseSessionStorage.create({
agentId: agent.id,
userId: user.id,
assetId: asset.id,
})
storage.currentMessageContext = {
currentAsset: {
id: asset.id,
name: asset.name,
type: 'file',
path: asset.name,
},
it('resolves degree positions as timestamps for 3D assets', async () => {
const { session, asset } = await fixture()
const id = await annotate(session.id, 'degree', {
currentAsset: { id: asset.id, name: asset.name, type: 'file' },
position: { type: 'degree', degree: 45 },
annotation: true,
annotations: [
{
type: 'rectangle',
x: 10,
y: 20,
width: 30,
height: 40,
},
],
}
const userEntry: SessionTreeEntry = {
type: 'message',
id: '01JTEST3DENTRY123456789',
parentId: null,
timestamp: new Date().toISOString(),
message: {
role: 'user',
content: 'Check markup at 45 degrees',
timestamp: Date.now(),
},
}
await storage.appendEntry(userEntry)
const result = await resolveAnnotationsById(asset.id, '01JTEST3DENTRY123456789')
expect(result.timestamp).toBeCloseTo(degreeToSecond(45))
expect(result.annotations).toEqual([
{
type: 'rectangle',
x: 10,
y: 20,
width: 30,
height: 40,
},
])
annotations: [{ type: 'box' }],
})
expect((await resolveAnnotationsById(asset.id, id)).timestamp).toBeCloseTo(degreeToSecond(45))
})
it('throws an error when AgentSessionEntry belongs to a different asset', async () => {
const user = await prisma.user.create({
data: { name: 'User', email: 'user3@test.com', password: 'pw' },
})
const team = await prisma.team.create({
data: { name: 'Team' },
})
const project = await prisma.project.create({
data: { name: 'Project', teamId: team.id },
})
const assetA = await prisma.asset.create({
data: { name: 'chatA.mp4', type: 'file', projectId: project.id, status: 'uploaded' },
})
const assetB = await prisma.asset.create({
data: { name: 'chatB.mp4', type: 'file', projectId: project.id, status: 'uploaded' },
})
const agentUser = await prisma.user.create({
data: { name: 'Bot User', email: 'bot2@example.com', type: 'agent' },
})
const agent = await prisma.agent.create({
data: {
id: agentUser.id,
teamId: team.id,
type: 'chat',
config: { provider: 'test-provider', model: 'test-model' },
},
})
const storage = await DatabaseSessionStorage.create({
agentId: agent.id,
userId: user.id,
assetId: assetB.id,
})
storage.currentMessageContext = {
currentAsset: { id: assetB.id, name: assetB.name, type: 'file', path: assetB.name },
it('rejects references to another asset', async () => {
const { session, asset, other } = await fixture()
const id = await annotate(session.id, 'request', {
currentAsset: { id: asset.id, name: asset.name, type: 'file' },
annotation: true,
annotations: [{ type: 'box' }],
}
const userEntry: SessionTreeEntry = {
type: 'message',
id: '01JENTRYONASSETB123456',
parentId: null,
timestamp: new Date().toISOString(),
message: { role: 'user', content: 'Markup on B', timestamp: Date.now() },
}
await storage.appendEntry(userEntry)
await expect(resolveAnnotationsById(assetA.id, '01JENTRYONASSETB123456')).rejects.toThrow(
`Annotation "01JENTRYONASSETB123456" belongs to asset "${assetB.id}", not target asset "${assetA.id}".`,
})
await expect(resolveAnnotationsById(other.id, id)).rejects.toThrow(
`belongs to asset "${asset.id}"`,
)
})
+396
View File
@@ -0,0 +1,396 @@
import { createModels, fauxAssistantMessage, type Models } from '@earendil-works/pi-ai'
import { AssistantMessageEventStream } from '@earendil-works/pi-ai/utils/event-stream'
import { BACKGROUND_CONTEXT } from '@earendil-works/chord/context'
import { Harness, createRegistry } from '@earendil-works/pi-durable'
import { agentSessionService } from '@shumai/core/src/agent/session-service'
import { prisma, type AssetComment } from '@shumai/db'
import { acquireAdvisoryLock } from '@shumai/db/src/advisory-lock'
import { setupTestDbHooks } from '@shumai/db/test'
import { getShumaiMessage } from '@shumai/dtos'
import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest'
import { agentChatActivity, getAgentChatContextActivity } from './activities/agent'
import { initializeCommentSession, synchronizeCommentContext } from './comment-context'
import { closeAgentSessions } from './runtime'
async function createThread() {
const team = await prisma.team.create({ data: { name: 'Concurrent comment team' } })
const project = await prisma.project.create({
data: { name: 'Concurrent comment project', teamId: team.id },
})
const users = await Promise.all(
Array.from({ length: 5 }, (_, index) =>
prisma.user.create({
data: { name: `User ${index}`, email: `comment-user-${index}@example.test` },
}),
),
)
await prisma.teamMember.createMany({
data: users.map((user) => ({ teamId: team.id, userId: user.id, role: 'owner' })),
})
const provider = await prisma.provider.create({
data: {
teamId: team.id,
name: 'google',
config: { api: 'google-generative-ai', apiKey: 'unused-test-key' },
},
})
const model = await prisma.model.create({
data: {
providerId: provider.id,
modelId: 'gemini-test',
config: {
input: ['text'],
reasoning: false,
contextWindow: 8192,
maxTokens: 1024,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
},
},
})
const agentUser = await prisma.user.create({
data: { name: 'Comment agent', email: 'comment-agent@example.test', type: 'agent' },
})
const agent = await prisma.agent.create({
data: {
id: agentUser.id,
teamId: team.id,
type: 'chat',
providerId: provider.id,
modelId: model.id,
config: { provider: 'google', model: 'gemini-test' },
},
})
const asset = await prisma.asset.create({
data: { name: 'comments.txt', type: 'file', projectId: project.id, status: 'processed' },
})
const root = await prisma.assetComment.create({
data: {
assetId: asset.id,
creatorId: users[0].id,
message: 'Discuss this asset here.',
createdAt: new Date('2026-01-01T00:00:00.000Z'),
},
})
const mentions: AssetComment[] = []
for (const [index, user] of users.entries()) {
mentions.push(
await prisma.assetComment.create({
data: {
assetId: asset.id,
creatorId: user.id,
replyToId: root.id,
message: `<@${agent.id}> Request ${index}`,
// Explicit ordering makes the imported history independent of clock resolution.
createdAt: new Date(root.createdAt.getTime() + index + 1),
},
}),
)
}
const initialize = (comment: AssetComment) =>
initializeCommentSession({
teamId: team.id,
agentId: agent.id,
userId: comment.creatorId!,
userCommentId: comment.id,
})
const tasks = await prisma.workflowTask.createManyAndReturn({
data: mentions.map((comment) => ({
teamId: team.id,
projectId: project.id,
assetId: asset.id,
type: 'chat',
status: 'pending',
payload: {
projectId: project.id,
agent: { agentId: agent.id, userId: comment.creatorId!, userCommentId: comment.id },
},
})),
})
const reply = async (comment: AssetComment, sessionId: string) => {
const context = await getAgentChatContextActivity({
teamId: team.id,
agentId: agent.id,
userId: comment.creatorId!,
projectId: project.id,
})
return agentChatActivity({
taskId: tasks.find((task) => task.payload?.agent?.userCommentId === comment.id)!.id,
teamId: team.id,
agentId: agent.id,
sessionId,
userId: comment.creatorId!,
userCommentId: comment.id,
message: comment.message!,
imageUrls: [],
projectId: project.id,
folderId: asset.id,
assetId: asset.id,
context,
})
}
return { team, project, users, agent, asset, root, mentions, tasks, initialize, reply }
}
describe('Comment session concurrency regressions', () => {
setupTestDbHooks()
afterEach(async () => {
await closeAgentSessions()
vi.restoreAllMocks()
})
describe('simultaneous first mentions in a human-created thread', () => {
let sessionIds: string[]
let persistedIds: string[]
beforeEach(async () => {
const thread = await createThread()
sessionIds = await Promise.all(thread.mentions.map(thread.initialize))
const sessions = await prisma.agentSession.findMany({
where: { assetId: thread.asset.id, type: 'comment', userCommentId: thread.root.id },
orderBy: { id: 'asc' },
})
persistedIds = sessions.map((session) => session.id)
// Keep setup/storage failures outside the expected-failure assertion.
expect(sessionIds).toHaveLength(5)
expect(new Set(persistedIds)).toEqual(new Set(sessionIds))
for (const sessionId of new Set(sessionIds)) {
expect(await prisma.agentSession.findUnique({ where: { id: sessionId } })).toMatchObject({
agentId: thread.agent.id,
assetId: thread.asset.id,
userCommentId: thread.root.id,
})
}
})
it('uses one durable session for all five callers', () => {
expect({ returned: [...new Set(sessionIds)], persisted: persistedIds }).toEqual({
returned: [sessionIds[0]],
persisted: [sessionIds[0]],
})
})
})
describe('concurrent history synchronization before live submissions', () => {
let sourceCounts: number[]
let thread: Awaited<ReturnType<typeof createThread>>
let sessionId: string
let model: MockInstance<Models['streamSimple']>
beforeEach(async () => {
// Mock only the provider boundary; admission, history, locks, SQLite, and DB remain real.
model = vi
.spyOn(Object.getPrototypeOf(createModels()) as Models, 'streamSimple')
.mockImplementation(() => {
const stream = new AssistantMessageEventStream()
const answer = fauxAssistantMessage('Test reply')
answer.usage = { ...answer.usage, input: 3, output: 2, totalTokens: 5 }
stream.push({ type: 'done', reason: 'stop', message: answer })
stream.end()
return stream
})
thread = await createThread()
sessionId = await thread.initialize(thread.root)
const initialized = await Promise.all(thread.mentions.map(thread.initialize))
expect(new Set(initialized)).toEqual(new Set([sessionId]))
// All initializers can finish before the workflows acquire their generation writer.
const replies = await Promise.all(
thread.mentions.map((comment) => thread.reply(comment, sessionId)),
)
expect(replies.map((reply) => reply.text)).toEqual(Array(5).fill('Test reply'))
expect(model).toHaveBeenCalledTimes(5)
// Reopen from PostgreSQL commits rather than trusting the in-process SQLite cache.
await closeAgentSessions()
const entries = await agentSessionService.getEntries(sessionId)
sourceCounts = thread.mentions.map(
(comment) =>
entries.filter((entry) => getShumaiMessage(entry)?.sourceCommentId === comment.id).length,
)
expect(sourceCounts).toHaveLength(5)
expect(sourceCounts.every((count) => count >= 1)).toBe(true)
})
it('includes each source comment only once in persisted model history', () => {
expect(sourceCounts).toEqual([1, 1, 1, 1, 1])
})
it('recovers a completed request without another model call, input, or usage charge', async () => {
const usage = await prisma.aiUsage.findMany({
where: { teamId: thread.team.id },
orderBy: { id: 'desc' },
})
const entries = await agentSessionService.getEntries(sessionId)
await closeAgentSessions()
expect((await thread.reply(thread.mentions[0], sessionId)).text).toBe('Test reply')
expect(model).toHaveBeenCalledTimes(5)
expect(await agentSessionService.getEntries(sessionId)).toEqual(entries)
expect(
await prisma.aiUsage.findMany({
where: { teamId: thread.team.id },
orderBy: { id: 'desc' },
}),
).toEqual(usage)
})
})
it('keeps different agents and different thread roots in separate sessions', async () => {
const thread = await createThread()
const first = await thread.initialize(thread.root)
const secondRoot = await prisma.assetComment.create({
data: { assetId: thread.asset.id, creatorId: thread.users[0].id, message: 'Another thread' },
})
const agentUser = await prisma.user.create({
data: { name: 'Second agent', email: 'second-agent@example.test', type: 'agent' },
})
await prisma.agent.create({
data: { id: agentUser.id, teamId: thread.team.id, type: 'chat', config: thread.agent.config },
})
const [secondThread, secondAgent] = await Promise.all([
thread.initialize(secondRoot),
initializeCommentSession({
teamId: thread.team.id,
agentId: agentUser.id,
userCommentId: thread.root.id,
}),
])
expect(new Set([first, secondThread, secondAgent]).size).toBe(3)
expect(await thread.initialize(thread.root)).toBe(first)
})
it('imports context-only comments once while reserving workflow-owned comments in every status', async () => {
const thread = await createThread()
const statuses = ['pending', 'processing', 'failed', 'completed', 'pending'] as const
for (const [index, task] of thread.tasks.entries()) {
await prisma.workflowTask.update({
where: { id: task.id },
data: { status: statuses[index] },
})
}
const note = await prisma.assetComment.create({
data: {
assetId: thread.asset.id,
creatorId: thread.users[0].id,
replyToId: thread.root.id,
message: 'Keep this review note.',
createdAt: new Date(thread.root.createdAt.getTime() + 1),
},
})
const otherAgentComment = await prisma.assetComment.create({
data: {
assetId: thread.asset.id,
creatorId: thread.users[1].id,
replyToId: thread.root.id,
message: 'A request for another agent.',
createdAt: new Date(thread.root.createdAt.getTime() + 2),
},
})
await prisma.workflowTask.create({
data: {
assetId: thread.asset.id,
type: 'chat',
status: 'pending',
payload: {
projectId: thread.project.id,
agent: { agentId: 'another-agent', userCommentId: otherAgentComment.id },
},
},
})
await prisma.assetComment.create({
data: {
assetId: thread.asset.id,
replyToId: thread.root.id,
message: '__CHAT__',
createdAt: new Date(thread.root.createdAt.getTime() + 3),
},
})
const earlierThread = await prisma.assetComment.create({
data: {
assetId: thread.asset.id,
creatorId: thread.users[0].id,
message: 'An earlier top-level agent request.',
createdAt: new Date(thread.root.createdAt.getTime() - 1),
},
})
await prisma.workflowTask.create({
data: {
assetId: thread.asset.id,
type: 'chat',
status: 'pending',
payload: {
projectId: thread.project.id,
agent: { agentId: thread.agent.id, userCommentId: earlierThread.id },
},
},
})
const sessionId = await thread.initialize(thread.root)
await agentSessionService.withWriter(sessionId, async (storage) => {
const harness = await Harness.open(
storage,
{ models: createModels(), registry: createRegistry() },
BACKGROUND_CONTEXT,
)
try {
const params = {
conversation: await harness.root(BACKGROUND_CONTEXT),
sessionId,
teamId: thread.team.id,
agentId: thread.agent.id,
userCommentId: thread.mentions[4].id,
}
await synchronizeCommentContext(params)
await synchronizeCommentContext(params)
} finally {
await harness.close(BACKGROUND_CONTEXT)
}
})
await closeAgentSessions()
const sources = (await agentSessionService.getEntries(sessionId)).map(
(entry) => getShumaiMessage(entry)?.sourceCommentId,
)
expect(new Set(sources)).toEqual(
new Set([earlierThread.id, thread.root.id, note.id, otherAgentComment.id]),
)
expect(sources).toHaveLength(4)
})
it('reuses the oldest duplicate session without rewriting existing records', async () => {
const thread = await createThread()
const first = await thread.initialize(thread.root)
const duplicate = await prisma.agentSession.create({
data: {
agentId: thread.agent.id,
assetId: thread.asset.id,
userCommentId: thread.root.id,
type: 'comment',
cwd: process.cwd(),
},
})
const original = await prisma.agentSession.findMany({
where: { id: { in: [first, duplicate.id] } },
orderBy: { id: 'desc' },
})
expect(await thread.initialize(thread.root)).toBe([first, duplicate.id].sort()[0])
expect(
await prisma.agentSession.findMany({
where: { id: { in: [first, duplicate.id] } },
orderBy: { id: 'desc' },
}),
).toEqual(original)
})
it('releases the thread creation lock when initialization rolls back', async () => {
const thread = await createThread()
const agentUser = await prisma.user.create({
data: { name: 'New agent', email: 'new-agent@example.test', type: 'agent' },
})
const params = { teamId: thread.team.id, agentId: agentUser.id, userCommentId: thread.root.id }
await expect(initializeCommentSession({ ...params, teamId: 'missing-team' })).rejects.toThrow()
const lock = await acquireAdvisoryLock(
`agent-thread:${agentUser.id}:${thread.asset.id}:${thread.root.id}`,
AbortSignal.timeout(2000),
)
await lock.release()
expect(await prisma.agent.findUnique({ where: { id: agentUser.id } })).toBeNull()
expect(await initializeCommentSession(params)).toBeTruthy()
})
})
+373
View File
@@ -0,0 +1,373 @@
import { BACKGROUND_CONTEXT as piContext } from '@earendil-works/chord/context'
import { type Message as AgentMessage } from '@earendil-works/pi-ai'
import {
type Conversation,
defineDoc,
type Cursor,
type EntryDraft,
type JsonObject,
} from '@earendil-works/pi-durable'
import { secondToDegree } from '@shumai/core/src/utils/model3d'
import { prisma } from '@shumai/db'
import {
ShumaiMessageEntry,
type ShumaiMediaPosition,
type ShumaiMessageContext,
} from '@shumai/dtos'
import { ApplicationFailure } from '@shumai/workflow-core'
const ThreadContextDoc = defineDoc<{ commentIds: string[] }>({
kind: 'shumai.thread',
version: 1,
scope: 'conversation',
history: 'latest',
fork: 'initial',
initial: () => ({ commentIds: [] }),
checkpointWhen: () => true,
})
export async function initializeCommentSession(params: {
teamId: string
agentId: string
userCommentId: string
userId?: string
}): Promise<string> {
const userComment = await prisma.assetComment.findUnique({
where: { id: params.userCommentId },
select: { assetId: true, replyToId: true },
})
if (!userComment) {
throw ApplicationFailure.create({
message: `User comment ${params.userCommentId} not found`,
nonRetryable: true,
})
}
const rootCommentId = userComment.replyToId || params.userCommentId
const threadKey = `agent-thread:${params.agentId}:${userComment.assetId}:${rootCommentId}`
return prisma.$transaction(async (tx) => {
// The lock and insert share a transaction, so rollback also releases ownership.
// Unlike the writer lock, this key exists before a session ID has been chosen.
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${threadKey}, 0))`
await tx.user.upsert({
where: { id: params.agentId },
update: {},
create: {
id: params.agentId,
name: 'Ai Agent',
email: `${params.agentId}@shumai.ai`,
type: 'agent',
},
})
await tx.agent.upsert({
where: { id: params.agentId },
update: {},
create: {
id: params.agentId,
teamId: params.teamId,
type: 'chat',
config: { provider: 'openai', model: 'gpt-4' },
},
})
const existing = await tx.agentSession.findFirst({
where: {
agentId: params.agentId,
assetId: userComment.assetId,
type: 'comment',
userCommentId: rootCommentId,
},
// Reuse the original session deterministically if older data contains duplicates.
orderBy: { id: 'asc' },
})
if (existing) return existing.id
const session = await tx.agentSession.create({
data: {
agentId: params.agentId,
userId: params.userId || null,
cwd: process.cwd(),
assetId: userComment.assetId,
userCommentId: rootCommentId,
type: 'comment',
},
})
return session.id
})
}
/** Import passive history while the caller owns the generation's session writer. */
export async function synchronizeCommentContext(params: {
conversation: Conversation
sessionId: string
teamId: string
agentId: string
userCommentId: string
}): Promise<void> {
const userComment = await prisma.assetComment.findUnique({
where: { id: params.userCommentId },
include: { creator: true },
})
if (!userComment) {
throw ApplicationFailure.create({
message: `User comment ${params.userCommentId} not found`,
nonRetryable: true,
})
}
const rootCommentId = userComment.replyToId || userComment.id
const rootComment = await prisma.assetComment.findUnique({
where: { id: rootCommentId },
include: { creator: true },
})
if (!rootComment) {
throw ApplicationFailure.create({
message: `Root comment ${rootCommentId} not found`,
nonRetryable: true,
})
}
// 1. Fetch top-level comments up to rootComment.createdAt sorted by id
const topLevelComments = await prisma.assetComment.findMany({
where: {
assetId: userComment.assetId,
replyToId: null,
createdAt: { lte: rootComment.createdAt },
},
orderBy: { id: 'asc' },
include: {
creator: true,
attachments: { include: { asset: true } },
},
})
// 2. Fetch thread replies up to userComment.createdAt excluding userComment itself
const threadReplies = userComment.replyToId
? await prisma.assetComment.findMany({
where: {
replyToId: rootCommentId,
createdAt: { lte: userComment.createdAt },
id: { not: userComment.id },
},
orderBy: { id: 'asc' },
include: {
creator: true,
attachments: { include: { asset: true } },
},
})
: []
const replyCounts = await prisma.assetComment.groupBy({
by: ['replyToId'],
where: { assetId: userComment.assetId, replyToId: { not: null }, message: { not: '__CHAT__' } },
_count: true,
})
const counts = new Map(replyCounts.map((row) => [row.replyToId, row._count]))
const allCommentsToSync = [...topLevelComments, ...threadReplies]
// Resolve user mentions from IDs to names and roles
const mentionRegex = /<@([^>]+)>/g
const mentionedUserIds = new Set<string>()
for (const c of allCommentsToSync) {
if (c.message) {
const matches = [...c.message.matchAll(mentionRegex)]
for (const match of matches) {
mentionedUserIds.add(match[1])
}
}
}
const userIdToNameMap = new Map<string, string>()
if (mentionedUserIds.size > 0) {
const resolvedUsers = await prisma.user.findMany({
where: { id: { in: Array.from(mentionedUserIds) } },
select: { id: true, name: true },
})
for (const u of resolvedUsers) {
if (u.name) userIdToNameMap.set(u.id, u.name)
}
}
const userRoleMap = new Map<string, string>()
const humanCreatorIds = Array.from(
new Set(
allCommentsToSync
.filter((c) => c.creator?.type !== 'agent' && c.creatorId)
.map((c) => c.creatorId!),
),
)
if (humanCreatorIds.length > 0) {
const members = await prisma.teamMember.findMany({
where: {
teamId: params.teamId,
userId: { in: humanCreatorIds },
},
select: { userId: true, role: true },
})
for (const m of members) {
userRoleMap.set(m.userId, m.role)
}
}
const assetRecord = await prisma.asset.findUnique({
where: { id: userComment.assetId },
select: { media: true },
})
const proxyType = (assetRecord?.media as PrismaJson.MediaInfo | null)?.proxyType
function buildCommentEntry(c: (typeof allCommentsToSync)[0]): EntryDraft {
const isAgent = c.creator?.type === 'agent' || c.sessionId !== null
let messageContent = c.message || ''
messageContent = messageContent.replace(mentionRegex, (match, userId) => {
const resolvedName = userIdToNameMap.get(userId)
return resolvedName ? `<@${resolvedName}>` : match
})
if (isAgent) {
const message: AgentMessage = {
role: 'assistant',
content: [{ type: 'text', text: messageContent }],
api: 'custom',
provider: 'shumai',
model: 'agent',
usage: {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0,
totalTokens: 0,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
},
stopReason: 'stop',
timestamp: c.createdAt.getTime(),
}
return {
kind: 'pi.assistant',
model: [message],
data: { sourceCommentId: c.id },
}
}
let userObj: ShumaiMessageContext['user'] = undefined
if (c.creator) {
const role = (c.creatorId ? userRoleMap.get(c.creatorId) : undefined) || 'user'
userObj = {
id: c.creator.id,
name: c.creator.name || 'Unknown',
role,
}
}
let position: ShumaiMediaPosition | undefined = undefined
if (c.second !== null && c.second !== undefined) {
if (proxyType === '3d') {
position = { type: 'degree', degree: secondToDegree(c.second) }
} else if (proxyType === 'pdf') {
position = { type: 'page', page: Math.round(c.second) }
} else {
position = { type: 'time', seconds: c.second }
}
}
const annotation = !!(c.annotation && Array.isArray(c.annotation) && c.annotation.length > 0)
const attachedFiles: ShumaiMessageContext['attachedFiles'] = []
if (c.attachments && c.attachments.length > 0) {
for (const att of c.attachments) {
if (att.asset) {
const attProxyType = (att.asset.media as PrismaJson.MediaInfo | null)?.proxyType
attachedFiles.push({
id: att.asset.id,
name: att.asset.name,
type: att.asset.type,
mediaType: attProxyType as
'image' | 'video' | 'pdf' | 'audio' | '3d' | 'other' | undefined,
mimeType: att.asset.mediaType || undefined,
})
}
}
}
const commentDetails: ShumaiMessageContext = {
id: c.id,
...(!c.replyToId && counts.get(c.id)
? { thread: { id: c.id, replyCount: counts.get(c.id)! } }
: {}),
...(userObj ? { user: userObj } : {}),
...(position ? { position } : {}),
...(annotation
? {
annotation: true,
annotations: c.annotation as unknown as ShumaiMessageContext['annotations'],
}
: {}),
...(attachedFiles.length > 0 ? { attachedFiles } : {}),
}
return {
kind: ShumaiMessageEntry.kind,
model: [{ role: 'user' as const, content: messageContent, timestamp: c.createdAt.getTime() }],
data: JSON.parse(
JSON.stringify({
displayText: messageContent,
timestamp: c.createdAt.getTime(),
context: commentDetails,
sourceCommentId: c.id,
}),
) as JsonObject,
}
}
const root = params.conversation
const present = new Set<string>()
let cursor: Cursor | undefined
do {
const page = await root.entries({ order: 'ascending' }, 100, cursor, piContext)
for (const entry of page.items) {
if (
entry.data &&
typeof entry.data === 'object' &&
!Array.isArray(entry.data) &&
'sourceCommentId' in entry.data &&
typeof entry.data.sourceCommentId === 'string'
)
present.add(entry.data.sourceCommentId)
}
cursor = page.next
} while (cursor)
const candidates = allCommentsToSync.filter(
(comment) =>
comment.id !== params.userCommentId &&
comment.sessionId !== params.sessionId &&
comment.message !== '__CHAT__' &&
!present.has(comment.id),
)
if (!candidates.length) return
// A comment and its agent workflows are created in the same DB transaction.
// Reserve these comments for their live input, including across workflow retries.
const threadCommentIds = candidates
.filter((comment) => (comment.replyToId || comment.id) === rootCommentId)
.map((comment) => comment.id)
const tasks = threadCommentIds.length
? await prisma.workflowTask.findMany({
where: {
assetId: userComment.assetId,
type: 'chat',
payload: { path: ['agent', 'agentId'], equals: params.agentId },
OR: threadCommentIds.map((id) => ({
payload: { path: ['agent', 'userCommentId'], equals: id },
})),
},
select: { payload: true },
orderBy: { id: 'desc' },
})
: []
const liveComments = new Set(tasks.map((task) => task.payload?.agent?.userCommentId))
await root.commit(async (tx) => {
const state = await tx.doc(ThreadContextDoc, root.id)
for (const comment of candidates) {
if (liveComments.has(comment.id) || state.commentIds.includes(comment.id)) continue
await tx.appendEntry(root.id, buildCommentEntry(comment))
state.commentIds.push(comment.id)
}
}, piContext)
}
+11 -7
View File
@@ -1,12 +1,14 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type { SandboxConfig, SandboxProvider, WrapCommandOptions } from '@shumai/core'
import { sandboxService } from '@shumai/core'
import type { SandboxProvider, SandboxConfig, WrapCommandOptions } from '@shumai/core'
import { createAgentSession, type DbProviderInfo } from './index'
import { createSandboxedBashTool } from './tools/sandboxed-bash'
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { spawn } from 'node:child_process'
import { EventEmitter } from 'node:events'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createAgentSession, type DbProviderInfo } from './index'
import { closeAgentSessions } from './runtime'
import { createSandboxedBashTool } from './tools/sandboxed-bash'
vi.mock('node:child_process')
@@ -142,7 +144,7 @@ describe('Concurrent Sandbox Sessions', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock spawn return value
;(spawn as any).mockReturnValue(mockChild)
const sessionExecutionA = tool.execute('call-session-a-1', {
const sessionExecutionA = invokeTool(tool, 'call-session-a-1', {
command: 'curl https://api.github.com/repos',
source: 'skill',
})
@@ -244,11 +246,11 @@ describe('Concurrent Sandbox Sessions', () => {
// Record violation for the blocked command only
testProvider.violationsByCommandId.set('call-blocked', 'blocked-target.com')
const blockedExecution = tool.execute('call-blocked', {
const blockedExecution = invokeTool(tool, 'call-blocked', {
command: 'curl http://blocked-target.com',
source: 'skill',
})
const allowedExecution = tool.execute('call-allowed', {
const allowedExecution = invokeTool(tool, 'call-allowed', {
command: 'curl https://api.github.com/data',
source: 'skill',
})
@@ -322,3 +324,5 @@ describe('Concurrent Sandbox Sessions', () => {
expect(sandboxService.getCurrentAllowedDomains()).toEqual(['*.github.com'])
})
})
afterEach(closeAgentSessions)
@@ -1,820 +0,0 @@
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { s3Service } from '@shumai/core/src/s3/s3'
import { type SessionTreeEntry } from '@earendil-works/pi-agent-core'
import { describe, expect, it, vi, afterEach } from 'vitest'
import { DatabaseSessionStorage } from './database-session-storage'
import { agentService } from '@shumai/core/src/agent/agent'
import { createAgentSession, type DbProviderInfo } from './index'
import * as sandboxedBashModule from './tools/sandboxed-bash'
import * as operationToolsModule from './operation-tools'
describe('DatabaseSessionStorage', () => {
setupTestDbHooks()
afterEach(() => {
vi.restoreAllMocks()
})
const mockModelConfig: PrismaJson.ModelConfig = {
reasoning: false,
input: ['text'],
contextWindow: 128000,
maxTokens: 4096,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
}
const mockProviders: DbProviderInfo[] = [
{
name: 'test-provider',
config: { api: 'openai-responses', apiKey: 'TEST_KEY' },
models: [
{
modelId: 'test-model',
name: 'Test Model',
config: mockModelConfig,
},
],
},
]
const setupTestData = async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
const provider = await prisma.provider.create({
data: {
name: 'test-provider',
teamId: team.id,
config: { api: 'openai-responses' },
},
})
const model = await prisma.model.create({
data: {
modelId: 'test-model',
name: 'Test Model',
providerId: provider.id,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config: mockModelConfig as any,
},
})
const user = await prisma.user.create({
data: { name: 'Test User', email: 'test@example.com', type: 'human' },
})
const agent = await prisma.agent.create({
data: {
id: user.id,
teamId: team.id,
type: 'chat',
providerId: provider.id,
modelId: model.id,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config: { provider: 'test-provider', model: 'test-model' } as any,
},
})
return { team, user, agent }
}
it('should create and retrieve metadata', async () => {
const { agent, user } = await setupTestData()
const storage = await DatabaseSessionStorage.create({
agentId: agent.id,
userId: user.id,
cwd: '/test/cwd',
})
const metadata = await storage.getMetadata()
expect(metadata.agentId).toBe(agent.id)
expect(metadata.userId).toBe(user.id)
expect(metadata.cwd).toBe('/test/cwd')
expect(metadata.id).toBeDefined()
expect(metadata.createdAt).toBeDefined()
})
it('should manage leafId', async () => {
const { agent } = await setupTestData()
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
expect(await storage.getLeafId()).toBeNull()
const entry: SessionTreeEntry = {
type: 'message',
id: 'entry-1',
parentId: null,
timestamp: new Date().toISOString(),
message: {
role: 'user',
content: [{ type: 'text', text: 'Test' }],
timestamp: Date.now(),
},
}
await storage.appendEntry(entry)
expect(await storage.getLeafId()).toBe('entry-1')
await storage.setLeafId(null)
expect(await storage.getLeafId()).toBeNull()
})
it('should append and retrieve entries', async () => {
const { agent } = await setupTestData()
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
const entry: SessionTreeEntry = {
type: 'message',
id: 'msg-1',
parentId: null,
timestamp: new Date().toISOString(),
message: {
role: 'user',
content: [{ type: 'text', text: 'hello' }],
timestamp: Date.now(),
},
}
await storage.appendEntry(entry)
// Verify leafId was auto-updated
expect(await storage.getLeafId()).toBe('msg-1')
const retrieved = await storage.getEntry('msg-1')
expect(retrieved).toEqual(entry)
const allEntries = await storage.getEntries()
expect(allEntries).toHaveLength(1)
expect(allEntries[0]).toEqual(entry)
})
it('should find entries by type', async () => {
const { agent } = await setupTestData()
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
await storage.appendEntry({
type: 'message',
id: 'msg-1',
parentId: null,
timestamp: new Date().toISOString(),
message: { role: 'user', content: [], timestamp: Date.now() },
})
await storage.appendEntry({
type: 'thinking_level_change',
id: 'think-1',
parentId: 'msg-1',
timestamp: new Date().toISOString(),
thinkingLevel: 'high',
})
const messages = await storage.findEntries('message')
expect(messages).toHaveLength(1)
expect(messages[0].id).toBe('msg-1')
const thinkChanges = await storage.findEntries('thinking_level_change')
expect(thinkChanges).toHaveLength(1)
expect(thinkChanges[0].id).toBe('think-1')
})
it('should retrieve path to root', async () => {
const { agent } = await setupTestData()
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
await storage.appendEntry({
type: 'message',
id: 'msg-1',
parentId: null,
timestamp: new Date().toISOString(),
message: { role: 'user', content: [], timestamp: Date.now() },
})
await storage.appendEntry({
type: 'message',
id: 'msg-2',
parentId: 'msg-1',
timestamp: new Date().toISOString(),
message: {
role: 'assistant',
content: [],
timestamp: Date.now(),
provider: 'p',
model: 'm',
api: 'api',
usage: { input: 0, output: 0 },
// AssistantMessage has many internal fields from pi-ai
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any,
})
await storage.appendEntry({
type: 'message',
id: 'msg-3',
parentId: 'msg-2',
timestamp: new Date().toISOString(),
message: { role: 'user', content: [], timestamp: Date.now() },
})
const path = await storage.getPathToRoot('msg-3')
expect(path).toHaveLength(3)
expect(path[0].id).toBe('msg-1')
expect(path[1].id).toBe('msg-2')
expect(path[2].id).toBe('msg-3')
})
it('should strip and reinject image data', async () => {
const { agent } = await setupTestData()
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
const getObjectSpy = vi.spyOn(s3Service, 'getObject').mockResolvedValue({
buffer: Buffer.from('reinjected-data'),
contentType: 'image/png',
// S3Object has complex metadata requirements not needed for this test
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
const entry: SessionTreeEntry = {
type: 'message',
id: 'msg-1',
parentId: null,
timestamp: new Date().toISOString(),
message: {
role: 'toolResult',
toolCallId: 'call-1',
toolName: 'tool',
isError: false,
timestamp: Date.now(),
content: [{ type: 'image', data: 'original-base64-data', mimeType: 'image/png' }],
details: {
sourceKeys: ['path/to/image.png'],
},
},
}
await storage.appendEntry(entry)
// Record data is generic Json
const record = await prisma.agentSessionEntry.findUnique({ where: { id: 'msg-1' } })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const savedEntry = record?.data as any
expect(savedEntry.message.content[0].data).toBe('__S3_DATA__')
// Verify retrieval reinjects data
const retrieved = await storage.getEntry('msg-1')
expect(getObjectSpy).toHaveBeenCalledWith('shumai', 'path/to/image.png')
// retrieved is a SessionTreeEntry, but we need to access internal message properties for verification
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((retrieved as any).message.content[0].data).toBe(
Buffer.from('reinjected-data').toString('base64'),
)
})
it('should strip and reinject skill content', async () => {
const { agent } = await setupTestData()
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
const getSkillContentSpy = vi
.spyOn(agentService, 'getSkillContent')
.mockResolvedValue('# Mocked Skill Content')
const entry: SessionTreeEntry = {
type: 'message',
id: 'msg-skill',
parentId: null,
timestamp: new Date().toISOString(),
message: {
role: 'toolResult',
toolCallId: 'call-2',
toolName: 'read_skill',
isError: false,
timestamp: Date.now(),
content: [{ type: 'text', text: 'original-skill-content' }],
details: {
skillId: 'some-skill-id',
},
},
}
await storage.appendEntry(entry)
// Verify saved entry is stripped
const record = await prisma.agentSessionEntry.findUnique({ where: { id: 'msg-skill' } })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const savedEntry = record?.data as any
expect(savedEntry.message.content[0].text).toBe('__SKILL_CONTENT__')
// Verify retrieval reinjects data
const retrieved = await storage.getEntry('msg-skill')
expect(getSkillContentSpy).toHaveBeenCalledWith('some-skill-id')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((retrieved as any).message.content[0].text).toBe('# Mocked Skill Content')
})
it('should restore environment variables when resuming session', async () => {
const { agent, user } = await setupTestData()
// 1. Create a session first to get a sessionId
const initialStorage = await DatabaseSessionStorage.create({ agentId: agent.id })
const sessionId = initialStorage.sessionId
// 2. Append a successful read_skill entry
const entry: SessionTreeEntry = {
type: 'message',
id: 'msg-skill-env',
parentId: null,
timestamp: new Date().toISOString(),
message: {
role: 'toolResult',
toolCallId: 'call-env-1',
toolName: 'read_skill',
isError: false,
timestamp: Date.now(),
content: [{ type: 'text', text: 'skill content' }],
details: {
skillId: 'env-skill-id',
},
},
}
await initialStorage.appendEntry(entry)
// 3. Mock getSkillEnvs to return environment variables
const getSkillEnvsSpy = vi.spyOn(agentService, 'getSkillEnvs').mockResolvedValue({
MOCK_ENV_VAR: 'mocked-value',
})
// 4. Mock agentService.getSkillContent to avoid actual download throws
vi.spyOn(agentService, 'getSkillContent').mockResolvedValue('# Skill')
// 5. Spy on createSandboxedBashTool
const createSandboxedBashToolSpy = vi.spyOn(sandboxedBashModule, 'createSandboxedBashTool')
// 6. Resume the session via createAgentSession
await createAgentSession({
teamId: 't1',
agentId: agent.id,
providerName: 'test-provider',
modelId: 'test-model',
systemPrompt: 'Test prompt',
teamSkills: [],
allowedDomains: [],
sessionId: sessionId,
userId: user.id,
providers: mockProviders,
})
// 7. Verify skill environment variables are restored.
expect(getSkillEnvsSpy).toHaveBeenCalledWith('env-skill-id')
expect(createSandboxedBashToolSpy).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({
MOCK_ENV_VAR: 'mocked-value',
}),
expect.any(Object),
)
})
it('should retrieve label', async () => {
const { agent } = await setupTestData()
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
await storage.appendEntry({
type: 'label',
id: 'label-1',
targetId: 'target-1',
parentId: null,
timestamp: new Date().toISOString(),
label: 'Test Label',
})
const label = await storage.getLabel('label-1')
expect(label).toBe('Test Label')
})
it('should retrieve entries in order', async () => {
const { agent } = await setupTestData()
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
// Insert entries out of order (by insertion time) but with ordered IDs
await storage.appendEntry({
type: 'message',
id: '01B',
parentId: null,
timestamp: new Date().toISOString(),
message: { role: 'user', content: [], timestamp: Date.now() },
})
await storage.appendEntry({
type: 'message',
id: '01A',
parentId: null,
timestamp: new Date().toISOString(),
message: { role: 'user', content: [], timestamp: Date.now() },
})
await storage.appendEntry({
type: 'message',
id: '01C',
parentId: null,
timestamp: new Date().toISOString(),
message: { role: 'user', content: [], timestamp: Date.now() },
})
const entries = await storage.getEntries()
expect(entries).toHaveLength(3)
expect(entries[0].id).toBe('01A')
expect(entries[1].id).toBe('01B')
expect(entries[2].id).toBe('01C')
})
it('should use the current comment ID for media tools in subsequent turns (image)', async () => {
const { agent, user, team } = await setupTestData()
// Create a project and asset to satisfy FK constraints
const project = await prisma.project.create({
data: { name: 'Test Project', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
id: 'asset-123',
name: 'test.png',
type: 'file',
mediaType: 'image/png',
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- partial MediaInfo mock for testing
media: { proxyType: 'image' } as any,
projectId: project.id,
status: 'uploaded',
},
})
// 1. Create a session with an original comment ID and an asset ID using the storage class
const initialStorage = await DatabaseSessionStorage.create({
agentId: agent.id,
userId: user.id,
cwd: '/test/cwd',
assetId: asset.id,
userCommentId: 'original-comment-123',
})
const sessionId = initialStorage.sessionId
// 2. Spy on the Operation tools builder (read_asset comes from the Operation registry)
const buildOperationToolsSpy = vi.spyOn(operationToolsModule, 'buildOperationTools')
// 3. Resume the session via createAgentSession with a NEW comment ID
await createAgentSession({
teamId: 't1',
agentId: agent.id,
providerName: 'test-provider',
modelId: 'test-model',
systemPrompt: 'Test prompt',
teamSkills: [],
allowedDomains: [],
sessionId: sessionId,
userId: user.id,
userCommentId: 'new-comment-456',
providers: mockProviders,
})
// 4. Assert that the tools were built for the user
expect(buildOperationToolsSpy).toHaveBeenCalledWith(
expect.objectContaining({ userId: user.id }),
expect.objectContaining({}),
)
})
it('should instantiate media tools with user ID in subsequent turns (video)', async () => {
const { agent, user, team } = await setupTestData()
// Create a project and asset to satisfy FK constraints
const project = await prisma.project.create({
data: { name: 'Test Project', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
id: 'asset-456',
name: 'test.mp4',
type: 'file',
mediaType: 'video/mp4',
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- partial MediaInfo mock for testing
media: { proxyType: 'video' } as any,
projectId: project.id,
status: 'uploaded',
},
})
// 1. Create a session with an original comment ID and an asset ID using the storage class
const initialStorage = await DatabaseSessionStorage.create({
agentId: agent.id,
userId: user.id,
cwd: '/test/cwd',
assetId: asset.id,
userCommentId: 'original-comment-123',
})
const sessionId = initialStorage.sessionId
// 2. Spy on the Operation tools builder (read_asset comes from the Operation registry)
const buildOperationToolsSpy = vi.spyOn(operationToolsModule, 'buildOperationTools')
// 3. Resume the session via createAgentSession with a NEW comment ID
await createAgentSession({
teamId: 't1',
agentId: agent.id,
providerName: 'test-provider',
modelId: 'test-model',
systemPrompt: 'Test prompt',
teamSkills: [],
allowedDomains: [],
sessionId: sessionId,
userId: user.id,
userCommentId: 'new-comment-456',
providers: mockProviders,
})
// 4. Assert that the tools were built for the user
expect(buildOperationToolsSpy).toHaveBeenCalledWith(
expect.objectContaining({ userId: user.id }),
expect.objectContaining({}),
)
})
describe('P1 Bug Reproductions', () => {
it('should persist a leaf entry and validate targetId when setLeafId is called', async () => {
const { agent } = await setupTestData()
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
const msgEntry: SessionTreeEntry = {
type: 'message',
id: 'msg-100',
parentId: null,
timestamp: new Date().toISOString(),
message: {
role: 'user',
content: [{ type: 'text', text: 'Hello' }],
timestamp: Date.now(),
},
}
await storage.appendEntry(msgEntry)
expect(await storage.getLeafId()).toBe('msg-100')
// setLeafId to an existing entry
await storage.setLeafId('msg-100')
// Verify that a 'leaf' entry was appended to database entries
const entries = await storage.getEntries()
const leafEntries = entries.filter((e) => e.type === 'leaf')
expect(leafEntries.length).toBe(1)
expect(leafEntries[0]).toMatchObject({
type: 'leaf',
targetId: 'msg-100',
})
// Calling setLeafId with non-existent targetId should throw not_found error
await expect(storage.setLeafId('non-existent-id')).rejects.toThrow(
'Entry non-existent-id not found',
)
})
it('should execute appendEntry in a single atomic transaction', async () => {
const { agent } = await setupTestData()
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
// Mock prisma.agentSession.update to throw an error during setLeafId inside appendEntry
const updateSpy = vi
.spyOn(prisma.agentSession, 'update')
.mockRejectedValueOnce(new Error('DB Update Failed'))
const entry: SessionTreeEntry = {
type: 'message',
id: 'atomic-msg-1',
parentId: null,
timestamp: new Date().toISOString(),
message: {
role: 'user',
content: [{ type: 'text', text: 'Atomic test' }],
timestamp: Date.now(),
},
}
await expect(storage.appendEntry(entry)).rejects.toThrow('DB Update Failed')
// Because appendEntry should be atomic, atomic-msg-1 must NOT exist in the database
const dbEntry = await prisma.agentSessionEntry.findUnique({
where: { id: 'atomic-msg-1' },
})
expect(dbEntry).toBeNull()
updateSpy.mockRestore()
})
it('should return session name from agentSession record', async () => {
const { agent } = await setupTestData()
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
expect(await storage.getSessionName()).toBeUndefined()
await prisma.agentSession.update({
where: { id: storage.sessionId },
data: { name: 'My Chat Session' },
})
expect(await storage.getSessionName()).toBe('My Chat Session')
})
it('should aggregate session stats correctly', async () => {
const { agent } = await setupTestData()
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
const msg1: SessionTreeEntry = {
type: 'message',
id: 'stats-msg-1',
parentId: null,
timestamp: new Date().toISOString(),
message: {
role: 'user',
content: [{ type: 'text', text: 'Hello' }],
timestamp: Date.now(),
},
}
const msg2: SessionTreeEntry = {
type: 'message',
id: 'stats-msg-2',
parentId: 'stats-msg-1',
timestamp: new Date().toISOString(),
message: {
role: 'assistant',
content: [{ type: 'text', text: 'Hi there!' }],
api: 'openai-responses',
provider: 'test-provider',
model: 'test-model',
stopReason: 'stop',
timestamp: Date.now(),
usage: {
input: 100,
output: 50,
cacheRead: 20,
cacheWrite: 0,
totalTokens: 170,
cost: { input: 0.01, output: 0.02, cacheRead: 0.002, cacheWrite: 0, total: 0.032 },
},
},
}
await storage.appendEntry(msg1)
await storage.appendEntry(msg2)
const stats = await storage.getSessionStats()
expect(stats.messageCount).toBe(2)
expect(stats.cachedTokens).toBe(20)
expect(stats.uncachedTokens).toBe(150)
expect(stats.totalTokens).toBe(170)
expect(stats.costTotal).toBeCloseTo(0.032)
})
it('should save user message turn as custom_message (shumai_message) in DB when currentMessageContext is set', async () => {
const { agent, user } = await setupTestData()
const storage = await DatabaseSessionStorage.create({ agentId: agent.id, userId: user.id })
storage.currentMessageContext = {
user: { id: user.id, name: user.name, role: 'owner' },
currentAsset: { id: 'asset-123', name: 'video.mp4', type: 'file' },
}
const userEntry: SessionTreeEntry = {
type: 'message',
id: 'msg-user-1',
parentId: null,
timestamp: new Date().toISOString(),
message: {
role: 'user',
content: 'Hello, help me analyze this video',
timestamp: Date.now(),
},
}
await storage.appendEntry(userEntry)
// 1. Verify DB record type is 'custom_message', not 'message'
const record = await prisma.agentSessionEntry.findUnique({
where: { id: 'msg-user-1' },
})
expect(record).toBeDefined()
expect(record?.type).toBe('custom_message')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const data = record?.data as any
expect(data.customType).toBe('shumai_message')
expect(data.content).toBe('Hello, help me analyze this video')
expect(data.details?.user?.id).toBe(user.id)
expect(data.details?.currentAsset?.id).toBe('asset-123')
// 2. Verify getEntries() and getPathToRoot() do not throw and return proper custom_message
const entries = await storage.getEntries()
expect(entries).toHaveLength(1)
expect(entries[0].type).toBe('custom_message')
const pathEntries = await storage.getPathToRoot('msg-user-1')
expect(pathEntries).toHaveLength(1)
expect(pathEntries[0].type).toBe('custom_message')
const stats = await storage.getSessionStats()
expect(stats.messageCount).toBe(1)
})
it('should safely handle legacy records where type was message but data was shumai_message', async () => {
const { agent } = await setupTestData()
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
await prisma.agentSessionEntry.create({
data: {
id: 'legacy-corrupted-entry',
sessionId: storage.sessionId,
type: 'message',
data: {
customType: 'shumai_message',
content: 'Legacy prompt',
display: true,
details: { user: { id: 'u1', name: 'User 1' } },
},
},
})
// Must not throw in getEntries(), getPathToRoot(), or getSessionStats()
const entries = await storage.getEntries()
expect(entries).toHaveLength(1)
expect(entries[0].type).toBe('custom_message')
const path = await storage.getPathToRoot('legacy-corrupted-entry')
expect(path).toHaveLength(1)
expect(path[0].type).toBe('custom_message')
const stats = await storage.getSessionStats()
expect(stats.messageCount).toBe(1)
})
it('should dynamically inject thread metadata into details.thread in getPathToRoot when replies exist', async () => {
const { agent, user } = await setupTestData()
const project = await prisma.project.create({
data: { name: 'Test Project', teamId: agent.teamId },
})
const asset = await prisma.asset.create({
data: {
name: 'Test Asset',
type: 'file',
status: 'uploaded',
projectId: project.id,
},
})
const storage = await DatabaseSessionStorage.create({ agentId: agent.id, assetId: asset.id })
const rootComment = await prisma.assetComment.create({
data: {
id: 'comment-root-1',
assetId: asset.id,
message: 'Top-level question',
creatorId: user.id,
},
})
// Add a reply
await prisma.assetComment.create({
data: {
id: 'comment-reply-1',
assetId: asset.id,
message: 'Reply 1',
creatorId: user.id,
replyToId: rootComment.id,
},
})
// Create session entry for root comment
await prisma.agentSessionEntry.create({
data: {
id: rootComment.id,
sessionId: storage.sessionId,
assetId: asset.id,
type: 'custom_message',
data: {
customType: 'shumai_message',
content: 'Top-level question',
display: true,
details: { user: { id: user.id, name: user.name } },
},
},
})
const path = await storage.getPathToRoot(rootComment.id)
expect(path).toHaveLength(1)
expect(path[0].type).toBe('custom_message')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const details = (path[0] as any).details
expect(details.thread).toEqual({
id: rootComment.id,
replyCount: 1,
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((path[0] as any).content).toBe('Top-level question')
const entries = await storage.getEntries()
expect(entries).toHaveLength(1)
expect(entries[0].type).toBe('custom_message')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((entries[0] as any).details?.thread).toEqual({
id: rootComment.id,
replyCount: 1,
})
})
})
})
@@ -1,511 +0,0 @@
import { prisma } from '@shumai/db'
import { s3Service } from '@shumai/core/src/s3/s3'
import { ulid } from 'ulid'
import {
type AgentMessage,
type SessionMetadata,
type SessionStorage,
type SessionTreeEntry,
} from '@earendil-works/pi-agent-core'
import { agentService } from '@shumai/core/src/agent/agent'
import type { ShumaiMessageContext } from '@shumai/dtos'
export interface DatabaseSessionMetadata extends SessionMetadata {
agentId: string
userId?: string
cwd: string
assetId?: string
userCommentId?: string
}
export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMetadata> {
constructor(public readonly sessionId: string) {}
async getMetadata(): Promise<DatabaseSessionMetadata> {
const session = await prisma.agentSession.findUnique({
where: { id: this.sessionId },
})
if (!session) throw new Error(`Session ${this.sessionId} not found`)
return {
id: session.id,
createdAt: session.createdAt.toISOString(),
agentId: session.agentId,
userId: session.userId || undefined,
cwd: session.cwd,
assetId: session.assetId || undefined,
userCommentId: session.userCommentId || undefined,
}
}
async getLeafId(): Promise<string | null> {
const session = await prisma.agentSession.findUnique({
where: { id: this.sessionId },
select: { leafId: true },
})
return session?.leafId || null
}
async setLeafId(leafId: string | null): Promise<void> {
if (leafId === null) {
await prisma.agentSession.update({
where: { id: this.sessionId },
data: { leafId: null },
})
return
}
const existing = await prisma.agentSessionEntry.findFirst({
where: { id: leafId },
})
if (!existing) {
throw new Error(`Entry ${leafId} not found`)
}
const currentLeafId = await this.getLeafId()
const leafEntry: SessionTreeEntry = {
type: 'leaf',
id: await this.createEntryId(),
parentId: currentLeafId,
timestamp: new Date().toISOString(),
targetId: leafId,
}
await this.appendEntry(leafEntry)
}
nextEntryId?: string | null
currentMessageContext?: PrismaJson.ShumaiMessageContext
async createEntryId(): Promise<string> {
if (this.nextEntryId) {
const id = this.nextEntryId
this.nextEntryId = null
return id
}
return ulid()
}
private recordToEntry(record: {
id: string
type: string | null
parentId: string | null
createdAt: Date
data: unknown
}): SessionTreeEntry {
const payload = (record.data as Record<string, unknown>) || {}
let type = (record.type || 'message') as SessionTreeEntry['type']
if (type === 'message' && payload.customType === 'shumai_message') {
type = 'custom_message'
}
return {
id: record.id,
type,
parentId: record.parentId,
timestamp: record.createdAt.toISOString(),
...payload,
} as unknown as SessionTreeEntry
}
async appendEntry(entry: SessionTreeEntry): Promise<void> {
let entryToProcess = entry
if (
entryToProcess.type === 'message' &&
entryToProcess.message &&
entryToProcess.message.role === 'user' &&
this.currentMessageContext
) {
let contentText = ''
if (typeof entryToProcess.message.content === 'string') {
contentText = entryToProcess.message.content
} else if (Array.isArray(entryToProcess.message.content)) {
contentText = entryToProcess.message.content
.map((c) =>
typeof c === 'object' && c && 'text' in c && typeof c.text === 'string' ? c.text : '',
)
.join('')
}
entryToProcess = {
type: 'custom_message',
id: entryToProcess.id,
parentId: entryToProcess.parentId,
timestamp: entryToProcess.timestamp,
customType: 'shumai_message',
content: contentText,
display: true,
details: {
...this.currentMessageContext,
id: entryToProcess.id,
},
} as unknown as SessionTreeEntry
this.currentMessageContext = undefined
}
const strippedEntry = structuredClone(entryToProcess)
// Strip image data and skill content before saving to DB
if (strippedEntry.type === 'message' && strippedEntry.message) {
const msg = strippedEntry.message
if (msg.role === 'toolResult') {
const details = msg.details as { sourceKeys?: string[]; skillId?: string } | undefined
// Strip S3 image data
if (Array.isArray(msg.content) && details?.sourceKeys) {
const sourceKeys = details.sourceKeys
let keyIdx = 0
msg.content.forEach((item: { type: string; data?: string }) => {
if (item.type === 'image' && sourceKeys[keyIdx]) {
item.data = '__S3_DATA__'
keyIdx++
}
})
}
// Strip skill content
if (msg.toolName === 'read_skill' && !msg.isError) {
if (details?.skillId && Array.isArray(msg.content)) {
msg.content.forEach((item: { type: string; text?: string }) => {
if (
item.type === 'text' &&
item.text &&
!item.text.startsWith('Skill with ID') &&
!item.text.startsWith('Skill downloaded but') &&
!item.text.startsWith('Error reading skill')
) {
item.text = '__SKILL_CONTENT__'
}
})
}
}
}
}
const targetLeafId =
strippedEntry.type === 'leaf'
? (strippedEntry as unknown as { targetId?: string }).targetId || strippedEntry.id
: strippedEntry.id
// Extract base fields and store type-specific properties in data payload
const payload = { ...strippedEntry } as Record<string, unknown>
delete payload.id
delete payload.type
delete payload.parentId
delete payload.timestamp
const session = await prisma.agentSession.findUnique({
where: { id: this.sessionId },
select: { assetId: true },
})
await prisma.$transaction([
prisma.agentSessionEntry.upsert({
where: { id: strippedEntry.id },
create: {
id: strippedEntry.id,
sessionId: this.sessionId,
assetId: session?.assetId || null,
type: strippedEntry.type,
parentId: strippedEntry.parentId || null,
createdAt: strippedEntry.timestamp ? new Date(strippedEntry.timestamp) : new Date(),
data: payload as PrismaJson.PiSessionEntryData,
},
update: {
type: strippedEntry.type,
data: payload as PrismaJson.PiSessionEntryData,
},
}),
prisma.agentSession.update({
where: { id: this.sessionId },
data: { leafId: targetLeafId },
}),
])
}
async getEntry(id: string): Promise<SessionTreeEntry | undefined> {
const record = await prisma.agentSessionEntry.findUnique({
where: { id },
})
if (!record) return undefined
const entry = this.recordToEntry(record)
await this.reinjectImageDataAsync(entry)
await this.reinjectSkillContentAsync(entry)
return entry
}
async findEntries<TType extends SessionTreeEntry['type']>(
type: TType,
): Promise<Array<Extract<SessionTreeEntry, { type: TType }>>> {
const records = await prisma.agentSessionEntry.findMany({
where: {
sessionId: this.sessionId,
type,
},
orderBy: { id: 'asc' },
})
const entries = records.map((r) => this.recordToEntry(r)) as Array<
Extract<SessionTreeEntry, { type: TType }>
>
for (const entry of entries) {
await this.reinjectImageDataAsync(entry)
await this.reinjectSkillContentAsync(entry)
}
return entries
}
async getLabel(id: string): Promise<string | undefined> {
const entry = await this.getEntry(id)
return (entry as { label?: string } | undefined)?.label
}
async getSessionName(): Promise<string | undefined> {
const session = await prisma.agentSession.findUnique({
where: { id: this.sessionId },
select: { name: true },
})
return session?.name || undefined
}
async getSessionStats(): Promise<{
messageCount: number
cachedTokens: number
uncachedTokens: number
totalTokens: number
costTotal: number
}> {
const entries = await this.getEntries()
let messageCount = 0
let cachedTokens = 0
let uncachedTokens = 0
let totalTokens = 0
let costTotal = 0
for (const entry of entries) {
if (entry.type === 'custom_message' && entry.customType === 'shumai_message') {
messageCount++
} else if (entry.type === 'message' && entry.message) {
const msg = entry.message
if (msg.role === 'user' || msg.role === 'assistant') {
messageCount++
}
if (msg.role === 'assistant' && msg.usage) {
cachedTokens += msg.usage.cacheRead || 0
uncachedTokens += (msg.usage.input || 0) + (msg.usage.output || 0)
totalTokens +=
msg.usage.totalTokens ||
(msg.usage.input || 0) + (msg.usage.output || 0) + (msg.usage.cacheRead || 0)
if (msg.usage.cost) {
costTotal += msg.usage.cost.total || 0
}
}
} else if (entry.type === 'compaction' || entry.type === 'branch_summary') {
const usage = entry.usage
if (usage) {
cachedTokens += usage.cacheRead || 0
uncachedTokens += (usage.input || 0) + (usage.output || 0)
totalTokens +=
usage.totalTokens || (usage.input || 0) + (usage.output || 0) + (usage.cacheRead || 0)
if (usage.cost) {
costTotal += usage.cost.total || 0
}
}
}
}
return {
messageCount,
cachedTokens,
uncachedTokens,
totalTokens,
costTotal,
}
}
async getPathToRootOrCompaction(leafId: string | null): Promise<SessionTreeEntry[]> {
return this.getPathToRoot(leafId)
}
async getPathToRoot(leafId: string | null): Promise<SessionTreeEntry[]> {
if (!leafId) return []
interface EntryRow {
id: string
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 prisma.$queryRaw<EntryRow[]>`
WITH RECURSIVE entry_path AS (
SELECT id, type, parent_id, created_at, data, 1 AS depth
FROM agent_session_entries
WHERE id = ${leafId}
UNION ALL
SELECT e.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, type, parent_id, created_at, data
FROM entry_path
ORDER BY depth DESC;
`
const pathEntries: SessionTreeEntry[] = rows.map((r) =>
this.recordToEntry({
id: r.id,
type: r.type,
parentId: r.parent_id,
createdAt: r.created_at,
data: r.data,
}),
)
// Only reinject image data (which may involve S3 calls) for the entries in the path
for (const entry of pathEntries) {
await this.reinjectImageDataAsync(entry)
await this.reinjectSkillContentAsync(entry)
}
return this.injectThreadMetadataAsync(pathEntries)
}
async getEntries(): Promise<SessionTreeEntry[]> {
const records = await prisma.agentSessionEntry.findMany({
where: { sessionId: this.sessionId },
orderBy: { id: 'asc' },
})
const entries = records.map((r) => this.recordToEntry(r))
for (const entry of entries) {
await this.reinjectImageDataAsync(entry)
await this.reinjectSkillContentAsync(entry)
}
return this.injectThreadMetadataAsync(entries)
}
private async injectThreadMetadataAsync(
entries: SessionTreeEntry[],
): Promise<SessionTreeEntry[]> {
const entryIds = entries.map((e) => e.id)
if (entryIds.length === 0) {
return entries
}
const threadCounts = await prisma.assetComment.groupBy({
by: ['replyToId'],
where: {
replyToId: { in: entryIds },
message: { not: '__CHAT__' },
},
_count: {
id: true,
},
})
const threadReplyCountMap = new Map<string, number>()
for (const tc of threadCounts) {
if (tc.replyToId) {
threadReplyCountMap.set(tc.replyToId, tc._count.id)
}
}
if (threadReplyCountMap.size > 0) {
for (let i = 0; i < entries.length; i++) {
const entry = entries[i]
const count = threadReplyCountMap.get(entry.id)
if (count !== undefined && count > 0) {
if (entry.type === 'custom_message') {
const cloned = structuredClone(entry)
const existingDetails = ((cloned as unknown as { details?: ShumaiMessageContext })
.details || {}) as ShumaiMessageContext
;(cloned as unknown as { details: ShumaiMessageContext }).details = {
...existingDetails,
thread: {
id: entry.id,
replyCount: count,
},
}
entries[i] = cloned
}
}
}
}
return entries
}
private async reinjectImageDataAsync(entry: SessionTreeEntry) {
if (entry.type === 'message' && entry.message) {
const msg = entry.message as AgentMessage
if (msg.role === 'toolResult') {
const details = msg.details as { sourceKeys?: string[] } | undefined
if (Array.isArray(msg.content) && details?.sourceKeys) {
const sourceKeys = details.sourceKeys
let keyIdx = 0
for (const item of msg.content) {
if (item.type === 'image' && item.data === '__S3_DATA__' && sourceKeys[keyIdx]) {
const key = sourceKeys[keyIdx]
try {
const { buffer } = await s3Service.getObject(process.env.S3_BUCKET || 'shumai', key)
item.data = buffer.toString('base64')
} catch (err) {
console.error(`Failed to re-inject image data for key ${key}:`, err)
}
keyIdx++
}
}
}
}
}
}
private async reinjectSkillContentAsync(entry: SessionTreeEntry) {
if (entry.type === 'message' && entry.message) {
const msg = entry.message as AgentMessage
if (msg.role === 'toolResult' && msg.toolName === 'read_skill') {
const details = msg.details as { skillId?: string } | undefined
if (details?.skillId && Array.isArray(msg.content)) {
for (const item of msg.content) {
if (item.type === 'text' && item.text === '__SKILL_CONTENT__') {
try {
const content = await agentService.getSkillContent(details.skillId)
item.text = content
} catch (err) {
console.error(
`Failed to re-inject skill content for skill ${details.skillId}:`,
err,
)
}
}
}
}
}
}
}
static async create(params: {
agentId: string
userId?: string
sessionId?: string
cwd?: string
assetId?: string
userCommentId?: string
}): Promise<DatabaseSessionStorage> {
if (params.sessionId) {
return new DatabaseSessionStorage(params.sessionId)
} else {
const session = await prisma.agentSession.create({
data: {
agentId: params.agentId,
userId: params.userId,
cwd: params.cwd || process.cwd(),
assetId: params.assetId || null,
userCommentId: params.userCommentId || null,
},
})
return new DatabaseSessionStorage(session.id)
}
}
}
+144 -70
View File
@@ -1,22 +1,30 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import {
formatSkillsForPrompt,
createAgentSession,
getModelFromDb,
buildRestrictedUserInstructions,
type DbProviderInfo,
} from './index'
import { createSandboxedBashTool } from './tools/sandboxed-bash'
import { SandboxManager, type SandboxAskCallback } from '@anthropic-ai/sandbox-runtime'
import { quotaService } from '@shumai/core/src/quota/quota-service'
import { BACKGROUND_CONTEXT as piContext } from '@earendil-works/chord/context'
import { Harness } from '@earendil-works/pi-durable'
import { appendSessionEntries } from '@shumai/core/src/agent/session-test-utils'
import { getAgentPrompt, getAgentTools, invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
import { quotaService } from '@shumai/core/src/quota/quota-service'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import * as fs from 'fs'
import * as childProcess from 'node:child_process'
import * as path from 'path'
import { type TSchema } from 'typebox'
import { Value } from 'typebox/value'
import * as path from 'path'
import * as childProcess from 'node:child_process'
import * as fs from 'fs'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
buildRestrictedUserInstructions,
createAgentSession,
formatSkillsForPrompt,
getModelFromDb,
type DbProviderInfo,
} from './index'
import { closeAgentSessions } from './runtime'
import { createSandboxedBashTool } from './tools/sandboxed-bash'
afterEach(async () => {
await closeAgentSessions()
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let mockSpawn: any = null
@@ -187,7 +195,10 @@ describe('Sandbox Network isolation integration', () => {
return mockChild
}
const bashPromise = bashTool.execute('1', { command: 'curl blocked-api.com', source: 'user' })
const bashPromise = invokeTool(bashTool, '1', {
command: 'curl blocked-api.com',
source: 'user',
})
try {
await expect(bashPromise).rejects.toThrow(
@@ -417,7 +428,9 @@ describe('Sandbox Network isolation integration', () => {
providers: mockProviders,
thinkingLevel: 'high',
})
expect(harnessHigh.getThinkingLevel()).toBe('high')
expect((await (await harnessHigh.root(piContext)).agent(piContext)).thinkingLevel).toBe(
'high',
)
// Call createAgentSession without thinkingLevel
const { harness: harnessDefault } = await createAgentSession({
@@ -430,7 +443,9 @@ describe('Sandbox Network isolation integration', () => {
allowedDomains: [],
providers: mockProviders,
})
expect(harnessDefault.getThinkingLevel()).toBe('off')
expect((await (await harnessDefault.root(piContext)).agent(piContext)).thinkingLevel).toBe(
'off',
)
} finally {
initializeSpy.mockRestore()
}
@@ -457,9 +472,10 @@ describe('Sandbox Network isolation integration', () => {
},
})
const openSpy = vi.spyOn(Harness, 'open')
const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue()
try {
const { harness } = await createAgentSession({
await createAgentSession({
teamId: team.id,
agentId: 'test-agent-retry',
providerName: 'google',
@@ -472,13 +488,76 @@ describe('Sandbox Network isolation integration', () => {
baseDelayMs: 1500,
})
// @ts-expect-error accessing private property for verification
expect(harness.streamOptions?.maxRetries).toBe(5)
expect(openSpy.mock.calls.at(-1)?.[1].settings).toMatchObject({
retry: { maxRetries: 5, baseDelayMs: 1500 },
})
} finally {
initializeSpy.mockRestore()
}
})
it.each(['openai', 'custom-responses'])(
'authenticates %s Responses sessions using the configured API key',
async (providerName) => {
const team = await prisma.team.create({ data: { name: 'Responses team' } })
const user = await prisma.user.create({
data: { name: 'Responses agent', email: 'responses@test.com', type: 'agent' },
})
const modelId = 'gpt-4.1'
const agent = await prisma.agent.create({
data: {
id: user.id,
teamId: team.id,
type: 'chat',
config: { provider: providerName, model: modelId },
},
})
const baseUrl =
providerName === 'openai' ? 'https://api.openai.com/v1' : 'https://example.test/v1'
const openSpy = vi.spyOn(Harness, 'open')
vi.stubEnv('CLOUDFLARE_ACCOUNT_ID', '')
vi.stubEnv('CLOUDFLARE_GATEWAY_ID', '')
vi.stubEnv('TEST_RESPONSES_API_KEY', 'test-responses-key')
try {
await createAgentSession({
teamId: team.id,
agentId: agent.id,
providerName,
modelId,
systemPrompt: 'prompt',
teamSkills: [],
disableTools: true,
providers: [
{
name: providerName,
config: { api: 'openai-responses', baseUrl, apiKey: 'TEST_RESPONSES_API_KEY' },
models: [
{
modelId,
name: 'Responses model',
config: { ...mockProviders[0].models[0].config, api: 'openai-responses' },
},
],
},
],
})
const configuredModels = openSpy.mock.lastCall?.[1].models
const models =
typeof configuredModels === 'function' ? configuredModels() : configuredModels
expect(models?.getModel(providerName, modelId)).toMatchObject({
api: 'openai-responses',
baseUrl,
})
await expect(models?.getAuth(providerName)).resolves.toMatchObject({
auth: { apiKey: 'test-responses-key' },
})
} finally {
openSpy.mockRestore()
vi.unstubAllEnvs()
}
},
)
it('should filter out denied tools from AgentHarness', async () => {
const team = await prisma.team.create({
data: { name: 'Test Team 3' },
@@ -512,7 +591,7 @@ describe('Sandbox Network isolation integration', () => {
allowedDomains: [],
providers: mockProviders,
})
const tools = harness.getTools()
const tools = await getAgentTools(harness)
const bashTool = tools.find((t) => t.name === 'bash')
expect(bashTool).toBeUndefined()
const readSkillTool = tools.find((t) => t.name === 'read_skill')
@@ -724,21 +803,20 @@ describe('createAgentSession bash restriction for non-owner users', () => {
it('should include the bash tool from the start for team owners', async () => {
const { harness } = await setupSession({ role: 'owner' })
expect(harness.getTools().some((t) => t.name === 'bash')).toBe(true)
expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(true)
})
it('should include the bash tool from the start when there is no user context', async () => {
const { harness } = await setupSession({ role: 'none' })
expect(harness.getTools().some((t) => t.name === 'bash')).toBe(true)
expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(true)
})
it('should treat a user who is not a team member as restricted (fail-closed)', async () => {
const { harness } = await setupSession({ role: 'non-member' })
const tools = harness.getTools()
const tools = await getAgentTools(harness)
expect(tools.some((t) => t.name === 'bash')).toBe(false)
expect(tools.some((t) => t.name === 'read_skill')).toBe(true)
// @ts-expect-error accessing private property for verification
const prompt = await harness.systemPrompt()
const prompt = await await getAgentPrompt(harness)
expect(prompt).toContain('# Restricted User Context')
})
@@ -746,7 +824,7 @@ describe('createAgentSession bash restriction for non-owner users', () => {
'should exclude the bash tool initially for %s users',
async (role) => {
const { harness } = await setupSession({ role })
const tools = harness.getTools()
const tools = await getAgentTools(harness)
expect(tools.some((t) => t.name === 'bash')).toBe(false)
expect(tools.some((t) => t.name === 'read_skill')).toBe(true)
},
@@ -785,23 +863,22 @@ describe('createAgentSession bash restriction for non-owner users', () => {
type: 'chat',
},
})
await prisma.agentSessionEntry.create({
data: {
id: 'restore-entry-1',
sessionId: session.id,
type: 'message',
data: {
message: {
await appendSessionEntries(session.id, [
{
kind: 'pi.tool-result',
model: [
{
role: 'toolResult',
toolCallId: 'loaded',
content: [{ type: 'text', text: 'skill content restored' }],
toolName: 'read_skill',
isError: false,
details: { skillId: 'previously-loaded-skill' },
timestamp: Date.now(),
},
},
],
},
})
])
const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue()
try {
@@ -817,7 +894,7 @@ describe('createAgentSession bash restriction for non-owner users', () => {
userId: user.id,
sessionId: session.id,
})
expect(harness.getTools().some((t) => t.name === 'bash')).toBe(true)
expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(true)
} finally {
initializeSpy.mockRestore()
}
@@ -837,17 +914,17 @@ describe('createAgentSession bash restriction for non-owner users', () => {
return ''
})
const readSkillTool = harness.getTools().find((t) => t.name === 'read_skill')
const readSkillTool = (await getAgentTools(harness)).find((t) => t.name === 'read_skill')
expect(readSkillTool).toBeDefined()
expect(harness.getTools().some((t) => t.name === 'bash')).toBe(false)
expect(harness.getActiveTools().some((t) => t.name === 'bash')).toBe(false)
expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(false)
expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(false)
await readSkillTool!.execute('1', { skillId: skill.id }, undefined, undefined, undefined)
await invokeTool(readSkillTool!, '1', { skillId: skill.id }, undefined, undefined)
expect(harness.getTools().some((t) => t.name === 'bash')).toBe(true)
expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(true)
// bash must be part of the ACTIVE tool set, not just the registry, or the model
// would never receive it on the next turn
expect(harness.getActiveTools().some((t) => t.name === 'bash')).toBe(true)
expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(true)
})
it('should not inject the bash tool for restricted users when bash is in deniedTools', async () => {
@@ -864,26 +941,24 @@ describe('createAgentSession bash restriction for non-owner users', () => {
return ''
})
const readSkillTool = harness.getTools().find((t) => t.name === 'read_skill')
const readSkillTool = (await getAgentTools(harness)).find((t) => t.name === 'read_skill')
expect(readSkillTool).toBeDefined()
await readSkillTool!.execute('1', { skillId: skill.id }, undefined, undefined, undefined)
await invokeTool(readSkillTool!, '1', { skillId: skill.id }, undefined, undefined)
expect(harness.getTools().some((t) => t.name === 'bash')).toBe(false)
expect((await getAgentTools(harness)).some((t) => t.name === 'bash')).toBe(false)
})
it('should include restricted user instructions in the system prompt for non-owners', async () => {
const { harness } = await setupSession({ role: 'editor' })
// @ts-expect-error accessing private property for verification
const prompt = await harness.systemPrompt()
const prompt = await await getAgentPrompt(harness)
expect(prompt).toContain('# Restricted User Context')
expect(prompt).toContain('source="user" will be rejected')
})
it('should not include restricted user instructions in the system prompt for owners', async () => {
const { harness } = await setupSession({ role: 'owner' })
// @ts-expect-error accessing private property for verification
const prompt = await harness.systemPrompt()
const prompt = await await getAgentPrompt(harness)
expect(prompt).not.toContain('# Restricted User Context')
})
})
@@ -982,7 +1057,7 @@ describe('createAgentSession typed metadata schema', () => {
it('should build create_file/create_version with the project CREATION_CONTEXT fields', async () => {
const { harness } = await setupSessionWithProject({ withCreationFields: true })
const tools = harness.getTools()
const tools = await getAgentTools(harness)
expect(tools.some((t) => t.name === 'list_autofill_fields')).toBe(false)
@@ -1018,8 +1093,8 @@ describe('createAgentSession typed metadata schema', () => {
it('should omit the metadata parameter when the project has no CREATION_CONTEXT fields', async () => {
const { harness } = await setupSessionWithProject({ withCreationFields: false })
const createFile = harness.getTools().find((t) => t.name === 'create_file')
const createVersion = harness.getTools().find((t) => t.name === 'create_version')
const createFile = (await getAgentTools(harness)).find((t) => t.name === 'create_file')
const createVersion = (await getAgentTools(harness)).find((t) => t.name === 'create_version')
expect(createFile).toBeDefined()
expect(createVersion).toBeDefined()
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- inspecting the runtime schema shape of the dynamically-built tool
@@ -1032,7 +1107,7 @@ describe('createAgentSession typed metadata schema', () => {
it('should include rename_asset and move_assets by default, but exclude delete_asset', async () => {
const { harness } = await setupSessionWithProject({ withCreationFields: false })
const toolNames = harness.getTools().map((t) => t.name)
const toolNames = (await getAgentTools(harness)).map((t) => t.name)
expect(toolNames).toContain('rename_asset')
expect(toolNames).toContain('move_assets')
@@ -1081,7 +1156,7 @@ describe('createAgentSession typed metadata schema', () => {
providers: mockProviders,
userId: user.id,
})
const toolNames = harness.getTools().map((t) => t.name)
const toolNames = (await getAgentTools(harness)).map((t) => t.name)
expect(toolNames).toContain('delete_asset')
} finally {
initializeSpy.mockRestore()
@@ -1151,13 +1226,12 @@ describe('createAgentSession enabled skill filtering', () => {
})
// The disabled skill must not be advertised in the available skills list
// @ts-expect-error accessing private property for verification
const prompt = await harness.systemPrompt()
const prompt = await await getAgentPrompt(harness)
expect(prompt).toContain(enabledSkill.id)
expect(prompt).not.toContain(disabledSkill.id)
// read_skill must reject the disabled skill id
const readSkillTool = harness.getTools().find((t) => t.name === 'read_skill')
const readSkillTool = (await getAgentTools(harness)).find((t) => t.name === 'read_skill')
expect(readSkillTool).toBeDefined()
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
@@ -1169,15 +1243,15 @@ describe('createAgentSession enabled skill filtering', () => {
})
await expect(
readSkillTool!.execute('1', { skillId: disabledSkill.id }, undefined, undefined, undefined),
invokeTool(readSkillTool!, '1', { skillId: disabledSkill.id }, undefined, undefined),
).rejects.toThrow('not enabled for this agent')
const result = await readSkillTool!.execute(
const result = await invokeTool(
readSkillTool!,
'1',
{ skillId: enabledSkill.id },
undefined,
undefined,
undefined,
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toBe('# Enabled Skill')
@@ -1223,11 +1297,11 @@ describe('createAgentSession enabled skill filtering', () => {
providers: mockProviders,
})
const readSkillTool = harness.getTools().find((t) => t.name === 'read_skill')
const readSkillTool = (await getAgentTools(harness)).find((t) => t.name === 'read_skill')
expect(readSkillTool).toBeDefined()
await expect(
readSkillTool!.execute('1', { skillId: skill.id }, undefined, undefined, undefined),
invokeTool(readSkillTool!, '1', { skillId: skill.id }, undefined, undefined),
).rejects.toThrow('not enabled for this agent')
} finally {
initializeSpy.mockRestore()
@@ -1283,26 +1357,26 @@ describe('createAgentSession enabled skill filtering', () => {
providers: mockProviders,
})
const readThreadTool = harness.getTools().find((t) => t.name === 'read_thread')
const readThreadTool = (await getAgentTools(harness)).find((t) => t.name === 'read_thread')
expect(readThreadTool).toBeDefined()
// First call executes and consumes quota
const res1 = await readThreadTool!.execute(
const res1 = await invokeTool(
readThreadTool!,
'call-1',
{ threadId: 'non-existent' },
undefined,
undefined,
undefined,
)
expect(res1).toBeDefined()
// Second call exceeds quota and returns error
const res2 = await readThreadTool!.execute(
const res2 = await invokeTool(
readThreadTool!,
'call-2',
{ threadId: 'non-existent' },
undefined,
undefined,
undefined,
)
expect(res2).toBeDefined()
const textContent = res2.content[0]
@@ -1393,7 +1467,7 @@ describe('createAgentSession media generation tools injection', () => {
providers: mockProviders,
})
const tools = harness.getTools()
const tools = await getAgentTools(harness)
expect(tools.find((t) => t.name === 'generate_image')).toBeUndefined()
expect(tools.find((t) => t.name === 'generate_video')).toBeUndefined()
} finally {
@@ -1467,7 +1541,7 @@ describe('createAgentSession media generation tools injection', () => {
providers: mockProviders,
})
const tools = harness.getTools()
const tools = await getAgentTools(harness)
expect(tools.find((t) => t.name === 'generate_image')).toBeDefined()
expect(tools.find((t) => t.name === 'generate_video')).toBeDefined()
} finally {
@@ -1545,7 +1619,7 @@ describe('createAgentSession media generation tools injection', () => {
providers: mockProviders,
})
const tools = harness.getTools()
const tools = await getAgentTools(harness)
expect(tools.find((t) => t.name === 'generate_image')).toBeUndefined()
expect(tools.find((t) => t.name === 'generate_video')).toBeDefined()
} finally {
+6 -597
View File
@@ -1,594 +1,3 @@
import { sandboxService } from '@shumai/core'
import {
AgentHarness,
Session,
type AgentTool,
type ThinkingLevel,
} from '@earendil-works/pi-agent-core'
import type { Api, Model } from '@earendil-works/pi-ai'
import { createModels, InMemoryCredentialStore } from '@earendil-works/pi-ai'
import { builtinProviders } from '@earendil-works/pi-ai/providers/all'
import { agentService } from '@shumai/core/src/agent/agent'
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
import { quotaService, QuotaExceededError } from '@shumai/core/src/quota/quota-service'
import { logger } from '@shumai/core/src/logger'
import { prisma } from '@shumai/db'
import { Type, type TSchema } from 'typebox'
import * as fs from 'fs'
import * as path from 'path'
import { DatabaseSessionStorage } from './database-session-storage'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { createReadSkillTool } from './tools/read-skill'
import { createReadThreadTool } from './tools/read-thread'
import { createSandboxedBashTool } from './tools/sandboxed-bash'
import { createGenerateImageTool } from './tools/generate-image'
import { createGenerateVideoTool } from './tools/generate-video'
import { buildOperationTools } from './operation-tools'
import { createAutofillReadAssetTool } from './operation-extensions'
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
import { serializeContextToXml } from './context/serialize-context'
import { DEFAULT_DENIED_TOOLS, type ShumaiMessageContext } from '@shumai/dtos'
export interface DbModelInfo {
modelId: string
name: string | null
config: PrismaJson.ModelConfig
}
export interface DbProviderInfo {
name: string
config: PrismaJson.ProviderConfig
models: DbModelInfo[]
}
export function getModelFromDb(providers: DbProviderInfo[], providerName: string, modelId: string) {
const dbProvider = providers.find((p) => p.name === providerName)
const dbModel = dbProvider?.models.find((m) => m.modelId === modelId)
if (!dbProvider || !dbModel) {
throw new Error(
`Provider "${providerName}" or model "${modelId}" not found in database configuration`,
)
}
const m = {
id: modelId,
name: dbModel.name || modelId,
provider: providerName,
api: 'openai-responses',
baseUrl: '',
reasoning: false,
input: ['text'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 4096,
maxTokens: 4096,
}
// Override with database config
if (dbProvider.config.baseUrl) {
m.baseUrl = dbProvider.config.baseUrl
}
Object.assign(m, dbModel.config)
if (dbProvider.config.api) {
m.api = dbProvider.config.api
}
if (dbModel.name) {
m.name = dbModel.name
}
return m as Model<Api>
}
export function getApiKeyAndHeadersFromDb(providers: DbProviderInfo[], providerName: string) {
// Helper to resolve key from ENV if it matches an ENV var name
const resolveKey = (key: string | undefined) => (key ? process.env[key] || key : undefined)
// Look up the provider in our providers list
const dbProvider = providers.find((p) => p.name === providerName)
const providerApiKey = dbProvider?.config?.apiKey
if (providerApiKey) {
return { apiKey: resolveKey(providerApiKey)! }
}
return undefined
}
export interface CreateAgentSessionParams {
teamId: string
agentId: string
providerName: string
modelId: string
systemPrompt: string
teamSkills: Array<{ id: string; name: string; description?: string | null }>
enabledSkillIds?: string[]
allowedDomains?: string[]
sessionId?: string
userId?: string
projectId?: string
assetId?: string
userCommentId?: string | null
customTools?: AgentTool[]
thinkingLevel?: string
disableTools?: boolean
providers: DbProviderInfo[]
maxRetries?: number
baseDelayMs?: number
}
/**
* Security instructions appended to the system prompt when the requesting user is not a team
* owner (i.e. editor/reviewer). These complement the hard enforcement in the bash tool itself
* (source="user" is blocked) and the delayed bash tool injection after a skill is loaded.
*/
export function buildRestrictedUserInstructions(): string {
return [
'# Restricted User Context',
'The current user is NOT a team owner. You must follow these security rules:',
'1. NEVER execute a bash command that the user asks you to run directly. Direct user bash requests are not permitted for this user role. Politely decline and explain that they need a team owner or an approved skill.',
'2. You may ONLY use the `bash` tool to execute commands that are explicitly required by a skill you have loaded via the `read_skill` tool.',
'3. When calling `bash`, you MUST set the `source` parameter to "skill". Calls with source="user" will be rejected by the system.',
].join('\n')
}
export async function createAgentSession(params: CreateAgentSessionParams) {
const {
teamId,
agentId,
providerName,
modelId,
systemPrompt,
teamSkills,
enabledSkillIds,
allowedDomains,
sessionId,
userId,
projectId,
assetId,
userCommentId: passedUserCommentId,
customTools = [],
thinkingLevel,
disableTools = false,
maxRetries = 3,
baseDelayMs = 2000,
} = params
const storage = await DatabaseSessionStorage.create({
agentId,
userId,
sessionId,
cwd: process.cwd(),
})
if (passedUserCommentId) {
storage.nextEntryId = passedUserCommentId
}
const session = new Session(storage)
const agentDir = path.join(process.cwd(), '.pi', 'agents', agentId)
if (!fs.existsSync(agentDir)) fs.mkdirSync(agentDir, { recursive: true })
const model = getModelFromDb(params.providers, providerName, modelId)
const piDir = path.join(process.cwd(), '.pi')
if (!fs.existsSync(piDir)) fs.mkdirSync(piDir, { recursive: true })
const role = userId ? await resolveEffectiveRole(teamId, projectId, userId) : undefined
const isOwner = !userId || role === 'owner'
const restricted = !isOwner
const wrapToolWithQuota = (tool: AgentTool): AgentTool => {
const originalExecute = tool.execute
return {
...tool,
execute: async (toolCallId, args, signal, onUpdate) => {
try {
await quotaService.checkQuota(
{
teamId,
userId,
role,
resource: 'agent_tool_call_count',
resourceData: { name: tool.name, toolName: tool.name },
},
1,
)
} catch (err) {
if (err instanceof QuotaExceededError) {
return {
content: [{ type: 'text', text: `Quota exceeded: ${err.message}` }],
details: { error: err.message },
}
}
throw err
}
const result = await originalExecute(toolCallId, args, signal, onUpdate)
try {
await quotaService.consumeQuota(
{
teamId,
userId,
role,
resource: 'agent_tool_call_count',
resourceData: { name: tool.name, toolName: tool.name },
},
1,
)
} catch (err) {
logger.error({ err }, 'Failed to record quota usage for agent tool call')
}
return result
},
}
}
if (allowedDomains !== undefined) {
await sandboxService.syncAllowedDomains(allowedDomains, teamId)
}
const skillEnvs: Record<string, string> = {}
const onEnvsAdded = (envs: Record<string, string>) => {
Object.assign(skillEnvs, envs)
}
// Restore env variables from previously loaded skills in this session
let skillLoadedInSession = false
if (sessionId) {
try {
const entries = await storage.getEntries()
for (const entry of entries) {
if (
entry.type === 'message' &&
entry.message &&
entry.message.role === 'toolResult' &&
entry.message.toolName === 'read_skill' &&
!entry.message.isError
) {
const details = entry.message.details as { skillId?: string } | undefined
if (details?.skillId) {
skillLoadedInSession = true
const envs = await agentService.getSkillEnvs(details.skillId)
onEnvsAdded(envs)
}
}
}
} catch (err) {
console.error('Failed to restore skill environment variables:', err)
}
}
const agent = await prisma.agent.findUnique({
where: { id: agentId },
})
const agentConfig = agent?.config as PrismaJson.AgentConfig | null | undefined
const deniedTools = agentConfig?.deniedTools ?? [...DEFAULT_DENIED_TOOLS]
const mediaTools: AgentTool[] = []
// Agents acting for a user get read_asset / get_asset_render from the Operation registry
// (see systemTools below); the autofill system agent has its own team-scoped read_asset.
if (!userId && agent?.type === 'autofill' && assetId) {
mediaTools.push(
createAutofillReadAssetTool({
teamId,
targetAssetId: assetId,
}),
)
}
if (!deniedTools.includes('generate_image') || !deniedTools.includes('generate_video')) {
try {
const { imageModels, videoModels, providerKeys } =
await mediaGenerationService.getValidModels(teamId)
if (imageModels.length > 0 && !deniedTools.includes('generate_image')) {
mediaTools.push(createGenerateImageTool(imageModels, providerKeys, userId))
}
if (videoModels.length > 0 && !deniedTools.includes('generate_video')) {
mediaTools.push(createGenerateVideoTool(videoModels, providerKeys, userId))
}
} catch (err) {
logger.error({ err, teamId }, 'Failed to initialize media generation tools')
}
}
const sandboxedBash = createSandboxedBashTool(process.cwd(), skillEnvs, {
teamId,
userId,
role,
getBlockedHost: (commandId?: string) => sandboxService.getBlockedHost(commandId),
clearBlockedHost: () => {
sandboxService.clearBlockedHost()
},
// Non-owner users can only run bash commands required by a loaded skill
restrictedUser: restricted,
})
// For non-owner users, the bash tool is not injected initially. It becomes available
// only after a skill is successfully loaded via the read_skill tool (or immediately when
// a skill was already loaded earlier in this session).
let harness: AgentHarness | undefined = undefined
const bashIncludedFromStart = isOwner || skillLoadedInSession
let bashInjected = bashIncludedFromStart
const onSkillLoaded = async () => {
if (!harness || bashInjected || deniedTools.includes('bash')) return
if (harness.getTools().some((t) => t.name === 'bash')) return
bashInjected = true
// Pass the full post-update tool list as activeToolNames: setTools only updates the
// registry otherwise, and the model would never see the bash tool on the next turn.
const next = [...harness.getTools(), wrapToolWithQuota(sandboxedBash)]
await harness.setTools(
next,
next.map((t) => t.name),
)
}
const readSkill = createReadSkillTool(
userId,
onEnvsAdded,
restricted ? onSkillLoaded : undefined,
enabledSkillIds,
projectId,
)
const systemTools: AgentTool[] = []
if (userId) {
const creationMetadataSchema = await buildProjectMetadataSchema(projectId)
systemTools.push(
// Shared Operations (also exposed via MCP and the CLI): browsing, searching, organizing,
// reading and downloading assets, creating files and versions, comments and metadata
...buildOperationTools({ userId, agentId, teamId, projectId }, { creationMetadataSchema }),
)
}
const readThread = createReadThreadTool({ userId, teamId })
const rawTools = [
...mediaTools,
readSkill,
readThread,
...(bashIncludedFromStart ? [sandboxedBash] : []),
...systemTools,
...customTools,
]
const allTools = rawTools.map((tool) => wrapToolWithQuota(tool))
const enabledTools = disableTools
? []
: allTools.filter((tool) => !deniedTools.includes(tool.name))
const credentials = new InMemoryCredentialStore()
const resolveKey = (key: string | undefined) => (key ? process.env[key] || key : undefined)
for (const p of params.providers) {
const apiKey = resolveKey(p.config?.apiKey)
if (apiKey) {
await credentials.modify(p.name, async () => ({ type: 'api_key' as const, key: apiKey }))
}
}
const modelsStore = createModels({ credentials })
for (const provider of builtinProviders()) {
modelsStore.setProvider(provider)
}
harness = new AgentHarness({
session,
models: modelsStore,
model,
thinkingLevel: (thinkingLevel || 'off') as ThinkingLevel,
streamOptions: {
maxRetries,
maxRetryDelayMs: baseDelayMs,
},
systemPrompt: async () => {
let prompt = systemPrompt
if (disableTools) {
return prompt
}
if (restricted) {
prompt += `\n\n${buildRestrictedUserInstructions()}`
}
// Sandbox environment restrictions
prompt +=
'\n\n' +
[
'# Sandbox Environment Restrictions',
'Your shell environment (the `bash` tool) is highly sandboxed to protect the host system:',
'1. **Filesystem Isolation**: You only have read and write permissions to the `.pi` folder in the project root directory.',
'2. **Read/Write Restrictions**: All reading and writing to directories outside `.pi` (e.g. your home directory `~/`, `/tmp`, `/etc`, or the rest of the workspace) are strictly denied by the sandbox security policy.',
"3. **Avoid System Temp Directory Writes**: You must strictly avoid any commands or shell constructs that attempt to write to the system temporary directory `/tmp` or `/var/tmp`. For example, do not use Bash here documents (`<<EOF` or `<<'EOF'`) in your commands, as the bash shell internally implements here documents by writing temporary files to `/tmp`. If you need to create a file or write content, write it directly using file creation tools or write to files located inside the `.pi` directory without utilizing here documents.",
'4. **Temporary File Cleanup**: If you download workspace assets to `.pi` using the `download_asset` tool for local processing or script execution, you MUST delete the temporary downloaded files from `.pi` after finishing your task.',
].join('\n')
if (teamSkills.length > 0) {
prompt += formatSkillsForPrompt(teamSkills)
}
return prompt
},
tools: enabledTools,
})
harness.on('context', async ({ messages }) => {
return {
messages: messages.map((msg) => {
if (
msg.role === 'custom' &&
msg.customType === 'shumai_message' &&
msg.details &&
typeof msg.details === 'object'
) {
const context = msg.details as ShumaiMessageContext
const xml = serializeContextToXml(context)
const text = typeof msg.content === 'string' ? msg.content : ''
const fullContent = xml ? `${text}\n\n${xml}`.trim() : text
return {
...msg,
content: fullContent,
}
}
return msg
}),
}
})
return { session, harness }
}
export interface AutofillField {
id: string
config: PrismaJson.FieldConfig
description?: string | null
}
export function fieldsToTypeBoxSchema(fields: AutofillField[]) {
const newOptionSchema = Type.Object(
{
newOption: Type.Object(
{
value: Type.String({
minLength: 1,
description:
'The new option display name/value to create and select if none of the existing options match.',
}),
},
{ additionalProperties: false },
),
},
{ additionalProperties: false },
)
const properties: Record<string, TSchema> = {}
for (const f of fields) {
let schema: TSchema
const fieldName = f.config.name
const fieldDesc = f.description || fieldName
const baseDescription = `The field '${fieldName}' represents ${fieldDesc}.`
switch (f.config.type) {
case 'text':
case 'longText':
schema = Type.String({ description: baseDescription })
break
case 'number':
case 'rating':
schema = Type.Number({ description: baseDescription })
break
case 'toggle':
schema = Type.Boolean({ description: baseDescription })
break
case 'select': {
const options = f.config.select?.options || []
const description =
options.length > 0
? `${baseDescription}\nSelect one existing option ID or provide {"newOption": {"value": "..."}} to create a new option.\n\nAvailable options:\n${options.map((o) => `- ${o.displayName} => ${o.id}`).join('\n')}`
: `${baseDescription}\nProvide {"newOption": {"value": "..."}} with the desired option name.`
if (options.length > 0) {
schema = Type.Union(
[
Type.String({
enum: options.map((o) => o.id),
}),
newOptionSchema,
],
{ description },
)
} else {
schema = Type.Object(newOptionSchema.properties, {
additionalProperties: false,
description,
})
}
break
}
case 'selectMulti': {
const options = f.config.selectMulti?.options || []
const description =
options.length > 0
? `${baseDescription}\nSelect applicable option IDs or provide {"newOption": {"value": "..."}} objects for new options (e.g. ["opt1", {"newOption": {"value": "new_name"}}]).\n\nAvailable options:\n${options.map((o) => `- ${o.displayName} => ${o.id}`).join('\n')}`
: `${baseDescription}\nProvide an array of {"newOption": {"value": "..."}} objects for new options.`
const itemSchema =
options.length > 0
? Type.Union([
Type.String({
enum: options.map((o) => o.id),
}),
newOptionSchema,
])
: newOptionSchema
schema = Type.Array(itemSchema, { description })
break
}
default:
schema = Type.String({ description: baseDescription })
}
// Every field is required but nullable: the agent must return each field key,
// using `null` for values it does not know. Nulls are skipped when persisting.
// This matches the OpenAI structured-outputs strict-mode convention (all
// properties required, optionality expressed via `null`).
properties[f.id] = Type.Union([schema, Type.Null()])
}
return Type.Object(properties, { additionalProperties: false })
}
/**
* Builds the strict, all-optional metadata schema for the project's CREATION_CONTEXT
* fields (the same field set the agent may attach when creating files/versions).
* Returns undefined when no project is known or the project defines no fields, in
* which case the `metadata` parameter is omitted from the tools entirely.
*/
async function buildProjectMetadataSchema(projectId?: string): Promise<TSchema | undefined> {
if (!projectId) return undefined
const fields = await metadataService.listProjectFields('', projectId)
const creationFields: AutofillField[] = []
for (const f of fields) {
const config = f.field.config
if (!config || config.autofillSource !== 'CREATION_CONTEXT') continue
creationFields.push({
id: f.field.key,
config,
description: f.field.description,
})
}
if (creationFields.length === 0) return undefined
return fieldsToTypeBoxSchema(creationFields)
}
function escapeXml(str: string): string {
return str
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;')
}
export function formatSkillsForPrompt(
skills: Array<{ id: string; name: string; description?: string | null }>,
): string {
if (skills.length === 0) {
return ''
}
const lines = [
'\n\nThe following skills provide specialized instructions for specific tasks.',
"Use the read_skill tool to load a skill's file when the task matches its description.",
'When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.',
'',
'<available_skills>',
]
for (const skill of skills) {
const filePath = path.join(process.cwd(), '.pi', 'skills', skill.id, 'SKILL.md')
lines.push(' <skill>')
lines.push(` <id>${escapeXml(skill.id)}</id>`)
lines.push(` <name>${escapeXml(skill.name)}</name>`)
lines.push(` <description>${escapeXml(skill.description || 'No description')}</description>`)
lines.push(` <location>${escapeXml(filePath)}</location>`)
lines.push(' </skill>')
}
lines.push('</available_skills>')
return lines.join('\n')
}
import { WorkflowTaskType } from '@shumai/db'
import { registerWorkflow } from '@shumai/workflow-core'
import { agentAutofillMedia } from './workflows/agent-autofill'
@@ -603,22 +12,22 @@ export function initAgentWorkflows() {
export * from './activities/agent'
export {
deleteAssetEmbeddingsActivity,
extractAiMetadataActivity,
generateImageEmbeddingActivity,
generateTextEmbeddingActivity,
generateVideoChunkEmbeddingActivity,
saveAssetEmbeddingsActivity,
deleteAssetEmbeddingsActivity,
type ExistingAssetEmbeddingInfo,
type ExtractAiMetadataParams,
type GeneratedEmbedding,
type GenerateTextEmbeddingParams,
type ExistingAssetEmbeddingInfo,
} from './activities/ai'
export * from './database-session-storage'
export * from './context/serialize-context'
export * from './operation-tools'
export * from './runtime'
export * from './tools/generate-image'
export * from './tools/generate-video'
export * from './workflows/agent-autofill'
export * from './workflows/agent-chat'
export * from './workflows/agent-embedding'
export * from './tools/generate-image'
export * from './tools/generate-video'
export * from './operation-tools'
@@ -1,10 +1,11 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import * as fs from 'fs'
import * as path from 'path'
import { prisma, type Asset, type StorageKey } from '@shumai/db'
import { s3Service } from '@shumai/core/src/s3/s3'
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { authzService } from '@shumai/core/src/authz/authz'
import { getOperation } from '@shumai/core/src/operations'
import { s3Service } from '@shumai/core/src/s3/s3'
import { prisma, type Asset, type StorageKey } from '@shumai/db'
import * as fs from 'fs'
import * as path from 'path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { toAgentTool } from '../operation-tools'
import './download-asset'
@@ -96,7 +97,7 @@ describe('download_asset agent tool', () => {
mockAssets(photo)
mockStorage('image/webp', 'proxy-bytes')
const result = await downloadTool().execute('call-1', { assetIds: ['img-1'] })
const result = await invokeTool(downloadTool(), 'call-1', { assetIds: ['img-1'] })
const expectedPath = path.join(piDir, 'img-1_sample_photo.webp')
created.push(expectedPath)
@@ -130,7 +131,7 @@ describe('download_asset agent tool', () => {
mockAssets(photo)
mockStorage('image/jpeg')
await downloadTool().execute('call-1', { assetIds: ['img-1'], proxy: false })
await invokeTool(downloadTool(), 'call-1', { assetIds: ['img-1'], proxy: false })
const expectedPath = path.join(piDir, 'img-1_sample_photo.jpg')
created.push(expectedPath)
@@ -153,7 +154,7 @@ describe('download_asset agent tool', () => {
} as unknown as Asset)
mockStorage('image/webp')
const result = await downloadTool().execute('call-1', {
const result = await invokeTool(downloadTool(), 'call-1', {
assetIds: ['img-1', 'stack-1'],
key: null,
})
@@ -173,7 +174,7 @@ describe('download_asset agent tool', () => {
it('rejects folders', async () => {
mockAssets({ id: 'folder-1', name: 'Renders', type: 'folder', isDeleted: false })
await expect(downloadTool().execute('call-1', { assetIds: ['folder-1'] })).rejects.toThrow(
await expect(invokeTool(downloadTool(), 'call-1', { assetIds: ['folder-1'] })).rejects.toThrow(
'Asset folder-1 ("Renders") is a folder. Download the files inside it instead.',
)
expect(s3Service.downloadToFile).not.toHaveBeenCalled()
@@ -185,36 +186,36 @@ describe('download_asset agent tool', () => {
if (id === 'secret') throw new Error('Forbidden')
})
await expect(
downloadTool().execute('call-1', { assetIds: ['img-1', 'secret'] }),
invokeTool(downloadTool(), 'call-1', { assetIds: ['img-1', 'secret'] }),
).rejects.toThrow('Forbidden')
expect(s3Service.downloadToFile).not.toHaveBeenCalled()
})
it('requires assetIds or key', async () => {
await expect(downloadTool().execute('call-1', { assetIds: null, key: null })).rejects.toThrow(
'Invalid input for download_asset',
)
await expect(
invokeTool(downloadTool(), 'call-1', { assetIds: null, key: null }),
).rejects.toThrow('Invalid input for download_asset')
})
it('rejects assetIds and key together', async () => {
await expect(
downloadTool().execute('call-1', { assetIds: ['img-1'], key: 'files/img-1/a.webp' }),
invokeTool(downloadTool(), 'call-1', { assetIds: ['img-1'], key: 'files/img-1/a.webp' }),
).rejects.toThrow('Provide either "assetIds" or "key", not both.')
})
describe('by storage key', () => {
it('requires a user', async () => {
await expect(
downloadTool('').execute('call-1', { key: 'files/ast-1/shot.webp' }),
invokeTool(downloadTool(''), 'call-1', { key: 'files/ast-1/shot.webp' }),
).rejects.toThrow('User ID is required for authorization.')
})
it('rejects keys outside files/ and path traversal', async () => {
await expect(downloadTool().execute('call-1', { key: 'avatars/user-1.png' })).rejects.toThrow(
'Invalid storage key format: key must start with "files/"',
)
await expect(
downloadTool().execute('call-1', { key: 'files/../../etc/passwd' }),
invokeTool(downloadTool(), 'call-1', { key: 'avatars/user-1.png' }),
).rejects.toThrow('Invalid storage key format: key must start with "files/"')
await expect(
invokeTool(downloadTool(), 'call-1', { key: 'files/../../etc/passwd' }),
).rejects.toThrow('cannot contain ".."')
})
@@ -223,7 +224,7 @@ describe('download_asset agent tool', () => {
vi.mocked(prisma.storageKey.findFirst).mockResolvedValue(null)
vi.mocked(prisma.storageKey.findUnique).mockResolvedValue(null)
await expect(
downloadTool().execute('call-1', { key: 'files/nope/shot.webp' }),
invokeTool(downloadTool(), 'call-1', { key: 'files/nope/shot.webp' }),
).rejects.toThrow('does not belong to any valid asset or the asset has been deleted')
})
@@ -231,7 +232,7 @@ describe('download_asset agent tool', () => {
mockAssets({ id: 'other-project-asset' })
vi.mocked(authzService.hasPermission).mockRejectedValue(new Error('Forbidden'))
await expect(
downloadTool().execute('call-1', { key: 'files/other-project-asset/shots/a.webp' }),
invokeTool(downloadTool(), 'call-1', { key: 'files/other-project-asset/shots/a.webp' }),
).rejects.toThrow('Forbidden')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
@@ -246,7 +247,7 @@ describe('download_asset agent tool', () => {
mockAssets({ id: 'ast-123' })
mockStorage('image/webp', 'frame-bytes')
const result = await downloadTool().execute('call-1', {
const result = await invokeTool(downloadTool(), 'call-1', {
key: 'files/ast-123/screenshots/shot_5.0s.webp',
})
@@ -279,7 +280,7 @@ describe('download_asset agent tool', () => {
await fs.promises.writeFile(dest, pngHeader)
})
const result = await downloadTool().execute('call-1', {
const result = await invokeTool(downloadTool(), 'call-1', {
key: 'files/upload-ulid-456/photo.png',
})
@@ -1,17 +1,17 @@
import type { ToolExecutionResult as AgentToolResult } from '@earendil-works/pi-durable'
import { storageBucket } from '@shumai/core/src/asset-read'
import { assertStorageKeyNotArchived } from '@shumai/core/src/asset/asset-archive'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { s3Service } from '@shumai/core/src/s3/s3'
import { readFileMimeType } from '@shumai/core/src/utils/file-mime'
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
import type { User } from '@shumai/db'
import { downloadAsset, MAX_DOWNLOAD_ASSETS, type DownloadAssetOutput } from '@shumai/operations'
import * as fs from 'fs'
import * as path from 'path'
import { z } from 'zod'
import type { AgentToolResult } from '@earendil-works/pi-agent-core'
import { downloadAsset, MAX_DOWNLOAD_ASSETS, type DownloadAssetOutput } from '@shumai/operations'
import type { User } from '@shumai/db'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { assertStorageKeyNotArchived } from '@shumai/core/src/asset/asset-archive'
import { storageBucket } from '@shumai/core/src/asset-read'
import { s3Service } from '@shumai/core/src/s3/s3'
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
import { readFileMimeType } from '@shumai/core/src/utils/file-mime'
import { resolveAssetIdFromKey } from '../tools/download-asset'
import { registerAgentToolExtension, type AgentToolExtension } from '../operation-tools'
import { resolveAssetIdFromKey } from '../tools/download-asset'
const CLEANUP_REMINDER = 'Remember to delete these temporary files when finished.'
@@ -47,7 +47,7 @@ async function saveToSandbox(key: string, filename: string) {
}
/** Downloads one storage key (e.g. a frame from read_asset) after checking Read on its asset. */
async function downloadKey(key: string, userId: string): Promise<AgentToolResult<unknown>> {
async function downloadKey(key: string, userId: string): Promise<AgentToolResult> {
const owningAssetId = await resolveAssetIdFromKey(key)
await authzService.hasPermission({
user: { id: userId } as User,
@@ -59,7 +59,7 @@ async function downloadKey(key: string, userId: string): Promise<AgentToolResult
const filename = sanitizeFilename(path.basename(key)) || 'downloaded_file'
const saved = await saveToSandbox(key, filename)
return {
content: [
output: [
{
type: 'text',
text: `Downloaded storage key "${key}" to "${saved.filePath}". Remember to delete this temporary file when finished.`,
@@ -70,9 +70,7 @@ async function downloadKey(key: string, userId: string): Promise<AgentToolResult
}
/** Saves each file of a download_asset result into the sandbox. */
export async function presentDownloadOutput(
output: DownloadAssetOutput,
): Promise<AgentToolResult<unknown>> {
export async function presentDownloadOutput(output: DownloadAssetOutput): Promise<AgentToolResult> {
const lines: string[] = []
const files = []
for (const file of output.files) {
@@ -87,7 +85,7 @@ export async function presentDownloadOutput(
files.push({ assetId: file.assetId, name: file.name, kind: file.kind, ...saved })
}
lines.push(CLEANUP_REMINDER)
return { content: [{ type: 'text', text: lines.join('\n') }], details: { files } }
return { output: [{ type: 'text', text: lines.join('\n') }], details: { files } }
}
const downloadAssetExtension: AgentToolExtension = {
@@ -1,17 +1,18 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { resolveAnnotationsById } from '@shumai/core/src/asset-read/annotations'
import { authzService } from '@shumai/core/src/authz/authz'
import { getOperation } from '@shumai/core/src/operations'
import { s3Service } from '@shumai/core/src/s3/s3'
import { degreeToSecond } from '@shumai/core/src/utils/model3d'
import {
prisma,
WorkflowTaskType,
WorkflowTaskStatus,
WorkflowTaskType,
type Asset,
type WorkflowTask,
} from '@shumai/db'
import { s3Service } from '@shumai/core/src/s3/s3'
import { workflowService } from '@shumai/workflow-core'
import { authzService } from '@shumai/core/src/authz/authz'
import { resolveAnnotationsById } from '@shumai/core/src/asset-read/annotations'
import { getOperation } from '@shumai/core/src/operations'
import { degreeToSecond } from '@shumai/core/src/utils/model3d'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { toAgentTool } from '../operation-tools'
import { createAutofillReadAssetTool } from './read-asset'
@@ -90,7 +91,7 @@ type Details = {
taskId?: string
isTruncated?: boolean
}
function details(result: { details: unknown }): Details {
function details(result: { details?: unknown }): Details {
return result.details as Details
}
@@ -212,7 +213,7 @@ describe('read_asset agent tool', () => {
})
it('throws an authorization error if the user ID is empty', async () => {
await expect(readAssetTool('').execute('call-1', { assetId: 'asset-1' })).rejects.toThrow(
await expect(invokeTool(readAssetTool(''), 'call-1', { assetId: 'asset-1' })).rejects.toThrow(
'User ID is required for authorization.',
)
})
@@ -220,7 +221,7 @@ describe('read_asset agent tool', () => {
it('throws if the asset is not found', async () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue(null)
await expect(
readAssetTool().execute('call-1', {
invokeTool(readAssetTool(), 'call-1', {
assetId: 'asset-1',
annotationId: null,
imageConfig: null,
@@ -233,7 +234,7 @@ describe('read_asset agent tool', () => {
it('does not plan or render anything when Read is denied', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValue(new Error('Forbidden'))
await expect(
readAssetTool().execute('call-1', {
invokeTool(readAssetTool(), 'call-1', {
assetId: 'vid-1',
videoConfig: { start: 0, end: 1, count: 1 },
}),
@@ -244,7 +245,7 @@ describe('read_asset agent tool', () => {
it('rejects unsupported asset types', async () => {
mockAsset({ id: 'zip-1', name: 'bundle.zip', mediaType: 'application/zip', media: null })
await expect(readAssetTool().execute('call-1', { assetId: 'zip-1' })).rejects.toThrow(
await expect(invokeTool(readAssetTool(), 'call-1', { assetId: 'zip-1' })).rejects.toThrow(
'Unsupported asset type for read_asset. Asset zip-1 has media type "application/zip".',
)
})
@@ -254,7 +255,7 @@ describe('read_asset agent tool', () => {
mockAsset(imageAsset)
mockObjects()
const result = await readAssetTool().execute('call-1', {
const result = await invokeTool(readAssetTool(), 'call-1', {
assetId: 'img-1',
annotationId: null,
imageConfig: null,
@@ -289,14 +290,17 @@ describe('read_asset agent tool', () => {
it('ignores an empty imageConfig', async () => {
mockAsset(imageAsset)
mockObjects()
const result = await readAssetTool().execute('call-1', { assetId: 'img-1', imageConfig: {} })
const result = await invokeTool(readAssetTool(), 'call-1', {
assetId: 'img-1',
imageConfig: {},
})
expect(details(result).key).toBe('proxy/photo.webp')
})
it('rejects a config meant for another asset type', async () => {
mockAsset(imageAsset)
await expect(
readAssetTool().execute('call-1', {
invokeTool(readAssetTool(), 'call-1', {
assetId: 'img-1',
docConfig: { mode: 'pages', startPage: 1, endPage: 1 },
}),
@@ -312,7 +316,7 @@ describe('read_asset agent tool', () => {
mockTaskFinished('task-anno', { key: 'annotated/photo.webp' })
mockObjects()
const result = await readAssetTool().execute('call-1', {
const result = await invokeTool(readAssetTool(), 'call-1', {
assetId: 'img-1',
annotationId: 'comment-1',
})
@@ -348,7 +352,7 @@ describe('read_asset agent tool', () => {
mockAsset(modelAsset)
mockObjects()
const result = await readAssetTool().execute('call-3d', { assetId: 'model-1' })
const result = await invokeTool(readAssetTool(), 'call-3d', { assetId: 'model-1' })
expect(s3Service.getObject).toHaveBeenCalledWith('shumai', 'proxy/views.webp')
const text = textOf(result)
@@ -367,7 +371,7 @@ describe('read_asset agent tool', () => {
it('supports s3KeyOnly for 3D assets', async () => {
mockAsset(modelAsset)
const result = await readAssetTool().execute('call-3d-s3', {
const result = await invokeTool(readAssetTool(), 'call-3d-s3', {
assetId: 'model-1',
s3KeyOnly: true,
})
@@ -381,7 +385,7 @@ describe('read_asset agent tool', () => {
it('rejects videoConfig for 3D assets', async () => {
mockAsset(modelAsset)
await expect(
readAssetTool().execute('call-3d-err', {
invokeTool(readAssetTool(), 'call-3d-err', {
assetId: 'model-1',
videoConfig: { start: 0, end: 4, count: 4 },
}),
@@ -392,9 +396,9 @@ describe('read_asset agent tool', () => {
it('throws if the 4-views image is missing when the overview is requested', async () => {
mockAsset({ ...modelAsset, media: { proxyType: '3d', imageTranscodes: [] } })
await expect(readAssetTool().execute('call-3d-err2', { assetId: 'model-1' })).rejects.toThrow(
'4-views image (views.webp) is missing',
)
await expect(
invokeTool(readAssetTool(), 'call-3d-err2', { assetId: 'model-1' }),
).rejects.toThrow('4-views image (views.webp) is missing')
})
it('renders a turntable frame when config3d.degree is provided', async () => {
@@ -405,7 +409,7 @@ describe('read_asset agent tool', () => {
})
mockObjects()
const result = await readAssetTool().execute('call-3d-degree', {
const result = await invokeTool(readAssetTool(), 'call-3d-degree', {
assetId: 'model-1',
config3d: { degree: 45 },
})
@@ -446,10 +450,10 @@ describe('read_asset agent tool', () => {
mockAsset(modelAsset)
const tool = readAssetTool()
await expect(
tool.execute('call-1', { assetId: 'model-1', config3d: { degree: 40 } }),
invokeTool(tool, 'call-1', { assetId: 'model-1', config3d: { degree: 40 } }),
).rejects.toThrow('Invalid turntable degree: 40')
await expect(
tool.execute('call-2', { assetId: 'model-1', config3d: { degree: 360 } }),
invokeTool(tool, 'call-2', { assetId: 'model-1', config3d: { degree: 360 } }),
).rejects.toThrow('Invalid turntable degree: 360')
expect(resolveAnnotationsById).not.toHaveBeenCalled()
})
@@ -463,7 +467,7 @@ describe('read_asset agent tool', () => {
})
mockObjects()
const result = await readAssetTool().execute('call-3d-ann', {
const result = await invokeTool(readAssetTool(), 'call-3d-ann', {
assetId: 'model-1',
annotationId: 'comm-1',
config3d: null,
@@ -500,7 +504,7 @@ describe('read_asset agent tool', () => {
})
mockObjects()
const result = await readAssetTool().execute('call-3d-session-ann', {
const result = await invokeTool(readAssetTool(), 'call-3d-session-ann', {
assetId: 'model-1',
annotationId: 'session-entry-1',
})
@@ -524,7 +528,7 @@ describe('read_asset agent tool', () => {
mockAsset(modelAsset)
vi.mocked(resolveAnnotationsById).mockResolvedValue({ annotations: arrow, timestamp: 0.5 })
await expect(
readAssetTool().execute('call-3d-conflict', {
invokeTool(readAssetTool(), 'call-3d-conflict', {
assetId: 'model-1',
annotationId: 'comm-1',
config3d: { degree: 90 },
@@ -538,7 +542,7 @@ describe('read_asset agent tool', () => {
it('throws if the turntable video is missing when an angle is requested', async () => {
mockAsset({ ...modelAsset, media: { proxyType: '3d', videoTranscodes: [] } })
await expect(
readAssetTool().execute('call-1', { assetId: 'model-1', config3d: { degree: 45 } }),
invokeTool(readAssetTool(), 'call-1', { assetId: 'model-1', config3d: { degree: 45 } }),
).rejects.toThrow('turntable video (turntable.mp4) is missing')
})
})
@@ -546,7 +550,7 @@ describe('read_asset agent tool', () => {
describe('Video Assets', () => {
it('requires videoConfig', async () => {
mockAsset(videoAsset)
await expect(readAssetTool().execute('call-1', { assetId: 'vid-1' })).rejects.toThrow(
await expect(invokeTool(readAssetTool(), 'call-1', { assetId: 'vid-1' })).rejects.toThrow(
'videoConfig with start, end, and count is required',
)
})
@@ -554,7 +558,7 @@ describe('read_asset agent tool', () => {
it('rejects an invalid time range', async () => {
mockAsset(videoAsset)
await expect(
readAssetTool().execute('call-1', {
invokeTool(readAssetTool(), 'call-1', {
assetId: 'vid-1',
videoConfig: { start: 10, end: 5, count: 1 },
}),
@@ -566,7 +570,7 @@ describe('read_asset agent tool', () => {
it('rejects more than 20 frames', async () => {
mockAsset(videoAsset)
await expect(
readAssetTool().execute('call-1', {
invokeTool(readAssetTool(), 'call-1', {
assetId: 'vid-1',
videoConfig: { start: 0, end: 60, count: 21 },
}),
@@ -584,7 +588,7 @@ describe('read_asset agent tool', () => {
})
mockObjects()
const result = await readAssetTool().execute('call-1', {
const result = await invokeTool(readAssetTool(), 'call-1', {
assetId: 'vid-1',
annotationId: null,
imageConfig: null,
@@ -638,7 +642,7 @@ describe('read_asset agent tool', () => {
done: false,
}))
const result = await readAssetTool().execute('call-1', {
const result = await invokeTool(readAssetTool(), 'call-1', {
assetId: 'vid-1',
videoConfig: { start: 0, end: 10, count: 5 },
maxWaitSeconds: 0,
@@ -661,7 +665,7 @@ describe('read_asset agent tool', () => {
mockTaskFinished('task-shot', { screenshots: [{ key: 's/1.webp', timestamp: 0 }] })
mockObjects()
await readAssetTool().execute('call-1', {
await invokeTool(readAssetTool(), 'call-1', {
assetId: 'vid-1',
videoConfig: { start: 0, end: 0, count: 1 },
maxWaitSeconds: 600,
@@ -673,7 +677,7 @@ describe('read_asset agent tool', () => {
describe('Document Assets', () => {
it('requires docConfig', async () => {
mockAsset(pdfAsset)
await expect(readAssetTool().execute('call-1', { assetId: 'doc-1' })).rejects.toThrow(
await expect(invokeTool(readAssetTool(), 'call-1', { assetId: 'doc-1' })).rejects.toThrow(
'docConfig with mode ("pages" or "text") is required',
)
})
@@ -689,7 +693,7 @@ describe('read_asset agent tool', () => {
})
mockObjects()
const result = await readAssetTool().execute('call-1', {
const result = await invokeTool(readAssetTool(), 'call-1', {
assetId: 'doc-1',
docConfig: { mode: 'pages', startPage: 1, endPage: 2 },
})
@@ -716,7 +720,7 @@ describe('read_asset agent tool', () => {
it('rejects page ranges over 20 pages', async () => {
mockAsset(pdfAsset)
await expect(
readAssetTool().execute('call-1', {
invokeTool(readAssetTool(), 'call-1', {
assetId: 'doc-1',
docConfig: { mode: 'pages', startPage: 1, endPage: 25 },
}),
@@ -726,7 +730,7 @@ describe('read_asset agent tool', () => {
it('rejects mode "text" on a binary PDF', async () => {
mockAsset({ ...pdfAsset, name: 'manual.pdf' })
await expect(
readAssetTool().execute('call-1', {
invokeTool(readAssetTool(), 'call-1', {
assetId: 'doc-1',
docConfig: { mode: 'text', startPage: null, endPage: null },
}),
@@ -736,7 +740,7 @@ describe('read_asset agent tool', () => {
it('rejects mode "text" with annotationId', async () => {
mockAsset(markdownAsset)
await expect(
readAssetTool().execute('call-1', {
invokeTool(readAssetTool(), 'call-1', {
assetId: 'doc-md',
annotationId: 'comment-123',
docConfig: { mode: 'text', startPage: null, endPage: null },
@@ -748,7 +752,7 @@ describe('read_asset agent tool', () => {
it('rejects page numbers in mode "text"', async () => {
mockAsset(markdownAsset)
await expect(
readAssetTool().execute('call-1', {
invokeTool(readAssetTool(), 'call-1', {
assetId: 'doc-md',
docConfig: { mode: 'text', startPage: 1, endPage: 2 },
}),
@@ -762,7 +766,7 @@ describe('read_asset agent tool', () => {
contentType: 'text/markdown',
})
const result = await readAssetTool().execute('call-1', {
const result = await invokeTool(readAssetTool(), 'call-1', {
assetId: 'doc-md',
docConfig: { mode: 'text', startPage: null, endPage: null },
})
@@ -793,7 +797,7 @@ describe('read_asset agent tool', () => {
contentType: 'text/markdown',
})
const result = await readAssetTool().execute('call-1', {
const result = await invokeTool(readAssetTool(), 'call-1', {
assetId: 'doc-md',
docConfig: { mode: 'text' },
})
@@ -824,7 +828,7 @@ describe('read_asset agent tool', () => {
} as unknown as Asset)
mockObjects()
const result = await readAssetTool().execute('call-1', { assetId: 'stack-1' })
const result = await invokeTool(readAssetTool(), 'call-1', { assetId: 'stack-1' })
expect(prisma.asset.findFirst).toHaveBeenCalledWith({
where: { parentId: 'stack-1', isDeleted: false },
@@ -839,7 +843,7 @@ describe('read_asset agent tool', () => {
describe('s3KeyOnly mode', () => {
it('returns only the S3 key and MIME for image assets', async () => {
mockAsset(imageAsset)
const result = await readAssetTool().execute('call-1', {
const result = await invokeTool(readAssetTool(), 'call-1', {
assetId: 'img-1',
s3KeyOnly: true,
})
@@ -859,7 +863,7 @@ describe('read_asset agent tool', () => {
screenshots: [{ key: 'screenshots/shot1.webp', timestamp: 1.5 }],
})
const result = await readAssetTool().execute('call-1', {
const result = await invokeTool(readAssetTool(), 'call-1', {
assetId: 'vid-1',
s3KeyOnly: true,
videoConfig: { start: 1.5, end: 1.5, count: 1 },
@@ -875,7 +879,7 @@ describe('read_asset agent tool', () => {
it('returns only the document S3 key and MIME without reading the text', async () => {
mockAsset({ ...markdownAsset, name: 'notes.md', storageKey: { key: 'raw/notes.md' } })
const result = await readAssetTool().execute('call-1', {
const result = await invokeTool(readAssetTool(), 'call-1', {
assetId: 'doc-md',
s3KeyOnly: true,
docConfig: { mode: 'text', startPage: null, endPage: null },
@@ -919,7 +923,7 @@ describe('get_asset_render agent tool', () => {
})
mockObjects()
const result = await getAssetRenderTool().execute('call-1', { taskId: 'task-1' })
const result = await invokeTool(getAssetRenderTool(), 'call-1', { taskId: 'task-1' })
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
@@ -936,14 +940,14 @@ describe('get_asset_render agent tool', () => {
mockPendingTask('user-1')
vi.mocked(workflowService.waitFor).mockImplementation(async (task) => ({ task, done: false }))
const result = await getAssetRenderTool().execute('call-1', { taskId: 'task-1' })
const result = await invokeTool(getAssetRenderTool(), 'call-1', { taskId: 'task-1' })
expect(textOf(result)).toContain('Call get_asset_render with taskId "task-1"')
expect(details(result)).toEqual({ taskId: 'task-1', status: 'pending' })
})
it('hides renders requested by another user', async () => {
mockPendingTask('someone-else')
await expect(getAssetRenderTool().execute('call-1', { taskId: 'task-1' })).rejects.toThrow(
await expect(invokeTool(getAssetRenderTool(), 'call-1', { taskId: 'task-1' })).rejects.toThrow(
'Render not found',
)
expect(workflowService.waitFor).not.toHaveBeenCalled()
@@ -952,7 +956,7 @@ describe('get_asset_render agent tool', () => {
it('hides renders once the user loses access to the asset', async () => {
mockPendingTask('user-1')
vi.mocked(authzService.hasPermission).mockRejectedValue(new Error('Forbidden'))
await expect(getAssetRenderTool().execute('call-1', { taskId: 'task-1' })).rejects.toThrow(
await expect(invokeTool(getAssetRenderTool(), 'call-1', { taskId: 'task-1' })).rejects.toThrow(
'Render not found',
)
})
@@ -963,7 +967,7 @@ describe('get_asset_render agent tool', () => {
assetId: 'vid-1',
payload: { projectId: 'project-1' },
} as unknown as WorkflowTask)
await expect(getAssetRenderTool().execute('call-1', { taskId: 'task-2' })).rejects.toThrow(
await expect(invokeTool(getAssetRenderTool(), 'call-1', { taskId: 'task-2' })).rejects.toThrow(
'Render not found',
)
})
@@ -976,14 +980,14 @@ describe('autofill read_asset tool', () => {
it('requires targetAssetId', async () => {
const tool = createAutofillReadAssetTool({ teamId: 'team-1' })
await expect(tool.execute('call-1', { assetId: 'asset-1' })).rejects.toThrow(
await expect(invokeTool(tool, 'call-1', { assetId: 'asset-1' })).rejects.toThrow(
'Target asset ID is required for autofill agent authorization.',
)
})
it('requires teamId', async () => {
const tool = createAutofillReadAssetTool({ targetAssetId: 'asset-1' })
await expect(tool.execute('call-1', { assetId: 'asset-1' })).rejects.toThrow(
await expect(invokeTool(tool, 'call-1', { assetId: 'asset-1' })).rejects.toThrow(
'Team ID is required for autofill agent authorization.',
)
})
@@ -991,7 +995,7 @@ describe('autofill read_asset tool', () => {
it('denies assets from another team', async () => {
mockAsset({ id: 'asset-1', project: { teamId: 'other-team' } })
const tool = createAutofillReadAssetTool({ teamId: 'team-1', targetAssetId: 'asset-1' })
await expect(tool.execute('call-1', { assetId: 'asset-1' })).rejects.toThrow(
await expect(invokeTool(tool, 'call-1', { assetId: 'asset-1' })).rejects.toThrow(
'Access denied: asset asset-1 does not belong to team team-1.',
)
})
@@ -1002,7 +1006,7 @@ describe('autofill read_asset tool', () => {
teamId: 'team-1',
targetAssetId: 'target-asset-id',
})
await expect(tool.execute('call-1', { assetId: 'other-asset' })).rejects.toThrow(
await expect(invokeTool(tool, 'call-1', { assetId: 'other-asset' })).rejects.toThrow(
'Access denied: autofill agent can only read target asset target-asset-id.',
)
})
@@ -1021,7 +1025,7 @@ describe('autofill read_asset tool', () => {
targetAssetId: 'target-asset-id',
})
const result = await tool.execute('call-1', {
const result = await invokeTool(tool, 'call-1', {
assetId: 'target-asset-id',
annotationId: null,
s3KeyOnly: true,
@@ -1041,7 +1045,7 @@ describe('autofill read_asset tool', () => {
mockTaskFinished('task-shot', { screenshots: [{ key: 's/1.webp', timestamp: 0 }] })
const tool = createAutofillReadAssetTool({ teamId: 'team-1', targetAssetId: 'vid-1' })
await tool.execute('call-1', {
await invokeTool(tool, 'call-1', {
assetId: 'vid-1',
s3KeyOnly: true,
videoConfig: { start: 0, end: 0, count: 1 },
@@ -1,12 +1,19 @@
import { z } from 'zod'
import { type AgentTool, type AgentToolResult } from '@earendil-works/pi-agent-core'
import { type ImageContent, type TextContent } from '@earendil-works/pi-ai'
import { readAsset, type AssetReadOutput } from '@shumai/operations'
import { assetReadService, toAssetReadOutput } from '@shumai/core/src/asset-read'
import {
type ToolRegistration as AgentTool,
type ToolExecutionResult as AgentToolResult,
} from '@earendil-works/pi-durable'
import {
assetReadService,
MAX_TEXT_BYTES,
MAX_TEXT_LINES,
toAssetReadOutput,
} from '@shumai/core/src/asset-read'
import { getOperation, READ_WAIT_BUDGET_MS } from '@shumai/core/src/operations'
import { s3Service } from '@shumai/core/src/s3/s3'
import { getFileMimeType } from '@shumai/core/src/utils/file-mime'
import { MAX_TEXT_BYTES, MAX_TEXT_LINES } from '@shumai/core/src/asset-read'
import { readAsset, type AssetReadOutput } from '@shumai/operations'
import { z } from 'zod'
import {
registerAgentToolExtension,
splitAgentParams,
@@ -24,7 +31,7 @@ const extraParameters = z.object({
})
/** Details kept compatible with the previous tool; `sourceKeys` drives session image storage. */
interface ReadAssetDetails {
type ReadAssetDetails = {
assetId: string
name: string
mediaType: string | null
@@ -45,7 +52,7 @@ export async function presentReadOutput(
if (output.status === 'pending') {
const retry = output.retryAfterSeconds ?? 5
return {
content: [
output: [
{
type: 'text',
text: `${output.summary} Call get_asset_render with taskId "${output.taskId}" in about ${retry} seconds to get the result.`,
@@ -87,7 +94,7 @@ export async function presentReadOutput(
const imageKeys = output.images.map((i) => i.key ?? '')
const content: Array<TextContent | ImageContent> = [{ type: 'text', text }, ...imageBlocks]
return {
content,
output: content,
details: {
assetId: output.asset.id,
name: output.asset.name,
@@ -131,10 +138,10 @@ export function createAutofillReadAssetTool(access: {
const op = getOperation(readAsset.name)!
return {
name: readAsset.name,
label: readAsset.title,
description: readAsset.description,
parameters: toToolParameters(op, readAssetExtension),
execute: async (_toolCallId, params) => {
execute: async (params) => {
const { input, extra } = splitAgentParams(op, readAssetExtension, params)
const parsed = readAsset.input.safeParse(input)
if (!parsed.success) {
@@ -1,16 +1,17 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Value } from 'typebox/value'
import { validateToolArguments } from '@earendil-works/pi-ai'
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
import { AuditAction, type AssetInfo } from '@shumai/dtos'
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { assetService } from '@shumai/core/src/asset/asset'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { getOperation } from '@shumai/core/src/operations'
import { s3Service } from '@shumai/core/src/s3/s3'
import { AuditAction, type AssetInfo } from '@shumai/dtos'
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
import { Value } from 'typebox/value'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { fieldsToTypeBoxSchema } from '../index'
import { toAgentTool, type AgentToolOptions } from '../operation-tools'
import './upload'
@@ -106,7 +107,7 @@ describe('create_file and create_version agent tools', () => {
it('uploads a local file to storage and creates the file as the agent', async () => {
const filePath = tempFile('# Hello from disk', 'agent-create-file.md')
const result = await tool('create_file').execute('call-1', {
const result = await invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
path: filePath,
} as never)
@@ -155,7 +156,7 @@ describe('create_file and create_version agent tools', () => {
})
it('creates a text file from name and content', async () => {
await tool('create_file').execute('call-1', {
await invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
name: 'notes.md',
content: '# Notes\n\nHello',
@@ -172,7 +173,7 @@ describe('create_file and create_version agent tools', () => {
})
it('defaults unknown extensions to text/plain when creating from content', async () => {
await tool('create_file').execute('call-1', {
await invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
name: 'script.ts',
content: 'const x = 1',
@@ -185,7 +186,7 @@ describe('create_file and create_version agent tools', () => {
})
it('sanitizes the name', async () => {
await tool('create_file').execute('call-1', {
await invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
name: 'my/notes.md',
content: 'hello',
@@ -200,7 +201,7 @@ describe('create_file and create_version agent tools', () => {
it('forwards Creation Context metadata, including new select options', async () => {
const filePath = tempFile('# Hello', 'agent-create-file-meta.md')
await tool('create_file').execute('call-1', {
await invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
path: filePath,
metadata: { prompt: { newOption: { value: 'Kling' } } },
@@ -214,7 +215,7 @@ describe('create_file and create_version agent tools', () => {
it('treats null metadata as omitted', async () => {
const filePath = tempFile('# Hello', 'agent-create-file-null.md')
await tool('create_file').execute('call-1', {
await invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
path: filePath,
metadata: null,
@@ -227,7 +228,7 @@ describe('create_file and create_version agent tools', () => {
const filePath = tempFile('# Hello', 'agent-create-file-bad-meta.md')
await expect(
tool('create_file').execute('call-1', {
invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
path: filePath,
metadata: { status: 'approved' },
@@ -240,10 +241,10 @@ describe('create_file and create_version agent tools', () => {
it('rejects a call with neither or both of "path" and "content"', async () => {
await expect(
tool('create_file').execute('call-1', { parent: 'folder-1' } as never),
invokeTool(tool('create_file'), 'call-1', { parent: 'folder-1' } as never),
).rejects.toThrow('Provide exactly one of "path" (a local file) or "content" (with "name").')
await expect(
tool('create_file').execute('call-1', {
invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
path: '/some/file.md',
name: 'notes.md',
@@ -255,13 +256,13 @@ describe('create_file and create_version agent tools', () => {
it('requires a name with "content"', async () => {
await expect(
tool('create_file').execute('call-1', { parent: 'folder-1', content: 'x' } as never),
invokeTool(tool('create_file'), 'call-1', { parent: 'folder-1', content: 'x' } as never),
).rejects.toThrow('"name" is required')
})
it('fails when the local file does not exist, without touching storage', async () => {
await expect(
tool('create_file').execute('call-1', {
invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
path: '/nonexistent/file.md',
} as never),
@@ -277,10 +278,10 @@ describe('create_file and create_version agent tools', () => {
const filePath = tempFile('# Not allowed', 'agent-create-file-denied.md')
await expect(
tool('create_file').execute('call-1', { parent: 'folder-1', path: filePath } as never),
invokeTool(tool('create_file'), 'call-1', { parent: 'folder-1', path: filePath } as never),
).rejects.toThrow('User is not a member of the team')
await expect(
tool('create_file').execute('call-1', {
invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
name: 'notes.md',
content: 'x',
@@ -306,7 +307,7 @@ describe('create_file and create_version agent tools', () => {
} as Parameters<typeof validateToolArguments>[1],
)
await t.execute('call-1', validated as never)
await invokeTool(t, 'call-1', validated as never)
expect(assetService.createFile).toHaveBeenCalledWith(
expect.objectContaining({ name: 'random.txt' }),
)
@@ -324,7 +325,7 @@ describe('create_file and create_version agent tools', () => {
it('uploads a local file and creates a version as the agent', async () => {
const filePath = tempFile('# Hello from disk', 'agent-create-version.md')
const result = await tool('create_version').execute('call-1', {
const result = await invokeTool(tool('create_version'), 'call-1', {
parent: 'file-1',
path: filePath,
} as never)
@@ -349,7 +350,7 @@ describe('create_file and create_version agent tools', () => {
it('forwards Creation Context metadata', async () => {
const filePath = tempFile('# Hello', 'agent-create-version-meta.md')
await tool('create_version').execute('call-1', {
await invokeTool(tool('create_version'), 'call-1', {
parent: 'file-1',
path: filePath,
metadata: { prompt: 'Generated using gemini' },
@@ -367,7 +368,7 @@ describe('create_file and create_version agent tools', () => {
const filePath = tempFile('# Not allowed', 'agent-create-version-denied.md')
await expect(
tool('create_version').execute('call-1', { parent: 'file-1', path: filePath } as never),
invokeTool(tool('create_version'), 'call-1', { parent: 'file-1', path: filePath } as never),
).rejects.toThrow('User is not a member of the team')
expect(s3Service.putObject).not.toHaveBeenCalled()
expect(assetService.createVersion).not.toHaveBeenCalled()
@@ -375,7 +376,7 @@ describe('create_file and create_version agent tools', () => {
it('fails when the local file does not exist', async () => {
await expect(
tool('create_version').execute('call-1', {
invokeTool(tool('create_version'), 'call-1', {
parent: 'file-1',
path: '/nonexistent/file.md',
} as never),
@@ -1,13 +1,13 @@
import * as fs from 'fs'
import * as path from 'path'
import { z } from 'zod'
import { Type } from 'typebox'
import type { AgentToolResult } from '@earendil-works/pi-agent-core'
import { createFile, type StartedUploadOutput } from '@shumai/operations'
import type { ToolExecutionResult as AgentToolResult } from '@earendil-works/pi-durable'
import { storageBucket } from '@shumai/core/src/asset-read'
import { completeUploadOp, runOperation } from '@shumai/core/src/operations'
import { s3Service } from '@shumai/core/src/s3/s3'
import { getFileMimeType, readFileMimeType } from '@shumai/core/src/utils/file-mime'
import { createFile, type StartedUploadOutput } from '@shumai/operations'
import * as fs from 'fs'
import * as path from 'path'
import { Type } from 'typebox'
import { z } from 'zod'
import {
registerAgentToolExtension,
type AgentOperationContext,
@@ -48,7 +48,7 @@ async function uploadAndComplete(
raw: unknown,
extra: Record<string, unknown>,
ctx: AgentOperationContext,
): Promise<AgentToolResult<unknown>> {
): Promise<AgentToolResult> {
const started = raw as StartedUploadOutput
if (!started.key) throw new Error('The upload did not return a storage key')
@@ -79,7 +79,7 @@ async function uploadAndComplete(
{ ...ctx, via: 'agent' },
{ uploadId: started.uploadId },
)
return { content: [{ type: 'text', text: JSON.stringify(asset, null, 2) }], details: {} }
return { output: [{ type: 'text', text: JSON.stringify(asset, null, 2) }], details: {} }
}
const createFileExtension: AgentToolExtension = {
+7 -6
View File
@@ -1,12 +1,13 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Value } from 'typebox/value'
import { validateToolArguments } from '@earendil-works/pi-ai'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { AuditAction, type AssetInfo, type ProjectInfo } from '@shumai/dtos'
import { type ToolRegistration as AgentTool } from '@earendil-works/pi-durable'
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { assetService } from '@shumai/core/src/asset/asset'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { projectService } from '@shumai/core/src/project/project'
import { AuditAction, type AssetInfo, type ProjectInfo } from '@shumai/dtos'
import { Value } from 'typebox/value'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { buildOperationTools } from './operation-tools'
const ctx = { userId: 'user-1', agentId: 'agent-1', teamId: 'team-1', projectId: 'proj-1' }
@@ -33,7 +34,7 @@ function getTool(name: string): AgentTool {
}
async function run(name: string, params: Record<string, unknown>) {
const result = await getTool(name).execute('call-1', params as never)
const result = await invokeTool(getTool(name), 'call-1', params as never)
return { result, output: JSON.parse((result.content[0] as { text: string }).text) as unknown }
}
@@ -136,7 +137,7 @@ describe('operation-backed agent tools', () => {
arguments: { parent: 'folder-1' },
} as Parameters<typeof validateToolArguments>[1],
)
await expect(tool.execute('call-1', validated as never)).resolves.toBeDefined()
await expect(invokeTool(tool, 'call-1', validated as never)).resolves.toBeDefined()
})
})
+12 -10
View File
@@ -1,14 +1,17 @@
import { z } from 'zod'
import type { TSchema } from 'typebox'
import { Compile } from 'typebox/compile'
import { type AgentTool, type AgentToolResult } from '@earendil-works/pi-agent-core'
import { dropNullOptionals } from '@shumai/operations'
import {
type ToolRegistration as AgentTool,
type ToolExecutionResult as AgentToolResult,
} from '@earendil-works/pi-durable'
import {
getOperationsForSurface,
runOperation,
type Operation,
type OperationContext,
} from '@shumai/core/src/operations'
import { dropNullOptionals } from '@shumai/operations'
import type { TSchema } from 'typebox'
import { Compile } from 'typebox/compile'
import { z } from 'zod'
/** Context for agent-invoked Operations; `via` is always `agent`. */
export type AgentOperationContext = Omit<OperationContext, 'via'>
@@ -60,12 +63,12 @@ export interface AgentToolExtension {
input: Record<string, unknown>,
extra: Record<string, unknown>,
ctx: AgentOperationContext,
): Promise<AgentToolResult<unknown> | undefined>
): Promise<AgentToolResult | undefined>
present(
output: unknown,
extra: Record<string, unknown>,
ctx: AgentOperationContext,
): Promise<AgentToolResult<unknown>>
): Promise<AgentToolResult>
}
const extensions = new Map<string, AgentToolExtension>()
@@ -135,10 +138,9 @@ export function toAgentTool(
const extension = extensions.get(definition.name)
return {
name: definition.name,
label: definition.title,
description: extension?.description ?? definition.description,
parameters: toToolParameters(op, extension, options),
execute: async (_toolCallId, params) => {
execute: async (params) => {
const { input, extra } = splitAgentParams(op, extension, params)
if (extension?.intercept) {
const handled = await extension.intercept(input as Record<string, unknown>, extra, ctx)
@@ -149,7 +151,7 @@ export function toAgentTool(
return extension.present(output, extra, ctx)
}
return {
content: [{ type: 'text', text: JSON.stringify(output, null, 2) }],
output: [{ type: 'text', text: JSON.stringify(output, null, 2) }],
details: {},
}
},
+664
View File
@@ -0,0 +1,664 @@
import { BACKGROUND_CONTEXT as piContext } from '@earendil-works/chord/context'
import type { Model, ModelThinkingLevel } from '@earendil-works/pi-ai'
import {
createModels,
createProvider,
envApiKeyAuth,
InMemoryCredentialStore,
type ProviderStreams,
} from '@earendil-works/pi-ai'
import { anthropicMessagesApi } from '@earendil-works/pi-ai/api/anthropic-messages.lazy'
import { azureOpenAIResponsesApi } from '@earendil-works/pi-ai/api/azure-openai-responses.lazy'
import { bedrockConverseStreamApi } from '@earendil-works/pi-ai/api/bedrock-converse-stream.lazy'
import { googleGenerativeAIApi } from '@earendil-works/pi-ai/api/google-generative-ai.lazy'
import { googleVertexApi } from '@earendil-works/pi-ai/api/google-vertex.lazy'
import { mistralConversationsApi } from '@earendil-works/pi-ai/api/mistral-conversations.lazy'
import { openAICodexResponsesApi } from '@earendil-works/pi-ai/api/openai-codex-responses.lazy'
import { openAICompletionsApi } from '@earendil-works/pi-ai/api/openai-completions.lazy'
import { openAIResponsesApi } from '@earendil-works/pi-ai/api/openai-responses.lazy'
import { builtinProviders } from '@earendil-works/pi-ai/providers/all'
import {
createRegistry,
defineExtension,
GenerationTask,
Harness,
hook,
type ToolRegistration as AgentTool,
} from '@earendil-works/pi-durable'
import { sandboxService } from '@shumai/core'
import { agentService } from '@shumai/core/src/agent/agent'
import { hydrateRequest } from '@shumai/core/src/agent/session-content'
import { agentSessionService } from '@shumai/core/src/agent/session-service'
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
import { logger } from '@shumai/core/src/logger'
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { QuotaExceededError, quotaService } from '@shumai/core/src/quota/quota-service'
import { prisma } from '@shumai/db'
import { DEFAULT_DENIED_TOOLS } from '@shumai/dtos'
import * as fs from 'fs'
import * as path from 'path'
import { Type, type TSchema } from 'typebox'
import { createAutofillReadAssetTool } from './operation-extensions'
import { buildOperationTools } from './operation-tools'
import { createGenerateImageTool } from './tools/generate-image'
import { createGenerateVideoTool } from './tools/generate-video'
import { createReadSkillTool } from './tools/read-skill'
import { createReadThreadTool } from './tools/read-thread'
import { createSandboxedBashTool } from './tools/sandboxed-bash'
const activeHarnesses = new Set<Harness>()
export async function closeAgentSessions() {
await Promise.allSettled([...activeHarnesses].map((harness) => harness.close(piContext)))
await agentSessionService.closeAll()
}
export interface DbModelInfo {
modelId: string
name: string | null
config: PrismaJson.ModelConfig
}
export interface DbProviderInfo {
name: string
config: PrismaJson.ProviderConfig
models: DbModelInfo[]
}
type ConfiguredApi = PrismaJson.ProviderConfig['api']
const apiAdapters = {
'anthropic-messages': anthropicMessagesApi,
'azure-openai-responses': azureOpenAIResponsesApi,
'bedrock-converse-stream': bedrockConverseStreamApi,
'google-generative-ai': googleGenerativeAIApi,
'google-vertex': googleVertexApi,
'mistral-conversations': mistralConversationsApi,
'openai-codex-responses': openAICodexResponsesApi,
'openai-completions': openAICompletionsApi,
'openai-responses': openAIResponsesApi,
} satisfies Record<ConfiguredApi, () => ProviderStreams>
export function getModelFromDb(providers: DbProviderInfo[], providerName: string, modelId: string) {
const dbProvider = providers.find((p) => p.name === providerName)
const dbModel = dbProvider?.models.find((m) => m.modelId === modelId)
if (!dbProvider || !dbModel) {
throw new Error(
`Provider "${providerName}" or model "${modelId}" not found in database configuration`,
)
}
const m = {
id: modelId,
name: dbModel.name || modelId,
provider: providerName,
api: 'openai-responses',
baseUrl: '',
reasoning: false,
input: ['text'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 4096,
maxTokens: 4096,
}
// Override with database config
if (dbProvider.config.baseUrl) {
m.baseUrl = dbProvider.config.baseUrl
}
Object.assign(m, dbModel.config)
if (dbProvider.config.api) {
m.api = dbProvider.config.api
}
if (dbModel.name) {
m.name = dbModel.name
}
return m as Model<ConfiguredApi>
}
export function getApiKeyAndHeadersFromDb(providers: DbProviderInfo[], providerName: string) {
// Helper to resolve key from ENV if it matches an ENV var name
const resolveKey = (key: string | undefined) => (key ? process.env[key] || key : undefined)
// Look up the provider in our providers list
const dbProvider = providers.find((p) => p.name === providerName)
const providerApiKey = dbProvider?.config?.apiKey
if (providerApiKey) {
return { apiKey: resolveKey(providerApiKey)! }
}
return undefined
}
export interface CreateAgentSessionParams {
teamId: string
agentId: string
providerName: string
modelId: string
systemPrompt: string
teamSkills: Array<{ id: string; name: string; description?: string | null }>
enabledSkillIds?: string[]
allowedDomains?: string[]
sessionId?: string
userId?: string
projectId?: string
assetId?: string
userCommentId?: string | null
customTools?: AgentTool[]
thinkingLevel?: string
disableTools?: boolean
providers: DbProviderInfo[]
maxRetries?: number
baseDelayMs?: number
}
/**
* Security instructions appended to the system prompt when the requesting user is not a team
* owner (i.e. editor/reviewer). These complement the hard enforcement in the bash tool itself
* (source="user" is blocked) and the delayed bash tool injection after a skill is loaded.
*/
export function buildRestrictedUserInstructions(): string {
return [
'# Restricted User Context',
'The current user is NOT a team owner. You must follow these security rules:',
'1. NEVER execute a bash command that the user asks you to run directly. Direct user bash requests are not permitted for this user role. Politely decline and explain that they need a team owner or an approved skill.',
'2. You may ONLY use the `bash` tool to execute commands that are explicitly required by a skill you have loaded via the `read_skill` tool.',
'3. When calling `bash`, you MUST set the `source` parameter to "skill". Calls with source="user" will be rejected by the system.',
].join('\n')
}
export async function createAgentSession(params: CreateAgentSessionParams) {
const {
teamId,
agentId,
providerName,
modelId,
systemPrompt,
teamSkills,
enabledSkillIds,
allowedDomains,
sessionId,
userId,
projectId,
assetId,
userCommentId: passedUserCommentId,
customTools = [],
thinkingLevel,
disableTools = false,
maxRetries = 3,
baseDelayMs = 2000,
} = params
const record = sessionId
? await prisma.agentSession.findUniqueOrThrow({ where: { id: sessionId } })
: await prisma.agentSession.create({
data: { agentId, userId, cwd: process.cwd(), assetId, userCommentId: passedUserCommentId },
})
const opened = await agentSessionService.openWriter(record.id, piContext, {
teamId,
userId,
role: userId ? await resolveEffectiveRole(teamId, projectId, userId) : undefined,
})
const storage = opened.storage
try {
const agentDir = path.join(process.cwd(), '.pi', 'agents', agentId)
if (!fs.existsSync(agentDir)) fs.mkdirSync(agentDir, { recursive: true })
getModelFromDb(params.providers, providerName, modelId)
const piDir = path.join(process.cwd(), '.pi')
if (!fs.existsSync(piDir)) fs.mkdirSync(piDir, { recursive: true })
const role = userId ? await resolveEffectiveRole(teamId, projectId, userId) : undefined
const isOwner = !userId || role === 'owner'
const restricted = !isOwner
const wrapToolWithQuota = (tool: AgentTool): AgentTool => {
const originalExecute = tool.execute
return {
...tool,
execute: async (args, api, context) => {
try {
await quotaService.checkQuota(
{
teamId,
userId,
role,
resource: 'agent_tool_call_count',
resourceData: { name: tool.name, toolName: tool.name },
},
1,
)
} catch (err) {
if (err instanceof QuotaExceededError) {
return {
output: [{ type: 'text', text: `Quota exceeded: ${err.message}` }],
details: { error: err.message },
}
}
throw err
}
const result = await originalExecute(args, api, context)
try {
await quotaService.consumeQuota(
{
teamId,
userId,
role,
resource: 'agent_tool_call_count',
resourceData: { name: tool.name, toolName: tool.name },
},
1,
)
} catch (err) {
logger.error({ err }, 'Failed to record quota usage for agent tool call')
}
return result
},
}
}
if (allowedDomains !== undefined) {
await sandboxService.syncAllowedDomains(allowedDomains, teamId)
}
const skillEnvs: Record<string, string> = {}
const onEnvsAdded = (envs: Record<string, string>) => {
Object.assign(skillEnvs, envs)
}
// Restore env variables from previously loaded skills in this session
let skillLoadedInSession = false
if (sessionId) {
try {
const entries = await agentSessionService.getEntries(record.id)
for (const entry of entries) {
for (const message of entry.model ?? []) {
if (
message.role === 'toolResult' &&
message.toolName === 'read_skill' &&
!message.isError
) {
const details = message.details
if (
details &&
typeof details === 'object' &&
!Array.isArray(details) &&
'skillId' in details &&
typeof details.skillId === 'string'
) {
skillLoadedInSession = true
onEnvsAdded(await agentService.getSkillEnvs(details.skillId))
}
}
}
}
} catch (err) {
logger.error({ err, sessionId }, 'Failed to restore skill environment variables')
}
}
const agent = await prisma.agent.findUnique({
where: { id: agentId },
})
const agentConfig = agent?.config as PrismaJson.AgentConfig | null | undefined
const deniedTools = agentConfig?.deniedTools ?? [...DEFAULT_DENIED_TOOLS]
const mediaTools: AgentTool[] = []
// Agents acting for a user get read_asset / get_asset_render from the Operation registry
// (see systemTools below); the autofill system agent has its own team-scoped read_asset.
if (!userId && agent?.type === 'autofill' && assetId) {
mediaTools.push(
createAutofillReadAssetTool({
teamId,
targetAssetId: assetId,
}),
)
}
if (!deniedTools.includes('generate_image') || !deniedTools.includes('generate_video')) {
try {
const { imageModels, videoModels, providerKeys } =
await mediaGenerationService.getValidModels(teamId)
if (imageModels.length > 0 && !deniedTools.includes('generate_image')) {
mediaTools.push(createGenerateImageTool(imageModels, providerKeys, userId))
}
if (videoModels.length > 0 && !deniedTools.includes('generate_video')) {
mediaTools.push(createGenerateVideoTool(videoModels, providerKeys, userId))
}
} catch (err) {
logger.error({ err, teamId }, 'Failed to initialize media generation tools')
}
}
const sandboxedBash = createSandboxedBashTool(process.cwd(), skillEnvs, {
teamId,
userId,
role,
getBlockedHost: (commandId?: string) => sandboxService.getBlockedHost(commandId),
clearBlockedHost: () => {
sandboxService.clearBlockedHost()
},
// Non-owner users can only run bash commands required by a loaded skill
restrictedUser: restricted,
})
// For non-owner users, the bash tool is not injected initially. It becomes available
// only after a skill is successfully loaded via the read_skill tool (or immediately when
// a skill was already loaded earlier in this session).
const registry = createRegistry()
const bashIncludedFromStart = isOwner || skillLoadedInSession
let bashInjected = bashIncludedFromStart
const onSkillLoaded = async () => {
if (bashInjected || deniedTools.includes('bash')) return
bashInjected = true
registry.install(
defineExtension({ name: 'shumai.bash', tools: [wrapToolWithQuota(sandboxedBash)] }),
)
await session?.configure(
{
tools: [...enabledTools, wrapToolWithQuota(sandboxedBash)],
modelTools: { add: [sandboxedBash] },
},
piContext,
)
}
const readSkill = createReadSkillTool(
userId,
onEnvsAdded,
restricted ? onSkillLoaded : undefined,
enabledSkillIds,
projectId,
)
const systemTools: AgentTool[] = []
if (userId) {
const creationMetadataSchema = await buildProjectMetadataSchema(projectId)
systemTools.push(
// Shared Operations (also exposed via MCP and the CLI): browsing, searching, organizing,
// reading and downloading assets, creating files and versions, comments and metadata
...buildOperationTools({ userId, agentId, teamId, projectId }, { creationMetadataSchema }),
)
}
const readThread = createReadThreadTool({ userId, teamId })
const rawTools = [
...mediaTools,
readSkill,
readThread,
...(bashIncludedFromStart ? [sandboxedBash] : []),
...systemTools,
...customTools,
]
const allTools = rawTools.map((tool) => wrapToolWithQuota(tool))
const enabledTools = disableTools
? []
: allTools.filter((tool) => !deniedTools.includes(tool.name))
const credentials = new InMemoryCredentialStore()
const resolveKey = (key: string | undefined) => (key ? process.env[key] || key : undefined)
for (const p of params.providers) {
const apiKey = resolveKey(p.config?.apiKey)
if (apiKey) {
await credentials.modify(p.name, async () => ({ type: 'api_key' as const, key: apiKey }))
}
}
const modelsStore = createModels({ credentials })
for (const provider of builtinProviders()) {
modelsStore.setProvider(provider)
}
const configuredModel = getModelFromDb(params.providers, providerName, modelId)
const builtin = modelsStore.getProvider(providerName)
if (builtin?.getModels().some((candidate) => candidate.api === configuredModel.api)) {
modelsStore.setProvider({ ...builtin, getModels: () => [configuredModel] })
} else {
// Providers that share an API can still require different authentication and headers.
modelsStore.setProvider(
createProvider({
id: providerName,
models: [configuredModel],
api: apiAdapters[configuredModel.api](),
auth: { apiKey: envApiKeyAuth('API key', []) },
}),
)
}
registry.install(
defineExtension({
name: 'shumai',
tools: enabledTools,
hooks: [
hook(GenerationTask, {
beforeRequest: async ({ messages }, api, context) => ({
messages: await hydrateRequest(messages, api, context),
}),
}),
],
}),
)
const harness = await Harness.open(
storage,
{
models: modelsStore,
registry,
settings: { retry: { enabled: true, maxRetries, baseDelayMs } },
onReport: (report) =>
logger.error({ kind: report.kind, err: report.error }, 'Agent runtime report'),
},
piContext,
)
const buildPrompt = async () => {
let prompt = systemPrompt
if (disableTools) {
return prompt
}
if (restricted) {
prompt += `\n\n${buildRestrictedUserInstructions()}`
}
// Sandbox environment restrictions
prompt +=
'\n\n' +
[
'# Sandbox Environment Restrictions',
'Your shell environment (the `bash` tool) is highly sandboxed to protect the host system:',
'1. **Filesystem Isolation**: You only have read and write permissions to the `.pi` folder in the project root directory.',
'2. **Read/Write Restrictions**: All reading and writing to directories outside `.pi` (e.g. your home directory `~/`, `/tmp`, `/etc`, or the rest of the workspace) are strictly denied by the sandbox security policy.',
"3. **Avoid System Temp Directory Writes**: You must strictly avoid any commands or shell constructs that attempt to write to the system temporary directory `/tmp` or `/var/tmp`. For example, do not use Bash here documents (`<<EOF` or `<<'EOF'`) in your commands, as the bash shell internally implements here documents by writing temporary files to `/tmp`. If you need to create a file or write content, write it directly using file creation tools or write to files located inside the `.pi` directory without utilizing here documents.",
'4. **Temporary File Cleanup**: If you download workspace assets to `.pi` using the `download_asset` tool for local processing or script execution, you MUST delete the temporary downloaded files from `.pi` after finishing your task.',
].join('\n')
if (teamSkills.length > 0) {
prompt += formatSkillsForPrompt(teamSkills)
}
return prompt
}
const session = await harness.root(piContext)
await session.configure(
{
model: { provider: providerName, modelId },
thinkingLevel: (thinkingLevel || 'off') as ModelThinkingLevel,
instructions: await buildPrompt(),
tools: enabledTools,
},
piContext,
)
const onLost = () => {
void harness.close(piContext)
}
opened.signal.addEventListener('abort', onLost, { once: true })
activeHarnesses.add(harness)
harness.subscribeClose(() => {
activeHarnesses.delete(harness)
opened.signal.removeEventListener('abort', onLost)
})
return { session, harness, storage, sessionId: record.id }
} catch (error) {
await storage.close(piContext)
throw error
}
}
export interface AutofillField {
id: string
config: PrismaJson.FieldConfig
description?: string | null
}
export function fieldsToTypeBoxSchema(fields: AutofillField[]) {
const newOptionSchema = Type.Object(
{
newOption: Type.Object(
{
value: Type.String({
minLength: 1,
description:
'The new option display name/value to create and select if none of the existing options match.',
}),
},
{ additionalProperties: false },
),
},
{ additionalProperties: false },
)
const properties: Record<string, TSchema> = {}
for (const f of fields) {
let schema: TSchema
const fieldName = f.config.name
const fieldDesc = f.description || fieldName
const baseDescription = `The field '${fieldName}' represents ${fieldDesc}.`
switch (f.config.type) {
case 'text':
case 'longText':
schema = Type.String({ description: baseDescription })
break
case 'number':
case 'rating':
schema = Type.Number({ description: baseDescription })
break
case 'toggle':
schema = Type.Boolean({ description: baseDescription })
break
case 'select': {
const options = f.config.select?.options || []
const description =
options.length > 0
? `${baseDescription}\nSelect one existing option ID or provide {"newOption": {"value": "..."}} to create a new option.\n\nAvailable options:\n${options.map((o) => `- ${o.displayName} => ${o.id}`).join('\n')}`
: `${baseDescription}\nProvide {"newOption": {"value": "..."}} with the desired option name.`
if (options.length > 0) {
schema = Type.Union(
[
Type.String({
enum: options.map((o) => o.id),
}),
newOptionSchema,
],
{ description },
)
} else {
schema = Type.Object(newOptionSchema.properties, {
additionalProperties: false,
description,
})
}
break
}
case 'selectMulti': {
const options = f.config.selectMulti?.options || []
const description =
options.length > 0
? `${baseDescription}\nSelect applicable option IDs or provide {"newOption": {"value": "..."}} objects for new options (e.g. ["opt1", {"newOption": {"value": "new_name"}}]).\n\nAvailable options:\n${options.map((o) => `- ${o.displayName} => ${o.id}`).join('\n')}`
: `${baseDescription}\nProvide an array of {"newOption": {"value": "..."}} objects for new options.`
const itemSchema =
options.length > 0
? Type.Union([
Type.String({
enum: options.map((o) => o.id),
}),
newOptionSchema,
])
: newOptionSchema
schema = Type.Array(itemSchema, { description })
break
}
default:
schema = Type.String({ description: baseDescription })
}
// Every field is required but nullable: the agent must return each field key,
// using `null` for values it does not know. Nulls are skipped when persisting.
// This matches the OpenAI structured-outputs strict-mode convention (all
// properties required, optionality expressed via `null`).
properties[f.id] = Type.Union([schema, Type.Null()])
}
return Type.Object(properties, { additionalProperties: false })
}
/**
* Builds the strict, all-optional metadata schema for the project's CREATION_CONTEXT
* fields (the same field set the agent may attach when creating files/versions).
* Returns undefined when no project is known or the project defines no fields, in
* which case the `metadata` parameter is omitted from the tools entirely.
*/
async function buildProjectMetadataSchema(projectId?: string): Promise<TSchema | undefined> {
if (!projectId) return undefined
const fields = await metadataService.listProjectFields('', projectId)
const creationFields: AutofillField[] = []
for (const f of fields) {
const config = f.field.config
if (!config || config.autofillSource !== 'CREATION_CONTEXT') continue
creationFields.push({
id: f.field.key,
config,
description: f.field.description,
})
}
if (creationFields.length === 0) return undefined
return fieldsToTypeBoxSchema(creationFields)
}
function escapeXml(str: string): string {
return str
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;')
}
export function formatSkillsForPrompt(
skills: Array<{ id: string; name: string; description?: string | null }>,
): string {
if (skills.length === 0) {
return ''
}
const lines = [
'\n\nThe following skills provide specialized instructions for specific tasks.',
"Use the read_skill tool to load a skill's file when the task matches its description.",
'When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.',
'',
'<available_skills>',
]
for (const skill of skills) {
const filePath = path.join(process.cwd(), '.pi', 'skills', skill.id, 'SKILL.md')
lines.push(' <skill>')
lines.push(` <id>${escapeXml(skill.id)}</id>`)
lines.push(` <name>${escapeXml(skill.name)}</name>`)
lines.push(` <description>${escapeXml(skill.description || 'No description')}</description>`)
lines.push(` <location>${escapeXml(filePath)}</location>`)
lines.push(' </skill>')
}
lines.push('</available_skills>')
return lines.join('\n')
}
@@ -0,0 +1,66 @@
import { fauxAssistantMessage, type AssistantMessage } from '@earendil-works/pi-ai'
import {
MemoryStorage,
ROOT_CONVERSATION_ID,
type Conversation,
type Harness,
type Tx,
} from '@earendil-works/pi-durable'
import { vi } from 'vitest'
import type { createAgentSession } from '../runtime'
/** Native conversation fixture for activity orchestration tests; model behavior remains independently scripted. */
export function mockAgentSession(
model: { prompt: (...args: unknown[]) => Promise<unknown>; abort?: () => void },
metadata: { getStorage?: () => unknown } = {},
): Awaited<ReturnType<typeof createAgentSession>> {
let answer = fauxAssistantMessage('')
const information = metadata.getStorage?.() as { sessionId?: string } | undefined
const entry = () => ({
id: 9,
conversationId: ROOT_CONVERSATION_ID,
kind: 'pi.assistant',
model: [answer],
})
const session = {
id: ROOT_CONVERSATION_ID,
submit: vi.fn(async (draft: { content: string | Array<{ type: string; text?: string }> }) => {
const text =
typeof draft.content === 'string'
? draft.content
: draft.content
.filter((block) => block.type === 'text')
.map((block) => block.text)
.join('\n')
const response = (await model.prompt(text, {
images:
typeof draft.content === 'string'
? []
: draft.content.filter((block) => block.type === 'image'),
})) as Partial<AssistantMessage>
answer = {
...fauxAssistantMessage(''),
...response,
usage: { ...fauxAssistantMessage('').usage, ...response.usage },
}
return { wait: async () => ({ type: 'input', status: 'done', entry: 7, answer: 9 }) }
}),
abort: vi.fn(async () => {
model.abort?.()
}),
commit: vi.fn(async (change: (tx: Tx) => unknown) =>
change({ entry: async () => entry() } as unknown as Tx),
),
} as unknown as Conversation
const harness = {
root: vi.fn(async () => session),
close: vi.fn(async () => {}),
usage: vi.fn(async () => ({ models: { faux: answer.usage }, tools: {} })),
} as unknown as Harness
return {
session,
harness,
storage: new MemoryStorage(),
sessionId: information?.sessionId ?? 'mock-session-id',
}
}
+18 -11
View File
@@ -1,14 +1,15 @@
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { vi } from 'vitest'
vi.mock('fs')
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { createGenerateImageTool } from './generate-image'
import * as downloadAsset from './download-asset'
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
import { EnabledMediaModel } from '@shumai/dtos'
import * as fs from 'fs'
import * as path from 'path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import * as downloadAsset from './download-asset'
import { createGenerateImageTool } from './generate-image'
describe('generate_image tool', () => {
const enabledModels: EnabledMediaModel[] = [
@@ -60,7 +61,6 @@ describe('generate_image tool', () => {
it('creates tool with correct metadata and provider-prefixed model schema', () => {
const tool = createGenerateImageTool(enabledModels, providerKeys, 'user-1')
expect(tool.name).toBe('generate_image')
expect(tool.label).toBe('Generate Image')
expect(tool.description).toContain('Generate an image')
const modelDesc = (tool.parameters as { properties: { model: { description: string } } })
.properties.model.description
@@ -78,7 +78,8 @@ describe('generate_image tool', () => {
})
const writeSpy = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})
const result = await tool.execute(
const result = await invokeTool(
tool,
'call-1',
{
prompt: 'A futuristic city skyline at dusk',
@@ -129,7 +130,8 @@ describe('generate_image tool', () => {
})
// Invoke azure:dall-e-3
await tool.execute(
await invokeTool(
tool,
'call-azure',
{
prompt: 'Azure generation',
@@ -153,7 +155,8 @@ describe('generate_image tool', () => {
)
// Invoke openai:dall-e-3
await tool.execute(
await invokeTool(
tool,
'call-openai',
{
prompt: 'OpenAI generation',
@@ -186,7 +189,8 @@ describe('generate_image tool', () => {
mimeType: 'image/png',
})
await tool.execute(
await invokeTool(
tool,
'call-2',
{
prompt: 'A cute cat',
@@ -224,7 +228,8 @@ describe('generate_image tool', () => {
mimeType: 'image/png',
}))
await tool.execute(
await invokeTool(
tool,
'call-3',
{
prompt: 'Transform into watercolor',
@@ -257,7 +262,8 @@ describe('generate_image tool', () => {
const tool = createGenerateImageTool(enabledModels, {}, 'user-1') // No keys configured
await expect(
tool.execute(
invokeTool(
tool,
'call-4',
{
prompt: 'A sunset',
@@ -278,7 +284,8 @@ describe('generate_image tool', () => {
const tool = createGenerateImageTool(enabledModels, providerKeys, 'user-1')
await expect(
tool.execute(
invokeTool(
tool,
'call-5',
{
prompt: 'A sunset',
+6 -6
View File
@@ -1,10 +1,10 @@
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { EnabledMediaModel } from '@shumai/dtos'
import { type ToolRegistration as AgentTool } from '@earendil-works/pi-durable'
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
import { Type, type Static, type TSchema } from 'typebox'
import { EnabledMediaModel } from '@shumai/dtos'
import * as fs from 'fs'
import * as path from 'path'
import { Type, type Static, type TSchema } from 'typebox'
import { ulid } from 'ulid'
import { resolveS3MediaBuffer } from './download-asset'
@@ -83,11 +83,11 @@ export function createGenerateImageTool(
return {
name: 'generate_image',
label: 'Generate Image',
description:
'Generate an image using a configured image model. Supports text-to-image, reference images (image-to-image using S3 keys from read_asset), and inpainting (using a mask image S3 key from read_asset). The generated file is saved in the local .pi/ directory.',
parameters: generateImageSchema,
execute: async (_toolCallId, params) => {
execute: async (params) => {
const p = params as GenerateImageParams
const defaultModel = `${enabledModels[0].provider}:${enabledModels[0].modelId}`
@@ -161,7 +161,7 @@ export function createGenerateImageTool(
fs.writeFileSync(targetPath, buffer)
return {
content: [
output: [
{
type: 'text',
text: `Successfully generated image using model "${modelConfig.modelId}" (${modelConfig.provider}). Saved to "${relativePath}". Size: ${(buffer.length / 1024).toFixed(1)} KB.`,
+18 -11
View File
@@ -1,14 +1,15 @@
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { vi } from 'vitest'
vi.mock('fs')
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { createGenerateVideoTool } from './generate-video'
import * as downloadAsset from './download-asset'
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
import { EnabledMediaModel } from '@shumai/dtos'
import * as fs from 'fs'
import * as path from 'path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import * as downloadAsset from './download-asset'
import { createGenerateVideoTool } from './generate-video'
describe('generate_video tool', () => {
const enabledModels: EnabledMediaModel[] = [
@@ -60,7 +61,6 @@ describe('generate_video tool', () => {
it('creates tool with correct metadata and provider-prefixed model schema', () => {
const tool = createGenerateVideoTool(enabledModels, providerKeys, 'user-1')
expect(tool.name).toBe('generate_video')
expect(tool.label).toBe('Generate Video')
expect(tool.description).toContain('Generate a video')
const modelDesc = (tool.parameters as { properties: { model: { description: string } } })
.properties.model.description
@@ -78,7 +78,8 @@ describe('generate_video tool', () => {
})
const writeSpy = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})
const result = await tool.execute(
const result = await invokeTool(
tool,
'call-vid-1',
{
mode: 'text_to_video',
@@ -140,7 +141,8 @@ describe('generate_video tool', () => {
})
// Select fal:kling-v1-standard
await tool.execute(
await invokeTool(
tool,
'call-fal',
{
mode: 'text_to_video',
@@ -169,7 +171,8 @@ describe('generate_video tool', () => {
)
// Select klingai:kling-v1-standard
await tool.execute(
await invokeTool(
tool,
'call-klingai',
{
mode: 'text_to_video',
@@ -211,7 +214,8 @@ describe('generate_video tool', () => {
mimeType: 'image/png',
})
await tool.execute(
await invokeTool(
tool,
'call-vid-2',
{
mode: 'image_to_video',
@@ -257,7 +261,8 @@ describe('generate_video tool', () => {
mimeType: 'image/png',
}))
await tool.execute(
await invokeTool(
tool,
'call-vid-3',
{
mode: 'first_last_frame',
@@ -304,7 +309,8 @@ describe('generate_video tool', () => {
mimeType: 'image/png',
}))
await tool.execute(
await invokeTool(
tool,
'call-vid-4',
{
mode: 'reference_to_video',
@@ -343,7 +349,8 @@ describe('generate_video tool', () => {
const tool = createGenerateVideoTool(enabledModels, {}, 'user-1')
await expect(
tool.execute(
invokeTool(
tool,
'call-vid-5',
{
mode: 'text_to_video',
+6 -6
View File
@@ -1,10 +1,10 @@
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { EnabledMediaModel } from '@shumai/dtos'
import { type ToolRegistration as AgentTool } from '@earendil-works/pi-durable'
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
import { Type, type Static, type TSchema } from 'typebox'
import { EnabledMediaModel } from '@shumai/dtos'
import * as fs from 'fs'
import * as path from 'path'
import { Type, type Static, type TSchema } from 'typebox'
import { ulid } from 'ulid'
import { resolveS3MediaBuffer } from './download-asset'
@@ -162,11 +162,11 @@ export function createGenerateVideoTool(
return {
name: 'generate_video',
label: 'Generate Video',
description:
'Generate a video using a configured video model. Supports text-to-video, image-to-video (using an S3 image key from read_asset), first/last frame (using S3 image keys from read_asset), and reference-to-video (using S3 image keys from read_asset). The generated file is saved in the local .pi/ directory.',
parameters: generateVideoSchema,
execute: async (_toolCallId, params) => {
execute: async (params) => {
const p = params as GenerateVideoParams
const defaultModel = `${enabledModels[0].provider}:${enabledModels[0].modelId}`
@@ -280,7 +280,7 @@ export function createGenerateVideoTool(
fs.writeFileSync(targetPath, buffer)
return {
content: [
output: [
{
type: 'text',
text: `Successfully generated video using model "${modelConfig.modelId}" (${modelConfig.provider}) in mode "${p.mode}". Saved to "${relativePath}". Size: ${(buffer.length / (1024 * 1024)).toFixed(2)} MB.`,
+34 -19
View File
@@ -1,15 +1,16 @@
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { vi } from 'vitest'
vi.mock('@shumai/core/src/s3/s3')
vi.mock('fs')
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { s3Service } from '@shumai/core/src/s3/s3'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { createReadSkillTool } from './read-skill'
import { s3Service } from '@shumai/core/src/s3/s3'
import AdmZip from 'adm-zip'
import * as fs from 'fs'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { createReadSkillTool } from './read-skill'
describe('readSkillTool', () => {
setupTestDbHooks()
@@ -21,7 +22,7 @@ describe('readSkillTool', () => {
it('should throw error if skill not found', async () => {
const readSkillTool = createReadSkillTool(undefined, () => {})
await expect(
readSkillTool.execute('1', { skillId: 'non-existent' }, undefined, undefined),
invokeTool(readSkillTool, '1', { skillId: 'non-existent' }, undefined, undefined),
).rejects.toThrow('not found')
})
@@ -45,7 +46,7 @@ describe('readSkillTool', () => {
})
const readSkillTool = createReadSkillTool(undefined, () => {})
const result = await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
const result = await invokeTool(readSkillTool, '1', { skillId: skill.id }, undefined, undefined)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toBe('# Test Skill Content')
@@ -97,7 +98,7 @@ describe('readSkillTool', () => {
})
const readSkillTool = createReadSkillTool(undefined, () => {})
const result = await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
const result = await invokeTool(readSkillTool, '1', { skillId: skill.id }, undefined, undefined)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toBe('# Extracted Content')
@@ -144,7 +145,7 @@ describe('readSkillTool', () => {
const readSkillTool = createReadSkillTool(undefined, (envs) => {
capturedEnvs = { ...capturedEnvs, ...envs }
})
await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
await invokeTool(readSkillTool, '1', { skillId: skill.id }, undefined, undefined)
expect(capturedEnvs).toEqual({
CONFIGURED_VAR: 'user-val',
@@ -179,7 +180,7 @@ describe('readSkillTool', () => {
const readSkillTool = createReadSkillTool(undefined, (envs) => {
capturedEnvs = { ...capturedEnvs, ...envs }
})
await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
await invokeTool(readSkillTool, '1', { skillId: skill.id }, undefined, undefined)
expect(capturedEnvs).toEqual({
OVERRIDDEN_VAR: 'user-val',
@@ -214,7 +215,7 @@ describe('readSkillTool', () => {
const readSkillTool = createReadSkillTool(undefined, (envs) => {
capturedEnvs = { ...capturedEnvs, ...envs }
})
await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
await invokeTool(readSkillTool, '1', { skillId: skill.id }, undefined, undefined)
expect(capturedEnvs).toEqual({
FALLBACK_VAR: 'host-val',
@@ -249,7 +250,7 @@ describe('readSkillTool', () => {
const readSkillTool = createReadSkillTool(undefined, (envs) => {
capturedEnvs = { ...capturedEnvs, ...envs }
})
await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
await invokeTool(readSkillTool, '1', { skillId: skill.id }, undefined, undefined)
expect(capturedEnvs).toEqual({
FALLBACK_VAR_UNDEF: 'host-val2',
@@ -293,7 +294,8 @@ describe('readSkillTool', () => {
})
const ownerTool = createReadSkillTool(ownerUser.id, () => {})
const resultOwner = await ownerTool.execute(
const resultOwner = await invokeTool(
ownerTool,
'1',
{ skillId: ownerSkill.id },
undefined,
@@ -304,7 +306,7 @@ describe('readSkillTool', () => {
const reviewerTool = createReadSkillTool(reviewerUser.id, () => {})
await expect(
reviewerTool.execute('1', { skillId: ownerSkill.id }, undefined, undefined),
invokeTool(reviewerTool, '1', { skillId: ownerSkill.id }, undefined, undefined),
).rejects.toThrow('Permission denied')
})
@@ -340,7 +342,7 @@ describe('readSkillTool', () => {
project.id,
)
await expect(
demotedTool.execute('1', { skillId: editorSkill.id }, undefined, undefined),
invokeTool(demotedTool, '1', { skillId: editorSkill.id }, undefined, undefined),
).rejects.toThrow('Permission denied')
// Project-scoped member invited as editor: allowed
@@ -369,7 +371,8 @@ describe('readSkillTool', () => {
undefined,
project.id,
)
const result = await projEditorTool.execute(
const result = await invokeTool(
projEditorTool,
'1',
{ skillId: editorSkill.id },
undefined,
@@ -402,7 +405,7 @@ describe('readSkillTool', () => {
const onSkillLoaded = vi.fn()
const readSkillTool = createReadSkillTool(undefined, () => {}, onSkillLoaded)
await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
await invokeTool(readSkillTool, '1', { skillId: skill.id }, undefined, undefined)
expect(onSkillLoaded).toHaveBeenCalledTimes(1)
})
@@ -428,7 +431,7 @@ describe('readSkillTool', () => {
const onSkillLoaded = vi.fn()
const reviewerTool = createReadSkillTool(reviewerUser.id, () => {}, onSkillLoaded)
await expect(
reviewerTool.execute('1', { skillId: ownerSkill.id }, undefined, undefined),
invokeTool(reviewerTool, '1', { skillId: ownerSkill.id }, undefined, undefined),
).rejects.toThrow('Permission denied')
expect(onSkillLoaded).not.toHaveBeenCalled()
@@ -451,7 +454,7 @@ describe('readSkillTool', () => {
'some-other-enabled-skill',
])
await expect(
readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined),
invokeTool(readSkillTool, '1', { skillId: skill.id }, undefined, undefined),
).rejects.toThrow('not enabled for this agent')
})
@@ -475,7 +478,13 @@ describe('readSkillTool', () => {
})
const readSkillTool = createReadSkillTool(undefined, () => {}, undefined, [skill.id])
const result = await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
const result = await invokeTool(
readSkillTool,
'1',
{ skillId: skill.id },
undefined,
undefined,
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toBe('# Enabled For Agent Skill')
})
@@ -500,7 +509,13 @@ describe('readSkillTool', () => {
})
const readSkillTool = createReadSkillTool(undefined, () => {})
const result = await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
const result = await invokeTool(
readSkillTool,
'1',
{ skillId: skill.id },
undefined,
undefined,
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toBe('# No Filter Skill')
})
+6 -6
View File
@@ -1,8 +1,8 @@
import { prisma } from '@shumai/db'
import { Type } from 'typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { type ToolRegistration as AgentTool } from '@earendil-works/pi-durable'
import { agentService } from '@shumai/core/src/agent/agent'
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
import { prisma } from '@shumai/db'
import { Type } from 'typebox'
const readSkillSchema = Type.Object({
skillId: Type.String({ description: 'The ID of the skill to read' }),
@@ -22,10 +22,10 @@ export const createReadSkillTool = (
projectId?: string,
): AgentTool<typeof readSkillSchema, { skillId: string }> => ({
name: 'read_skill',
label: 'Read Agent Skill',
description: 'Downloads and reads an agent skill to understand how to use it.',
parameters: readSkillSchema,
execute: async (_toolCallId, params) => {
execute: async (params) => {
const skill = await prisma.skill.findUnique({
where: { id: params.skillId },
})
@@ -71,7 +71,7 @@ export const createReadSkillTool = (
await onSkillLoaded?.()
return {
content: [{ type: 'text', text: skillMdContent }],
output: [{ type: 'text', text: skillMdContent }],
details: { skillId: params.skillId },
}
},
@@ -1,6 +1,7 @@
import { describe, it, expect } from 'vitest'
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { describe, expect, it } from 'vitest'
import { createReadThreadTool } from './read-thread'
/**
@@ -45,7 +46,7 @@ describe('read_thread authorization', () => {
const a = await seedTeamWithThread('a')
const tool = createReadThreadTool({ userId: a.author.id, teamId: a.team.id })
const result = await tool.execute('call-1', { threadId: a.thread.id })
const result = await invokeTool(tool, 'call-1', { threadId: a.thread.id })
const text = (result.content[0] as { text: string }).text
expect(text).toContain('secret message a')
@@ -58,7 +59,7 @@ describe('read_thread authorization', () => {
const tool = createReadThreadTool({ userId: a.author.id, teamId: a.team.id })
await expect(tool.execute('call-1', { threadId: b.thread.id })).rejects.toThrow(
await expect(invokeTool(tool, 'call-1', { threadId: b.thread.id })).rejects.toThrow(
'User is not a member of the team',
)
})
@@ -74,7 +75,7 @@ describe('read_thread authorization', () => {
const tool = createReadThreadTool({ userId: outsider.id, teamId: b.team.id })
await expect(tool.execute('call-1', { threadId: b.thread.id })).rejects.toThrow()
await expect(invokeTool(tool, 'call-1', { threadId: b.thread.id })).rejects.toThrow()
})
it('confines a system agent (no user) to threads in its own team', async () => {
@@ -83,9 +84,11 @@ describe('read_thread authorization', () => {
const tool = createReadThreadTool({ teamId: a.team.id })
const own = await tool.execute('call-1', { threadId: a.thread.id })
const own = await invokeTool(tool, 'call-1', { threadId: a.thread.id })
expect((own.content[0] as { text: string }).text).toContain('secret message a')
await expect(tool.execute('call-2', { threadId: b.thread.id })).rejects.toThrow('Access denied')
await expect(invokeTool(tool, 'call-2', { threadId: b.thread.id })).rejects.toThrow(
'Access denied',
)
})
})
+10 -9
View File
@@ -1,7 +1,8 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createReadThreadTool } from './read-thread'
import { prisma } from '@shumai/db'
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { authzService } from '@shumai/core/src/authz/authz'
import { prisma } from '@shumai/db'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createReadThreadTool } from './read-thread'
vi.mock('@shumai/core/src/authz/authz', () => ({
authzService: {
@@ -37,7 +38,7 @@ describe('createReadThreadTool', () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue(null)
const tool = createReadThreadTool({ userId: 'user-1', teamId: 'team-1' })
const result = await tool.execute('call-1', { threadId: 'non-existent' })
const result = await invokeTool(tool, 'call-1', { threadId: 'non-existent' })
const textContent = (result.content[0] as { text: string }).text
expect(textContent).toContain('Comment thread with ID "non-existent" not found.')
@@ -49,7 +50,7 @@ describe('createReadThreadTool', () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue({ id: 'asset-1' } as any)
const tool = createReadThreadTool({ userId: 'user-1', teamId: 'team-1' })
const result = await tool.execute('call-asset', { threadId: 'asset-1' })
const result = await invokeTool(tool, 'call-asset', { threadId: 'asset-1' })
const textContent = (result.content[0] as { text: string }).text
expect(textContent).toContain('ID "asset-1" is an Asset ID, not a Comment Thread ID')
@@ -68,7 +69,7 @@ describe('createReadThreadTool', () => {
vi.mocked(prisma.assetComment.findMany).mockResolvedValue([])
const tool = createReadThreadTool({ userId: 'user-1', teamId: 'team-1' })
const result = await tool.execute('call-2', { threadId: 'root-1' })
const result = await invokeTool(tool, 'call-2', { threadId: 'root-1' })
const textContent = (result.content[0] as { text: string }).text
expect(authzService.hasPermission).toHaveBeenCalledWith({
@@ -107,7 +108,7 @@ describe('createReadThreadTool', () => {
] as any)
const tool = createReadThreadTool({ userId: 'user-1', teamId: 'team-1' })
const result = await tool.execute('call-3', { threadId: 'root-1' })
const result = await invokeTool(tool, 'call-3', { threadId: 'root-1' })
const textContent = (result.content[0] as { text: string }).text
expect(textContent).toContain(
@@ -139,7 +140,7 @@ describe('createReadThreadTool', () => {
] as any)
const tool = createReadThreadTool({ userId: 'user-1', teamId: 'team-1' })
const result = await tool.execute('call-agent', { threadId: 'root-1' })
const result = await invokeTool(tool, 'call-agent', { threadId: 'root-1' })
const textContent = (result.content[0] as { text: string }).text
expect(textContent).toContain('- [Ai Agent] (id: reply-1, has_markup: false): Agent answer')
@@ -170,7 +171,7 @@ describe('createReadThreadTool', () => {
] as any)
const tool = createReadThreadTool({ userId: 'user-1', teamId: 'team-1' })
const result = await tool.execute('call-3d', { threadId: 'root-3d' })
const result = await invokeTool(tool, 'call-3d', { threadId: 'root-3d' })
const textContent = (result.content[0] as { text: string }).text
expect(textContent).toContain(
+8 -8
View File
@@ -1,10 +1,10 @@
import { prisma, type User } from '@shumai/db'
import { Type } from 'typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { type ToolRegistration as AgentTool } from '@earendil-works/pi-durable'
import { assetService } from '@shumai/core/src/asset/asset'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { secondToDegree } from '@shumai/core/src/utils/model3d'
import { getProxyType } from '@shumai/core/src/utils/mime'
import { secondToDegree } from '@shumai/core/src/utils/model3d'
import { prisma, type User } from '@shumai/db'
import { Type } from 'typebox'
const readThreadSchema = Type.Object({
threadId: Type.String({
@@ -67,10 +67,10 @@ export const createReadThreadTool = (
ctx: ReadThreadToolContext,
): AgentTool<typeof readThreadSchema, { threadId: string }> => ({
name: 'read_thread',
label: 'Read Comment Thread',
description: 'Reads all comments and replies inside a specific comment thread.',
parameters: readThreadSchema,
execute: async (_toolCallId, params) => {
execute: async (params) => {
const rootComment = await prisma.assetComment.findUnique({
where: { id: params.threadId },
include: {
@@ -89,7 +89,7 @@ export const createReadThreadTool = (
: `Comment thread with ID "${params.threadId}" not found.`
return {
content: [{ type: 'text', text: errorText }],
output: [{ type: 'text', text: errorText }],
details: { threadId: params.threadId },
}
}
@@ -127,7 +127,7 @@ export const createReadThreadTool = (
}
return {
content: [{ type: 'text', text: output }],
output: [{ type: 'text', text: output }],
details: { threadId: params.threadId },
}
},
+25 -12
View File
@@ -1,9 +1,10 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createSandboxedBashTool } from './sandboxed-bash'
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { spawn } from 'node:child_process'
import { EventEmitter } from 'node:events'
import { readFile } from 'node:fs/promises'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createSandboxedBashTool } from './sandboxed-bash'
vi.mock('@anthropic-ai/sandbox-runtime')
vi.mock('node:child_process')
@@ -57,7 +58,8 @@ describe('createSandboxedBashTool', () => {
const signal = createMockSignal()
// pi-coding-agent AgentTool.execute signature: (toolCallId, params, signal?, onUpdate?)
const executePromise = tool.execute(
const executePromise = invokeTool(
tool,
'1',
{ command: 'echo hello', source: 'user' },
signal,
@@ -97,7 +99,7 @@ describe('createSandboxedBashTool', () => {
const signal = createMockSignal()
await expect(
tool.execute('1', { command: 'echo hack', source: 'user' }, signal, createMockOnUpdate()),
invokeTool(tool, '1', { command: 'echo hack', source: 'user' }, signal, createMockOnUpdate()),
).rejects.toThrow(/not permitted for your role/)
expect(spawn).not.toHaveBeenCalled()
@@ -119,7 +121,7 @@ describe('createSandboxedBashTool', () => {
;(spawn as any).mockReturnValue(mockChild)
const signal = createMockSignal()
const executePromise = tool.execute('1', { command: 'echo skill', source: 'skill' }, signal)
const executePromise = invokeTool(tool, '1', { command: 'echo skill', source: 'skill' }, signal)
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
expect(SandboxManager.wrapWithSandbox).toHaveBeenCalledWith(
@@ -145,7 +147,8 @@ describe('createSandboxedBashTool', () => {
;(spawn as any).mockReturnValue(mockChild)
const signal = createMockSignal()
const executePromise = tool.execute(
const executePromise = invokeTool(
tool,
'1',
{ command: 'fail', source: 'user' },
signal,
@@ -169,7 +172,8 @@ describe('createSandboxedBashTool', () => {
;(spawn as any).mockReturnValue(mockChild)
const signal = createMockSignal()
const executePromise = tool.execute(
const executePromise = invokeTool(
tool,
'1',
{ command: 'exit 1', source: 'user' },
signal,
@@ -198,7 +202,8 @@ describe('createSandboxedBashTool', () => {
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true as any)
const signal = createMockSignal()
const executePromise = tool.execute(
const executePromise = invokeTool(
tool,
'1',
{ command: 'sleep 10', timeout: 2, source: 'user' },
signal,
@@ -232,7 +237,8 @@ describe('createSandboxedBashTool', () => {
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true as any)
const signal = createMockSignal()
const executePromise = tool.execute(
const executePromise = invokeTool(
tool,
'1',
{ command: 'long-run', source: 'user' },
signal,
@@ -266,7 +272,12 @@ describe('createSandboxedBashTool', () => {
;(spawn as any).mockReturnValue(mockChild)
const signal = createMockSignal()
const executePromise = tool.execute('1', { command: 'generate lines', source: 'user' }, signal)
const executePromise = invokeTool(
tool,
'1',
{ command: 'generate lines', source: 'user' },
signal,
)
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
@@ -308,7 +319,8 @@ describe('createSandboxedBashTool', () => {
;(spawn as any).mockReturnValue(mockChild)
const signal = createMockSignal()
const executePromise = tool.execute(
const executePromise = invokeTool(
tool,
'1',
{ command: 'long single line', source: 'user' },
signal,
@@ -342,7 +354,8 @@ describe('createSandboxedBashTool', () => {
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true as any)
const signal = createMockSignal()
const executePromise = tool.execute(
const executePromise = invokeTool(
tool,
'1',
{ command: 'slow', timeout: 1, source: 'user' },
signal,
+16 -59
View File
@@ -1,8 +1,13 @@
import {
type ToolRegistration as AgentTool,
type ToolExecutionResult as AgentToolResult,
} from '@earendil-works/pi-durable'
import { logger } from '@shumai/core/src/logger'
import { quotaService } from '@shumai/core/src/quota/quota-service'
import { sandboxService } from '@shumai/core/src/sandbox/sandbox-service'
import { type AgentTool, type AgentToolResult } from '@earendil-works/pi-agent-core'
import { Type } from 'typebox'
import type { TeamMemberRole } from '@shumai/db'
import { spawn } from 'node:child_process'
import { Type } from 'typebox'
import { OutputAccumulator } from '../utils/output-accumulator'
import {
DEFAULT_MAX_BYTES,
@@ -10,8 +15,6 @@ import {
formatSize,
type TruncationResult,
} from '../utils/truncate'
import { quotaService } from '@shumai/core/src/quota/quota-service'
import type { TeamMemberRole } from '@shumai/db'
const BashSource = Type.String({
enum: ['user', 'skill'],
@@ -28,7 +31,7 @@ const BashParameters = Type.Object({
source: BashSource,
})
export interface BashDetails {
export type BashDetails = {
exitCode: number | null
truncation?: TruncationResult
fullOutputPath?: string
@@ -47,8 +50,6 @@ export interface SandboxedBashOptions {
restrictedUser?: boolean
}
const BASH_UPDATE_THROTTLE_MS = 100
export const createSandboxedBashTool = (
cwd: string,
skillEnvs: Record<string, string> = {},
@@ -57,14 +58,15 @@ export const createSandboxedBashTool = (
return {
name: 'bash',
description: `Execute a bash command in a sandboxed environment. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds. When in a restricted (non-owner) user context, only commands required by a skill loaded via the read_skill tool are allowed, and you must set source="skill".`,
label: 'Executing bash command',
parameters: BashParameters,
outputLimits: { maxBytes: DEFAULT_MAX_BYTES, maxLines: DEFAULT_MAX_LINES, retain: 'tail' },
execute: async (
toolCallId,
{ command, timeout, source },
signal,
onUpdate,
api,
context,
): Promise<AgentToolResult<BashDetails>> => {
const toolCallId = api.callId
const signal = context.abortSignal
if (options?.restrictedUser && source !== 'skill') {
throw new Error(
'Bash commands requested directly by the user (source="user") are not permitted for your role. ' +
@@ -88,62 +90,17 @@ export const createSandboxedBashTool = (
const output = new OutputAccumulator({ tempFilePrefix: 'shumai-bash' })
let acceptingOutput = true
let updateTimer: NodeJS.Timeout | undefined
let updateDirty = false
let lastUpdateAt = 0
const emitOutputUpdate = () => {
if (!onUpdate || !updateDirty) return
updateDirty = false
lastUpdateAt = Date.now()
const snapshot = output.snapshot({ persistIfTruncated: true })
onUpdate({
content: [{ type: 'text', text: snapshot.content || '' }],
details: {
exitCode: null,
truncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,
fullOutputPath: snapshot.fullOutputPath,
},
})
}
const clearUpdateTimer = () => {
if (updateTimer) {
clearTimeout(updateTimer)
updateTimer = undefined
}
}
const scheduleOutputUpdate = () => {
if (!onUpdate) return
updateDirty = true
const delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt)
if (delay <= 0) {
clearUpdateTimer()
emitOutputUpdate()
return
}
updateTimer ??= setTimeout(() => {
updateTimer = undefined
emitOutputUpdate()
}, delay)
}
if (onUpdate) {
onUpdate({ content: [], details: { exitCode: null } })
}
await api.details({ exitCode: null }, context)
const handleData = (data: Buffer) => {
if (!acceptingOutput) return
output.append(data)
scheduleOutputUpdate()
api.output(data)
}
const finishOutput = async () => {
acceptingOutput = false
output.finish()
clearUpdateTimer()
emitOutputUpdate()
const snapshot = output.snapshot({ persistIfTruncated: true })
await output.closeTempFile()
return snapshot
@@ -284,7 +241,7 @@ export const createSandboxedBashTool = (
)
} else {
resolve({
content: [
output: [
{
type: 'text',
text: outputText,
+1 -1
View File
@@ -1,7 +1,7 @@
export const DEFAULT_MAX_LINES = 2000
export const DEFAULT_MAX_BYTES = 50 * 1024 // 50KB
export interface TruncationResult {
export type TruncationResult = {
content: string
truncated: boolean
truncatedBy: 'lines' | 'bytes' | null
@@ -108,6 +108,7 @@ describe('Agent Autofill Workflow', () => {
// Verify AI autofill called with asset details and mapped fields
expect(mockActivities.autofillAiActivity).toHaveBeenCalledWith({
taskId: task.id,
teamId: 't1',
assetId: 'a1',
assetName: 'test.png',
@@ -1,10 +1,10 @@
import { getProxyType } from '@shumai/core/src/utils/mime'
import type { WorkflowTask } from '@shumai/db'
import {
ApplicationFailure,
updateTaskStatusActivity,
updateTaskUsageActivity,
} from '@shumai/workflow-core'
import { getProxyType } from '@shumai/core/src/utils/mime'
import {
autofillAiActivity,
createCommentActivity,
@@ -64,6 +64,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
: undefined
const aiResult = await autofillAiActivity({
taskId: task.id,
teamId,
assetId: asset.id,
assetName: asset.name,