2026-05-27 23:40:14 +08:00
import { createAgentSession , fieldsToTypeBoxSchema , type AutofillField } from '@/agent'
2026-05-28 11:43:42 +08:00
import { DatabaseSessionStorage } from '@/agent/database-session-storage'
2026-06-01 23:16:22 +08:00
import type { Prisma , Skill } from '@shumai/db'
2026-05-27 23:40:14 +08:00
import { logger } from '@/logger'
2026-06-01 23:16:22 +08:00
import { s3Service } from '@shumai/core/src/s3/s3'
2026-05-27 23:40:14 +08:00
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { type ImageContent } from '@earendil-works/pi-ai'
2026-05-28 10:43:54 +08:00
import { ApplicationFailure } from '@temporalio/activity'
2026-05-28 14:55:59 +08:00
export interface Usage {
inputTokens : number
outputTokens : number
model : string
}
2026-05-19 16:05:09 +08:00
2026-05-28 11:43:42 +08:00
export type AgentWithProviderAndModel = Prisma . AgentGetPayload < {
include : {
provider : true
modelRef : true
}
} >
export type DbProviderWithModels = Prisma . ProviderGetPayload < {
include : {
models : true
}
} >
export interface AgentExecutionContext {
agent : AgentWithProviderAndModel
dbProviders : DbProviderWithModels []
teamSkills : Skill []
2026-05-27 23:40:14 +08:00
allowedDomains : string []
}
async function executeAgentPrompt ( params : {
2026-05-19 16:05:09 +08:00
teamId : string
2026-05-27 23:40:14 +08:00
agentId : string
prompt : string
2026-05-19 16:05:09 +08:00
images : string []
2026-05-27 23:40:14 +08:00
agentsInstruction : string
sessionId? : string
userId? : string
tools? : AgentTool []
context : AgentExecutionContext
}) : Promise < { text : string ; usage : Usage ; sessionId : string } > {
2026-05-28 11:43:42 +08:00
const { agent , dbProviders , teamSkills , allowedDomains } = params . context
2026-05-27 23:40:14 +08:00
2026-05-28 10:43:54 +08:00
if ( ! agent . provider ) {
throw ApplicationFailure . create ({
message : 'agent has no provider configured' ,
nonRetryable : true ,
})
}
if ( ! agent . modelRef ) {
throw ApplicationFailure . create ({
message : 'agent has no model configured' ,
nonRetryable : true ,
})
}
2026-05-27 23:40:14 +08:00
const providerName = agent . provider . name
const modelId = agent . modelRef . modelId
2026-05-30 18:50:12 +08:00
let systemPrompt = `You are the AI assistant for shumai.
shumai is a professional creative collaboration platform similar to frame.io, where users can upload creative files, manage projects, assign tasks, get precise feedback, and share their work. As the agent, your role is to help users use and manage this platform.
2026-05-30 23:23:25 +08:00
shumai has its own cloud file system. If a user asks you to perform file system operations (for example: creating a folder, creating a file, stacking a version, or listing assets), you MUST use the corresponding agent system tools (e.g., 'create_folder', 'create_file', 'create_version', 'list_assets'). Do NOT use local bash commands or the local bash tool to perform these operations locally on the host environment; all operations must be executed through the platform's cloud file system tools so they are correctly registered and visible within the platform.
If you need to create files in the local filesystem (for example, a temporary file for uploading), only the '.pi' folder in the current directory has write permissions. Do NOT attempt to create files in any other directories.`
2026-05-30 18:50:12 +08:00
if ( agent . soul ) {
systemPrompt = ` ${ systemPrompt } \ n \ nAgent Personality and Core Instructions: \ n ${ agent . soul } `
}
2026-05-27 23:40:14 +08:00
if ( params . agentsInstruction ) {
systemPrompt = ` ${ systemPrompt } \ n \ nContext and Instructions: \ n ${ params . agentsInstruction } `
}
2026-05-28 11:43:42 +08:00
const modelConfig = agent . modelRef ? . config
2026-05-27 23:40:14 +08:00
if ( modelConfig ? . input ) {
systemPrompt += ` \ n \ nYour current model supports the following input types: ${ modelConfig . input . join ( ', ' ) } .`
}
const { session , harness } = await createAgentSession ({
agentId : params.agentId ,
providerName ,
modelId ,
systemPrompt ,
2026-05-28 11:43:42 +08:00
teamSkills : teamSkills.map (( s ) => ({
2026-05-27 23:40:14 +08:00
id : s.id ,
name : s.name ,
description : s.description ,
})),
allowedDomains ,
sessionId : params.sessionId ,
userId : params.userId ,
customTools : params.tools || [],
2026-05-28 11:43:42 +08:00
providers : dbProviders.map (( p ) => ({
2026-05-27 23:40:14 +08:00
name : p.name ,
config : p.config ,
2026-05-28 11:43:42 +08:00
models : p.models.map (( m ) => ({
2026-05-27 23:40:14 +08:00
modelId : m.modelId ,
name : m.name ,
config : m.config ,
})),
})),
})
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 ,
})
}
}
try {
const assistantMessage = await harness . prompt ( params . prompt , { images : imagesToPass })
const sessionEntries = await session . getEntries ()
sessionEntries . forEach (( entry ) => {
if ( entry . type === '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' )
}
}
})
const text = assistantMessage . content
. filter (( c ) => c . type === 'text' )
2026-05-28 11:43:42 +08:00
. map (( c ) => {
if ( 'text' in c && typeof c . text === 'string' ) {
return c . text
}
return ''
})
2026-05-27 23:40:14 +08:00
. join ( '\n' )
const usage : Usage = {
model : modelId ,
inputTokens : assistantMessage.usage?.input || 0 ,
outputTokens : assistantMessage.usage?.output || 0 ,
}
2026-05-28 11:43:42 +08:00
const storage = session . getStorage ()
let sessionId = ''
if ( storage instanceof DatabaseSessionStorage ) {
sessionId = storage . sessionId
}
return { text , usage , sessionId }
2026-05-27 23:40:14 +08:00
} finally {
// Cleanup handled by agent session if needed
}
2026-05-19 16:05:09 +08:00
}
2026-05-27 23:40:14 +08:00
export interface AgentChatParams {
2026-05-19 16:05:09 +08:00
teamId : string
agentId : string
message : string
imageUrls : string []
projectId : string
folderId : string
agentsInstruction? : string
2026-05-22 09:49:22 +08:00
sessionId : string
2026-05-19 16:05:09 +08:00
userId? : string
2026-05-21 22:51:40 +08:00
explicitMention? : boolean
2026-05-27 23:40:14 +08:00
context : AgentExecutionContext
2026-05-19 16:05:09 +08:00
}
2026-05-27 23:40:14 +08:00
export async function agentChatActivity ( params : AgentChatParams ) {
2026-05-19 16:05:09 +08:00
const cleanMessage = params . message . replace ( /<@[A-Z0-9]+>/g , '' ). trim ()
2026-05-22 09:49:22 +08:00
const sessionId = params . sessionId
2026-05-21 22:51:40 +08:00
2026-05-27 23:40:14 +08:00
return executeAgentPrompt ({
teamId : params.teamId ,
agentId : params.agentId ,
prompt : cleanMessage ,
images : params.imageUrls ,
agentsInstruction : params.agentsInstruction || '' ,
2026-05-21 22:51:40 +08:00
sessionId ,
2026-05-27 23:40:14 +08:00
userId : params.userId ,
context : params.context ,
})
}
export interface AutofillAiParams {
teamId : string
images : string []
fields : AutofillField []
context : AgentExecutionContext
}
export async function autofillAiActivity ( params : AutofillAiParams ) {
const prompt = 'Analyze the provided images and extract metadata.'
const toolSchema = fieldsToTypeBoxSchema ( params . fields )
2026-05-28 11:43:42 +08:00
let capturedData : Record < string , unknown > | null = null
2026-05-27 23:40:14 +08:00
const autofillTool : AgentTool = {
name : 'autofill_metadata' ,
label : 'Autofill Metadata' ,
description : 'Extract metadata from the images.' ,
parameters : toolSchema ,
execute : async ( _toolCallId , toolParams ) => {
2026-05-28 11:43:42 +08:00
capturedData = toolParams as Record < string , unknown >
2026-05-27 23:40:14 +08:00
return {
content : [{ type : 'text' , text : 'Metadata captured successfully.' }],
details : {},
}
},
}
const fullPrompt = ` ${ prompt } \ n \ nPlease use the "autofill_metadata" tool to provide the extracted metadata.`
2026-05-28 11:43:42 +08:00
const { agent } = params . context
2026-05-27 23:40:14 +08:00
const { usage , sessionId } = await executeAgentPrompt ({
teamId : params.teamId ,
agentId : agent.id ,
prompt : fullPrompt ,
images : params.images ,
agentsInstruction : '' ,
sessionId : undefined ,
userId : undefined ,
tools : [ autofillTool ],
context : params.context ,
})
return {
text : capturedData ? JSON . stringify ( capturedData ) : '{}' ,
usage ,
sessionId ,
}
2026-05-19 16:05:09 +08:00
}