2026-05-28 09:57:30 +08:00
import { ApplicationFailure } from '@temporalio/workflow'
2026-06-01 23:16:22 +08:00
import type { WorkflowTask } from '@shumai/db'
2026-06-01 23:29:11 +08:00
import { executeActivity , getActivities , TaskQueueAgent , TaskQueueDb } from '@shumai/workflow-core'
2026-05-19 16:05:09 +08:00
2026-05-27 23:40:14 +08:00
export async function agentChat ( task : WorkflowTask ) : Promise < void > {
2026-05-19 16:05:09 +08:00
const {
updateTaskStatusActivity ,
getAssetActivity ,
getCommentActivity ,
2026-05-27 23:40:14 +08:00
getAgentChatContextActivity ,
agentChatActivity ,
2026-05-19 16:05:09 +08:00
createCommentActivity ,
updateCommentActivity ,
updateTaskUsageActivity ,
getAgentWorkerQueueActivity ,
2026-05-21 22:51:40 +08:00
deleteCommentActivity ,
2026-05-22 09:49:22 +08:00
initializeAgentSessionActivity ,
2026-05-30 17:09:18 +08:00
getAssetPathContextActivity ,
2026-05-19 16:05:09 +08:00
} = getActivities ()
let placeholderCommentId : string | undefined
try {
// Update status to processing
await executeActivity ( TaskQueueDb , updateTaskStatusActivity , {
taskId : task.id ,
status : 'processing' ,
})
2026-05-28 09:48:05 +08:00
const payload = task . payload
2026-05-28 09:57:30 +08:00
if ( ! payload ) {
throw ApplicationFailure . create ({ message : 'Task payload is missing' , nonRetryable : true })
}
2026-05-19 16:05:09 +08:00
2026-05-28 09:48:05 +08:00
const agentId = payload . agent ? . agentId
2026-05-28 09:57:30 +08:00
if ( ! agentId ) {
throw ApplicationFailure . create ({ message : 'agentId missing in payload' , nonRetryable : true })
}
2026-05-28 09:48:05 +08:00
let sessionId = payload . agent ? . sessionId
2026-05-21 22:51:40 +08:00
2026-05-19 16:05:09 +08:00
// 1. Get User Comment
2026-05-28 09:48:05 +08:00
const userCommentId = payload . agent ? . userCommentId
2026-05-28 09:57:30 +08:00
if ( ! userCommentId ) {
throw ApplicationFailure . create ({
message : 'userCommentId missing in payload' ,
nonRetryable : true ,
})
}
2026-05-19 16:05:09 +08:00
const userComment = await executeActivity ( TaskQueueDb , getCommentActivity , userCommentId )
2026-05-28 09:57:30 +08:00
if ( ! userComment ) {
throw ApplicationFailure . create ({ message : 'User comment not found' , nonRetryable : true })
}
2026-05-19 16:05:09 +08:00
// 2. Create Placeholder Comment
const placeholder = await executeActivity ( TaskQueueDb , createCommentActivity , {
assetId : task.assetId ,
message : '__CHAT__' ,
2026-05-21 22:51:40 +08:00
sessionId : sessionId || 'pending' ,
2026-05-28 09:48:05 +08:00
agentId : agentId ,
2026-05-19 16:05:09 +08:00
replyToId : userComment.replyToId ?? userComment . id ,
})
placeholderCommentId = placeholder . id
// 3. Get Asset
const asset = await executeActivity ( TaskQueueDb , getAssetActivity , task . assetId )
if ( ! asset || ! asset . project ) {
2026-05-28 09:57:30 +08:00
throw ApplicationFailure . create ({ message : 'Asset or project not found' , nonRetryable : true })
2026-05-19 16:05:09 +08:00
}
const teamId = asset . project . teamId
2026-05-22 09:49:22 +08:00
// 4. Initialize Session if missing (Database Activity on db_queue)
if ( ! sessionId ) {
sessionId = await executeActivity ( TaskQueueDb , initializeAgentSessionActivity , {
teamId ,
2026-05-28 09:48:05 +08:00
agentId : agentId ,
2026-05-22 09:49:22 +08:00
userCommentId ,
2026-05-28 09:48:05 +08:00
userId : payload.agent?.userId ,
2026-05-22 09:49:22 +08:00
})
}
2026-05-27 23:40:14 +08:00
// 4b. Fetch Agent Context (Database Activity on db_queue)
const context = await executeActivity ( TaskQueueDb , getAgentChatContextActivity , {
teamId ,
2026-05-28 09:48:05 +08:00
agentId : agentId ,
2026-05-27 23:40:14 +08:00
})
2026-05-22 09:49:22 +08:00
// 5. Prepare Images (Attachments only)
2026-05-19 16:05:09 +08:00
const attachmentImageUrls : string [] = []
2026-05-28 09:48:05 +08:00
if ( userComment ? . attachments ) {
for ( const att of userComment . attachments ) {
if ( att . asset ? . mediaType ? . startsWith ( 'image/' ) && att . asset ? . storageKey ? . key ) {
attachmentImageUrls . push ( att . asset . storageKey . key )
2026-05-19 16:05:09 +08:00
}
}
}
2026-05-30 17:09:18 +08:00
const pathContext = await executeActivity (
TaskQueueDb ,
getAssetPathContextActivity ,
task . assetId ,
)
2026-05-19 16:05:09 +08:00
let instruction = `The user is discussing an asset with ID: ${ asset . id } .`
2026-05-30 17:09:18 +08:00
if ( pathContext ) {
instruction += ` \ n \ nAsset Path Context: \ n ${ pathContext } `
}
2026-05-19 16:05:09 +08:00
if ( asset . media ) {
instruction += ` \ n \ nAsset Media Info: \ n ${ JSON . stringify ( asset . media , null , 2 ) } `
}
instruction += ` \ n \ nIf you need to view the asset's media content (frames/images/video), call the 'analyze_asset_media' tool by passing the appropriate 'key' from the Asset Media Info above. Choose the most suitable format based on your capabilities and the user's request (e.g., use a poster or sprite for quick visual checks, or a transcode/raw file for detailed analysis).`
2026-05-28 09:48:05 +08:00
if ( payload . agent ? . explicitMention ) {
2026-05-21 22:51:40 +08:00
instruction += ` \ n \ nThe user explicitly mentioned you in their message. You MUST reply to this message.`
} else {
instruction += ` \ n \ nThe user did not explicitly mention you, but is replying in a thread where you are the participant. Let's decide if you should reply or not. If the user is not directly addressing you or doesn't need a response from you, you may choose to not reply. To choose not to reply, respond with exactly and only the text: __NO_REPLY__.`
}
2026-05-22 09:49:22 +08:00
// 6. Call AI Chat
2026-05-19 16:05:09 +08:00
let folderId = ''
if ( asset . type === 'folder' ) {
folderId = asset . id
} else if ( asset . parentId ) {
folderId = asset . parentId
}
const agentWorkerQueue = await executeActivity ( TaskQueueAgent , getAgentWorkerQueueActivity )
2026-05-27 23:40:14 +08:00
const aiResult = await executeActivity ( agentWorkerQueue , agentChatActivity , {
2026-05-19 16:05:09 +08:00
teamId ,
2026-05-28 09:48:05 +08:00
agentId : agentId ,
2026-05-19 16:05:09 +08:00
message : userComment.message || '' ,
imageUrls : attachmentImageUrls ,
projectId : payload.projectId ,
folderId ,
agentsInstruction : instruction ,
2026-05-21 22:51:40 +08:00
sessionId ,
2026-05-28 09:48:05 +08:00
userId : payload.agent?.userId ,
explicitMention : payload.agent?.explicitMention ,
2026-05-27 23:40:14 +08:00
context ,
2026-05-19 16:05:09 +08:00
})
2026-05-22 09:49:22 +08:00
// 7. Update Placeholder Comment
2026-05-19 16:05:09 +08:00
if ( placeholderCommentId ) {
2026-05-21 22:51:40 +08:00
if ( aiResult . text . trim () === '__NO_REPLY__' ) {
await executeActivity ( TaskQueueDb , deleteCommentActivity , placeholderCommentId )
} else {
await executeActivity ( TaskQueueDb , updateCommentActivity , {
commentId : placeholderCommentId ,
message : aiResult.text ,
sessionId : aiResult.sessionId ,
})
}
2026-05-19 16:05:09 +08:00
}
2026-05-22 09:49:22 +08:00
// 8. Update Usage
2026-05-19 16:05:09 +08:00
if ( aiResult . usage ) {
await executeActivity ( TaskQueueDb , updateTaskUsageActivity , {
taskId : task.id ,
inputTokens : aiResult.usage.inputTokens ,
outputTokens : aiResult.usage.outputTokens ,
model : aiResult.usage.model ,
})
}
// Update status to completed
await executeActivity ( TaskQueueDb , updateTaskStatusActivity , {
taskId : task.id ,
status : 'completed' ,
output : { sessionId : aiResult.sessionId },
})
} catch ( err ) {
2026-05-27 23:40:14 +08:00
console . error ( `AgentChat failed for task ${ task . id } :` , err )
2026-05-19 16:05:09 +08:00
// Update placeholder comment with error message
if ( placeholderCommentId ) {
try {
const errorMessage =
err instanceof Error && err . message . startsWith ( 'AI error:' )
? `AI error: ${ err . message . substring ( 9 ) } `
: 'Sorry, I encountered an error while processing your request.'
await executeActivity ( TaskQueueDb , updateCommentActivity , {
commentId : placeholderCommentId ,
message : errorMessage ,
})
} catch ( commentErr ) {
console . error ( 'Failed to update error comment:' , commentErr )
}
}
// Update status to failed
await executeActivity ( TaskQueueDb , updateTaskStatusActivity , {
taskId : task.id ,
status : 'failed' ,
output : { error : err instanceof Error ? err.message : String ( err ) },
})
throw err
}
}
2026-05-27 23:40:14 +08:00
export const agentChatWorkflow = agentChat