mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-29 04:14:30 +00:00
refactor(workflow): eliminate worker-db package and simplify workflows
This commit is contained in:
@@ -1,11 +1,21 @@
|
||||
import { createAgentSession, fieldsToTypeBoxSchema, type AutofillField } from '../index'
|
||||
import { DatabaseSessionStorage } from '../database-session-storage'
|
||||
import type { Prisma, Skill } from '@shumai/db'
|
||||
import { prisma, AssetType, Prisma, type Skill } from '@shumai/db'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { type AgentTool, type AgentMessage, type SessionTreeEntry } from '@earendil-works/pi-agent-core'
|
||||
import { type ImageContent } from '@earendil-works/pi-ai'
|
||||
import { ApplicationFailure } from '@temporalio/activity'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { VersionStackService } from '@shumai/core/src/versionStack/versionStack'
|
||||
import { uploadService } from '@shumai/core/src/upload/upload'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||
import { paginateQuery, encodeCursor } from '@shumai/core/src/pagination'
|
||||
import { ulid } from 'ulid'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
|
||||
import { UpdateAssetMetadataRequest } from '@shumai/dtos'
|
||||
|
||||
export interface Usage {
|
||||
inputTokens: number
|
||||
@@ -244,3 +254,846 @@ export async function autofillAiActivity(params: AutofillAiParams) {
|
||||
sessionId,
|
||||
}
|
||||
}
|
||||
|
||||
export 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',
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Create a new AgentSession
|
||||
const newSession = await prisma.agentSession.create({
|
||||
data: {
|
||||
agentId,
|
||||
userId: params.userId || null,
|
||||
cwd: process.cwd(),
|
||||
},
|
||||
})
|
||||
const sessionId = newSession.id
|
||||
|
||||
// Fetch existing comments as context
|
||||
let existingComments: Array<{
|
||||
id: string
|
||||
message: string | null
|
||||
createdAt: Date
|
||||
creatorId: string | null
|
||||
creator: { type: string; name: string } | null
|
||||
sessionId: string | null
|
||||
}> = []
|
||||
|
||||
const userComment = await prisma.assetComment.findUnique({
|
||||
where: { id: params.userCommentId },
|
||||
include: { creator: true },
|
||||
})
|
||||
|
||||
if (userComment) {
|
||||
if (!userComment.replyToId) {
|
||||
// Rule 1: outside of a reply, add all other comments on that asset
|
||||
existingComments = await prisma.assetComment.findMany({
|
||||
where: {
|
||||
assetId: userComment.assetId,
|
||||
id: { not: userComment.id },
|
||||
},
|
||||
orderBy: { id: 'asc' },
|
||||
include: { creator: true },
|
||||
})
|
||||
} else {
|
||||
// Rule 2: in a reply, add root comment + all other replies to it
|
||||
const rootComment = await prisma.assetComment.findUnique({
|
||||
where: { id: userComment.replyToId },
|
||||
include: { creator: true },
|
||||
})
|
||||
if (rootComment) {
|
||||
const replies = await prisma.assetComment.findMany({
|
||||
where: {
|
||||
replyToId: rootComment.id,
|
||||
id: { not: userComment.id },
|
||||
},
|
||||
orderBy: { id: 'asc' },
|
||||
include: { creator: true },
|
||||
})
|
||||
existingComments = [rootComment, ...replies]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve user mentions from IDs to names
|
||||
const mentionRegex = /<@([^>]+)>/g
|
||||
const mentionedUserIds = new Set<string>()
|
||||
for (const c of existingComments) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Save context as AgentSessionEntry records
|
||||
let prevId: string | null = null
|
||||
for (const c of existingComments) {
|
||||
const isAgent = c.creator?.type === 'agent' || c.sessionId !== null
|
||||
let messageContent = c.message || ''
|
||||
|
||||
// Replace <@USER_ID> with <@USER_NAME>
|
||||
messageContent = messageContent.replace(mentionRegex, (match, userId) => {
|
||||
const resolvedName = userIdToNameMap.get(userId)
|
||||
return resolvedName ? `<@${resolvedName}>` : match
|
||||
})
|
||||
|
||||
if (isAgent) {
|
||||
const agentName = c.creator?.name || 'Ai Agent'
|
||||
messageContent = `[Agent Message][${agentName}]: ${messageContent}`
|
||||
} else if (c.creator?.name) {
|
||||
messageContent = `[${c.creator.name}]: ${messageContent}`
|
||||
}
|
||||
|
||||
const entryId = ulid()
|
||||
const message: AgentMessage = {
|
||||
role: 'user',
|
||||
content: [{ type: 'text', text: messageContent }],
|
||||
timestamp: c.createdAt.getTime(),
|
||||
}
|
||||
|
||||
const entryJson: SessionTreeEntry = {
|
||||
type: 'message',
|
||||
id: entryId,
|
||||
parentId: prevId,
|
||||
timestamp: c.createdAt.toISOString(),
|
||||
message,
|
||||
}
|
||||
|
||||
await prisma.agentSessionEntry.create({
|
||||
data: {
|
||||
id: entryId,
|
||||
sessionId,
|
||||
entry: entryJson as unknown as PrismaJson.PiSessionEntry,
|
||||
},
|
||||
})
|
||||
prevId = entryId
|
||||
}
|
||||
|
||||
// Update leafId of the session
|
||||
if (prevId) {
|
||||
await prisma.agentSession.update({
|
||||
where: { id: sessionId },
|
||||
data: { leafId: prevId },
|
||||
})
|
||||
}
|
||||
|
||||
return sessionId
|
||||
}
|
||||
|
||||
export async function deleteCommentActivity(commentId: string) {
|
||||
return prisma.assetComment.delete({
|
||||
where: { id: commentId },
|
||||
})
|
||||
}
|
||||
|
||||
export async function createCommentActivity(params: {
|
||||
assetId: string
|
||||
message: string
|
||||
sessionId?: string | null
|
||||
agentId?: string | null
|
||||
replyToId?: string | null
|
||||
}) {
|
||||
if (params.sessionId) {
|
||||
const agentId = params.agentId && params.agentId !== 'default' ? params.agentId : 'default'
|
||||
|
||||
// Fetch teamId from asset
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
include: { project: true },
|
||||
})
|
||||
if (!asset || !asset.project) {
|
||||
throw ApplicationFailure.create({ message: 'asset or project not found', nonRetryable: true })
|
||||
}
|
||||
const teamId = asset.project.teamId
|
||||
|
||||
// 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,
|
||||
type: 'chat',
|
||||
config: {
|
||||
provider: 'openai',
|
||||
model: 'gpt-4',
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure agent session exists
|
||||
const sessionExists = await prisma.agentSession.findUnique({ where: { id: params.sessionId } })
|
||||
if (!sessionExists) {
|
||||
await prisma.agentSession.create({
|
||||
data: {
|
||||
id: params.sessionId,
|
||||
agentId: agentId,
|
||||
cwd: process.cwd(),
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: params.assetId,
|
||||
message: params.message,
|
||||
sessionId: params.sessionId ?? null,
|
||||
creatorId: params.agentId && params.agentId !== 'default' ? params.agentId : null,
|
||||
replyToId: params.replyToId,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateCommentActivity(params: {
|
||||
commentId: string
|
||||
message: string
|
||||
sessionId?: string | null
|
||||
}) {
|
||||
return prisma.assetComment.update({
|
||||
where: { id: params.commentId },
|
||||
data: {
|
||||
message: params.message,
|
||||
...(params.sessionId !== undefined ? { sessionId: params.sessionId } : {}),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export async function getAgentChatContextActivity(params: {
|
||||
teamId: string
|
||||
agentId: string
|
||||
}): Promise<AgentExecutionContext> {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: params.teamId },
|
||||
})
|
||||
if (!team) {
|
||||
throw ApplicationFailure.create({ message: 'failed to get team', nonRetryable: true })
|
||||
}
|
||||
|
||||
const agent = await prisma.agent.findUnique({
|
||||
where: { id: params.agentId },
|
||||
include: {
|
||||
provider: true,
|
||||
modelRef: true,
|
||||
},
|
||||
})
|
||||
if (!agent) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `agent ${params.agentId} not found`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
const providerName = agent.provider.name
|
||||
|
||||
// Fetch the required provider configuration from database
|
||||
const dbProviders = await prisma.provider.findMany({
|
||||
where: { teamId: params.teamId, name: providerName },
|
||||
include: { models: true },
|
||||
})
|
||||
|
||||
// Fetch team skills
|
||||
const teamSkills = await prisma.skill.findMany({
|
||||
where: { teamId: params.teamId },
|
||||
})
|
||||
|
||||
const sandbox = await prisma.sandbox.findUnique({
|
||||
where: { teamId: params.teamId },
|
||||
})
|
||||
const allowedDomains = sandbox?.allowedDomains || []
|
||||
|
||||
return {
|
||||
agent,
|
||||
dbProviders,
|
||||
teamSkills,
|
||||
allowedDomains,
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAgentAutofillContextActivity(params: {
|
||||
teamId: string
|
||||
}): Promise<AgentExecutionContext> {
|
||||
const agent = await prisma.agent.findFirst({
|
||||
where: {
|
||||
type: 'autofill',
|
||||
enabled: true,
|
||||
teamId: params.teamId,
|
||||
},
|
||||
})
|
||||
if (!agent) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'no autofill agent found for team',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: params.teamId },
|
||||
})
|
||||
if (!team) {
|
||||
throw ApplicationFailure.create({ message: 'failed to get team', nonRetryable: true })
|
||||
}
|
||||
|
||||
// Find provider/model configuration
|
||||
const agentWithDetails = await prisma.agent.findUnique({
|
||||
where: { id: agent.id },
|
||||
include: {
|
||||
provider: true,
|
||||
modelRef: true,
|
||||
},
|
||||
})
|
||||
if (!agentWithDetails) {
|
||||
throw ApplicationFailure.create({ message: `agent ${agent.id} not found`, nonRetryable: true })
|
||||
}
|
||||
if (!agentWithDetails.provider) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'agent has no provider configured',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
if (!agentWithDetails.modelRef) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'agent has no model configured',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const providerName = agentWithDetails.provider.name
|
||||
|
||||
// Fetch the required provider configuration from database
|
||||
const dbProviders = await prisma.provider.findMany({
|
||||
where: { teamId: params.teamId, name: providerName },
|
||||
include: { models: true },
|
||||
})
|
||||
|
||||
// Fetch team skills
|
||||
const teamSkills = await prisma.skill.findMany({
|
||||
where: { teamId: params.teamId },
|
||||
})
|
||||
|
||||
const sandbox = await prisma.sandbox.findUnique({
|
||||
where: { teamId: params.teamId },
|
||||
})
|
||||
const allowedDomains = sandbox?.allowedDomains || []
|
||||
|
||||
return {
|
||||
agent: agentWithDetails,
|
||||
dbProviders,
|
||||
teamSkills,
|
||||
allowedDomains,
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAssetActivity(assetId: string) {
|
||||
return prisma.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
include: {
|
||||
storageKey: true,
|
||||
project: {
|
||||
include: {
|
||||
team: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export async function getCommentActivity(commentId: string) {
|
||||
return prisma.assetComment.findUnique({
|
||||
where: { id: commentId },
|
||||
include: { attachments: { include: { asset: { include: { storageKey: true } } } } },
|
||||
})
|
||||
}
|
||||
|
||||
export async function getProjectAutofillFieldsActivity(projectId: string) {
|
||||
const fields = await metadataService.listProjectFields('', projectId)
|
||||
return fields.filter((f) => f.field.aiAutofill).map((f) => f.field)
|
||||
}
|
||||
|
||||
export async function updateAssetMetadataActivity(params: {
|
||||
assetId: string
|
||||
metadata: UpdateAssetMetadataRequest[]
|
||||
}) {
|
||||
return metadataService.updateAssetMetadata(params.assetId, params.metadata)
|
||||
}
|
||||
|
||||
export async function getAssetPathContextActivity(assetId: string): Promise<string> {
|
||||
const parts: { name: string; id: string }[] = []
|
||||
let currentId: string | null = assetId
|
||||
|
||||
while (currentId) {
|
||||
/* prettier-ignore */
|
||||
const assetNode = (await prisma.asset.findUnique({
|
||||
where: { id: currentId },
|
||||
select: { id: true, name: true, parentId: true, type: true },
|
||||
})) as { id: string; name: string; parentId: string | null; type: AssetType } | null
|
||||
if (!assetNode) break
|
||||
|
||||
if (assetNode.name) {
|
||||
parts.unshift({ name: assetNode.name, id: assetNode.id })
|
||||
}
|
||||
|
||||
currentId = assetNode.parentId
|
||||
}
|
||||
|
||||
if (parts.length === 0) return ''
|
||||
|
||||
const pathStr = parts.map((p) => p.name).join('/')
|
||||
let contextStr = `Path: ${pathStr}\n\n`
|
||||
for (const part of parts) {
|
||||
contextStr += `name: ${part.name}, id: ${part.id}\n`
|
||||
}
|
||||
|
||||
return contextStr
|
||||
}
|
||||
|
||||
export interface ExecuteAgentToolParams {
|
||||
taskId: string
|
||||
toolName: string
|
||||
// args are dynamic JSON arguments passed from the agent harness at runtime
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
args: any
|
||||
userId?: string
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export async function executeAgentToolActivity(params: ExecuteAgentToolParams): Promise<any> {
|
||||
const { toolName, args, userId } = params
|
||||
if (!userId) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'User ID is required for tool authz',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// 1. Fetch User
|
||||
const user = await prisma.user.findUnique({ where: { id: userId } })
|
||||
if (!user) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `User not found: ${userId}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// 2. Perform Authz and Action based on toolName
|
||||
switch (toolName) {
|
||||
case 'list_assets': {
|
||||
const parent = args.parent
|
||||
if (!parent) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'parent parameter is required',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Authz check
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: parent,
|
||||
})
|
||||
|
||||
const page = args.page || 1
|
||||
const pageSize = args.pageSize || 20
|
||||
const type = args.type || 'all'
|
||||
|
||||
// We need to list files and folders of parent dir
|
||||
const where: Prisma.AssetWhereInput = {
|
||||
parentId: parent,
|
||||
isDeleted: false,
|
||||
}
|
||||
if (type === 'file') {
|
||||
where.type = { in: ['file', 'version_stack'] }
|
||||
} else if (type === 'folder') {
|
||||
where.type = 'folder'
|
||||
} else {
|
||||
where.type = { in: ['file', 'folder', 'version_stack'] }
|
||||
}
|
||||
|
||||
const limit = pageSize
|
||||
const offset = (page - 1) * limit
|
||||
const after = offset > 0 ? encodeCursor(offset) : undefined
|
||||
|
||||
const { data: assets, pageInfo } = await paginateQuery<
|
||||
Prisma.AssetGetPayload<Record<string, never>>
|
||||
>(
|
||||
async (skip, take) => {
|
||||
return prisma.asset.findMany({
|
||||
where,
|
||||
orderBy: { id: 'desc' }, // sort desc per ULID default in sorting guidelines!
|
||||
skip,
|
||||
take,
|
||||
})
|
||||
},
|
||||
async () => prisma.asset.count({ where }),
|
||||
{ first: limit, after, includeCount: true },
|
||||
)
|
||||
|
||||
// return asset id, asset name, asset type, asset size (sizeByte or size)
|
||||
const results = assets.map((a) => ({
|
||||
id: a.id,
|
||||
name: a.name,
|
||||
type: a.type,
|
||||
size: a.sizeByte,
|
||||
}))
|
||||
|
||||
return {
|
||||
assets: results,
|
||||
pageInfo,
|
||||
}
|
||||
}
|
||||
|
||||
case 'create_folder': {
|
||||
const parent = args.parent
|
||||
const name = args.name
|
||||
if (!parent || !name) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'parent and name parameters are required',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Authz check
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: parent,
|
||||
})
|
||||
|
||||
const newFolder = await assetService.createAsset({
|
||||
name,
|
||||
parentId: parent,
|
||||
type: 'folder',
|
||||
creatorId: userId,
|
||||
})
|
||||
|
||||
// Increment fileCount of parent folder
|
||||
await prisma.asset.update({
|
||||
where: { id: parent },
|
||||
data: { fileCount: { increment: 1 } },
|
||||
})
|
||||
|
||||
return {
|
||||
id: newFolder.id,
|
||||
name: newFolder.name,
|
||||
type: newFolder.type,
|
||||
size: newFolder.sizeByte,
|
||||
}
|
||||
}
|
||||
|
||||
case 'create_file': {
|
||||
const parent = args.parent
|
||||
const s3Key = args.s3Key as string
|
||||
const name = args.name as string
|
||||
const fileSize = args.size as number
|
||||
const mimeType = args.contentType as string
|
||||
if (!parent || !s3Key || !name || fileSize === undefined || !mimeType) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'parent, s3Key, name, size, and contentType parameters are required',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Authz check
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: parent,
|
||||
})
|
||||
|
||||
// Fetch parent folder to resolve projectId and teamId
|
||||
const parentAsset = await prisma.asset.findUnique({
|
||||
where: { id: parent },
|
||||
include: { project: true },
|
||||
})
|
||||
if (!parentAsset) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Parent folder not found with ID: ${parent}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
if (!parentAsset.projectId || !parentAsset.project?.teamId) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Parent folder ${parent} has no project or team associated`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Create asset via assetService
|
||||
const newFile = await assetService.createAsset({
|
||||
name,
|
||||
type: 'file',
|
||||
parentId: parent,
|
||||
key: s3Key,
|
||||
sizeByte: fileSize,
|
||||
contentType: mimeType,
|
||||
creatorId: userId,
|
||||
})
|
||||
|
||||
// Increment fileCount of parent and update ancestor size
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.asset.update({
|
||||
where: { id: parent },
|
||||
data: { fileCount: { increment: 1 } },
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await assetService.updateAncestorsSize(tx as any, parent, fileSize)
|
||||
|
||||
// Trigger post-upload transcode and AI workflows
|
||||
await uploadService.triggerPostUploadWorkflows(
|
||||
tx,
|
||||
newFile.id,
|
||||
parentAsset.project!.teamId,
|
||||
parentAsset.projectId!,
|
||||
)
|
||||
})
|
||||
|
||||
return {
|
||||
id: newFile.id,
|
||||
name: newFile.name,
|
||||
type: newFile.type,
|
||||
size: newFile.sizeByte,
|
||||
}
|
||||
}
|
||||
|
||||
case 'create_version': {
|
||||
const parent = args.parent // parent file id
|
||||
const s3Key = args.s3Key as string
|
||||
const name = args.name as string
|
||||
const fileSize = args.size as number
|
||||
const mimeType = args.contentType as string
|
||||
if (!parent || !s3Key || !name || fileSize === undefined || !mimeType) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'parent, s3Key, name, size, and contentType parameters are required',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Fetch parent file and cast to any due to Prisma type resolution limits
|
||||
/* prettier-ignore */
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const parentFile = (await prisma.asset.findUnique({ where: { id: parent }, include: { parent: true, project: true } })) as any
|
||||
if (!parentFile) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Parent file not found with ID: ${parent}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
if (!parentFile.projectId || !parentFile.project?.teamId) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Parent file ${parent} has no project or team associated`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Authz check: verify Edit permission on the parent file (resource ID is parent file id)
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: parent,
|
||||
})
|
||||
|
||||
// If already in a version stack
|
||||
if (parentFile.parentId && parentFile.parent?.type === AssetType.version_stack) {
|
||||
const stackId = parentFile.parentId
|
||||
|
||||
// Create the new file asset
|
||||
const newFile = await assetService.createAsset({
|
||||
name,
|
||||
type: 'file',
|
||||
parentId: stackId,
|
||||
key: s3Key,
|
||||
sizeByte: fileSize,
|
||||
contentType: mimeType,
|
||||
creatorId: userId,
|
||||
})
|
||||
|
||||
// Generate sort index for new version inside the stack (newest gets the lowest sortIndex)
|
||||
const firstChild = await prisma.asset.findFirst({
|
||||
where: {
|
||||
parentId: stackId,
|
||||
NOT: { id: newFile.id },
|
||||
},
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
})
|
||||
const newSortIndex = generateKeyBetween(null, firstChild?.sortIndex || null)
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
// Assign sort index
|
||||
await tx.asset.update({
|
||||
where: { id: newFile.id },
|
||||
data: { sortIndex: newSortIndex },
|
||||
})
|
||||
// Increment stack's fileCount and size
|
||||
const updatedStack = await tx.asset.update({
|
||||
where: { id: stackId },
|
||||
data: {
|
||||
fileCount: { increment: 1 },
|
||||
sizeByte: { increment: fileSize },
|
||||
},
|
||||
})
|
||||
// Update ancestors' size of stack's parent
|
||||
if (updatedStack.parentId) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await assetService.updateAncestorsSize(tx as any, updatedStack.parentId, fileSize)
|
||||
}
|
||||
|
||||
// Trigger post-upload transcode and AI workflows
|
||||
await uploadService.triggerPostUploadWorkflows(
|
||||
tx,
|
||||
newFile.id,
|
||||
parentFile.project.teamId,
|
||||
parentFile.projectId,
|
||||
)
|
||||
})
|
||||
|
||||
return {
|
||||
id: newFile.id,
|
||||
name: newFile.name,
|
||||
type: newFile.type,
|
||||
size: newFile.sizeByte,
|
||||
}
|
||||
} else {
|
||||
// Parent is a regular file. We must create a new version stack.
|
||||
const folderParentId = parentFile.parentId
|
||||
if (!folderParentId) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Parent file ${parent} has no parent folder`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Create the new file asset under parent folder first (so that createVersionStack can run on them,
|
||||
// which enforces both files must have same parent initially)
|
||||
const newFile = await assetService.createAsset({
|
||||
name,
|
||||
type: 'file',
|
||||
parentId: folderParentId,
|
||||
key: s3Key,
|
||||
sizeByte: fileSize,
|
||||
contentType: mimeType,
|
||||
creatorId: userId,
|
||||
})
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const txVersionStackService = new VersionStackService(tx as any)
|
||||
await txVersionStackService.createVersionStack({
|
||||
fileIds: [newFile.id, parentFile.id],
|
||||
projectId: parentFile.projectId!,
|
||||
creatorId: userId,
|
||||
})
|
||||
// Update ancestors' size (add size of the new file version)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await assetService.updateAncestorsSize(tx as any, folderParentId!, fileSize)
|
||||
|
||||
// Trigger post-upload transcode and AI workflows
|
||||
await uploadService.triggerPostUploadWorkflows(
|
||||
tx,
|
||||
newFile.id,
|
||||
parentFile.project.teamId,
|
||||
parentFile.projectId!,
|
||||
)
|
||||
})
|
||||
|
||||
return {
|
||||
id: newFile.id,
|
||||
name: newFile.name,
|
||||
type: newFile.type,
|
||||
size: newFile.sizeByte,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
throw ApplicationFailure.create({
|
||||
message: `Unsupported tool name: ${toolName}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import * as os from 'os'
|
||||
import * as path from 'path'
|
||||
import { promisify } from 'util'
|
||||
import { ApplicationFailure } from '@temporalio/activity'
|
||||
import { prisma } from '@shumai/db'
|
||||
|
||||
const execAsync = promisify(exec)
|
||||
|
||||
@@ -259,3 +260,69 @@ export async function extractAiMetadataActivity(
|
||||
|
||||
return generatedFiles
|
||||
}
|
||||
|
||||
export async function getEmbeddingContextActivity(params: {
|
||||
teamId: string
|
||||
assetId: string
|
||||
}) {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: params.teamId },
|
||||
})
|
||||
if (!team) {
|
||||
throw ApplicationFailure.create({ message: 'failed to get team', nonRetryable: true })
|
||||
}
|
||||
|
||||
const agent = await prisma.agent.findFirst({
|
||||
where: {
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
user: { teamMembers: { some: { teamId: params.teamId } } },
|
||||
},
|
||||
})
|
||||
if (!agent) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'embedding feature is disabled or agent not found',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
if (!asset) {
|
||||
throw ApplicationFailure.create({ message: 'failed to get asset', nonRetryable: true })
|
||||
}
|
||||
if (!asset.mediaType) {
|
||||
throw ApplicationFailure.create({ message: 'asset has no media type', nonRetryable: true })
|
||||
}
|
||||
|
||||
return {
|
||||
agent,
|
||||
asset,
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveAssetEmbeddingsActivity(params: {
|
||||
assetId: string
|
||||
embeddings: Array<{
|
||||
embedding: number[]
|
||||
startTime?: number
|
||||
endTime?: number
|
||||
}>
|
||||
}) {
|
||||
for (const item of params.embeddings) {
|
||||
const embVec = JSON.stringify(item.embedding)
|
||||
if (item.startTime !== undefined && item.endTime !== undefined) {
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, NOW())
|
||||
`
|
||||
} else {
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, NOW())
|
||||
`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ import type { WorkflowTask } from '@shumai/db'
|
||||
import {
|
||||
getActivities,
|
||||
executeActivity,
|
||||
TaskQueueDb,
|
||||
TaskQueueAgent,
|
||||
TaskQueueTranscode,
|
||||
} from '@shumai/workflow-core'
|
||||
@@ -32,14 +31,14 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
|
||||
try {
|
||||
// Update status to processing
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
// 0. Create Placeholder Comment
|
||||
const payload = task.payload
|
||||
const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, {
|
||||
const placeholder = await executeActivity(TaskQueueAgent, createCommentActivity, {
|
||||
assetId: task.assetId,
|
||||
message: '__AUTOFILL__',
|
||||
sessionId: payload?.agent?.sessionId || task.id,
|
||||
@@ -48,7 +47,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
placeholderCommentId = placeholder.id
|
||||
|
||||
// 1. Get Asset
|
||||
const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId)
|
||||
const asset = await executeActivity(TaskQueueAgent, getAssetActivity, task.assetId)
|
||||
const key = asset?.storageKey?.key
|
||||
if (!asset || !asset.project || !key) {
|
||||
throw ApplicationFailure.create({ message: 'Asset or project not found', nonRetryable: true })
|
||||
@@ -81,12 +80,12 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
if (generatedFiles.length === 0) {
|
||||
// If no images could be extracted, we can't do much
|
||||
if (placeholderCommentId) {
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: 'Autofill completed: No images could be extracted for analysis.',
|
||||
})
|
||||
}
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
@@ -94,23 +93,23 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// 3. Get Project Autofill Fields
|
||||
const fields = await executeActivity(TaskQueueDb, getProjectAutofillFieldsActivity, projectId)
|
||||
const fields = await executeActivity(TaskQueueAgent, getProjectAutofillFieldsActivity, projectId)
|
||||
if (fields.length === 0) {
|
||||
if (placeholderCommentId) {
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: 'Autofill completed: No autofill fields defined in project.',
|
||||
})
|
||||
}
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 3b. Fetch Agent Context (Database Activity on db_queue)
|
||||
const context = await executeActivity(TaskQueueDb, getAgentAutofillContextActivity, {
|
||||
// 3b. Fetch Agent Context
|
||||
const context = await executeActivity(TaskQueueAgent, getAgentAutofillContextActivity, {
|
||||
teamId,
|
||||
})
|
||||
|
||||
@@ -132,7 +131,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
|
||||
if (aiResult.usage) {
|
||||
// Update Usage
|
||||
await executeActivity(TaskQueueDb, updateTaskUsageActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateTaskUsageActivity, {
|
||||
taskId: task.id,
|
||||
inputTokens: aiResult.usage.inputTokens,
|
||||
outputTokens: aiResult.usage.outputTokens,
|
||||
@@ -148,7 +147,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
}))
|
||||
|
||||
if (metadataUpdates.length > 0) {
|
||||
await executeActivity(TaskQueueDb, updateAssetMetadataActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateAssetMetadataActivity, {
|
||||
assetId: asset.id,
|
||||
metadata: metadataUpdates,
|
||||
})
|
||||
@@ -156,7 +155,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// 7. Update Placeholder Comment
|
||||
if (placeholderCommentId) {
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: 'Autofill completed successfully.',
|
||||
sessionId: aiResult.sessionId,
|
||||
@@ -164,7 +163,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// Update status to completed
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
@@ -174,7 +173,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId) {
|
||||
try {
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: `Autofill failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
})
|
||||
@@ -184,7 +183,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// Update status to failed
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { ApplicationFailure } from '@temporalio/workflow'
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import { executeActivity, getActivities, TaskQueueAgent, TaskQueueDb } from '@shumai/workflow-core'
|
||||
import { executeActivity, getActivities, TaskQueueAgent } from '@shumai/workflow-core'
|
||||
|
||||
export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
@@ -22,7 +22,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
|
||||
try {
|
||||
// Update status to processing
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
@@ -47,13 +47,13 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
const userComment = await executeActivity(TaskQueueDb, getCommentActivity, userCommentId)
|
||||
const userComment = await executeActivity(TaskQueueAgent, getCommentActivity, userCommentId)
|
||||
if (!userComment) {
|
||||
throw ApplicationFailure.create({ message: 'User comment not found', nonRetryable: true })
|
||||
}
|
||||
|
||||
// 2. Create Placeholder Comment
|
||||
const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, {
|
||||
const placeholder = await executeActivity(TaskQueueAgent, createCommentActivity, {
|
||||
assetId: task.assetId,
|
||||
message: '__CHAT__',
|
||||
sessionId: sessionId || 'pending',
|
||||
@@ -63,15 +63,15 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
placeholderCommentId = placeholder.id
|
||||
|
||||
// 3. Get Asset
|
||||
const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId)
|
||||
const asset = await executeActivity(TaskQueueAgent, getAssetActivity, task.assetId)
|
||||
if (!asset || !asset.project) {
|
||||
throw ApplicationFailure.create({ message: 'Asset or project not found', nonRetryable: true })
|
||||
}
|
||||
const teamId = asset.project.teamId
|
||||
|
||||
// 4. Initialize Session if missing (Database Activity on db_queue)
|
||||
// 4. Initialize Session if missing
|
||||
if (!sessionId) {
|
||||
sessionId = await executeActivity(TaskQueueDb, initializeAgentSessionActivity, {
|
||||
sessionId = await executeActivity(TaskQueueAgent, initializeAgentSessionActivity, {
|
||||
teamId,
|
||||
agentId: agentId,
|
||||
userCommentId,
|
||||
@@ -79,8 +79,8 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
})
|
||||
}
|
||||
|
||||
// 4b. Fetch Agent Context (Database Activity on db_queue)
|
||||
const context = await executeActivity(TaskQueueDb, getAgentChatContextActivity, {
|
||||
// 4b. Fetch Agent Context
|
||||
const context = await executeActivity(TaskQueueAgent, getAgentChatContextActivity, {
|
||||
teamId,
|
||||
agentId: agentId,
|
||||
})
|
||||
@@ -96,7 +96,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
const pathContext = await executeActivity(
|
||||
TaskQueueDb,
|
||||
TaskQueueAgent,
|
||||
getAssetPathContextActivity,
|
||||
task.assetId,
|
||||
)
|
||||
@@ -145,9 +145,9 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
// 7. Update Placeholder Comment
|
||||
if (placeholderCommentId) {
|
||||
if (aiResult.text.trim() === '__NO_REPLY__') {
|
||||
await executeActivity(TaskQueueDb, deleteCommentActivity, placeholderCommentId)
|
||||
await executeActivity(TaskQueueAgent, deleteCommentActivity, placeholderCommentId)
|
||||
} else {
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: aiResult.text,
|
||||
sessionId: aiResult.sessionId,
|
||||
@@ -157,7 +157,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// 8. Update Usage
|
||||
if (aiResult.usage) {
|
||||
await executeActivity(TaskQueueDb, updateTaskUsageActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateTaskUsageActivity, {
|
||||
taskId: task.id,
|
||||
inputTokens: aiResult.usage.inputTokens,
|
||||
outputTokens: aiResult.usage.outputTokens,
|
||||
@@ -166,7 +166,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// Update status to completed
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
output: { sessionId: aiResult.sessionId },
|
||||
@@ -182,7 +182,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
? `AI error: ${err.message.substring(9)}`
|
||||
: 'Sorry, I encountered an error while processing your request.'
|
||||
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: errorMessage,
|
||||
})
|
||||
@@ -192,7 +192,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// Update status to failed
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { ApplicationFailure } from '@temporalio/workflow'
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import { getActivities, executeActivity, TaskQueueDb, TaskQueueAgent } from '@shumai/workflow-core'
|
||||
import { getActivities, executeActivity, TaskQueueAgent } from '@shumai/workflow-core'
|
||||
|
||||
export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
@@ -18,14 +18,14 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
|
||||
try {
|
||||
// Update status to processing
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
// 0. Create Placeholder Comment
|
||||
const payload = task.payload
|
||||
const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, {
|
||||
const placeholder = await executeActivity(TaskQueueAgent, createCommentActivity, {
|
||||
assetId: task.assetId,
|
||||
message: '__EMBEDDING__',
|
||||
sessionId: payload?.agent?.sessionId || task.id,
|
||||
@@ -37,8 +37,8 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
throw ApplicationFailure.create({ message: 'Task has no teamId', nonRetryable: true })
|
||||
}
|
||||
|
||||
// 1. Fetch Agent Context (Database Activity on db_queue)
|
||||
const context = await executeActivity(TaskQueueDb, getEmbeddingContextActivity, {
|
||||
// 1. Fetch Agent Context
|
||||
const context = await executeActivity(TaskQueueAgent, getEmbeddingContextActivity, {
|
||||
teamId: task.teamId,
|
||||
assetId: task.assetId,
|
||||
})
|
||||
@@ -54,7 +54,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// Save computed embeddings
|
||||
if (result.embeddings.length > 0) {
|
||||
await executeActivity(TaskQueueDb, saveAssetEmbeddingsActivity, {
|
||||
await executeActivity(TaskQueueAgent, saveAssetEmbeddingsActivity, {
|
||||
assetId: task.assetId,
|
||||
embeddings: result.embeddings,
|
||||
})
|
||||
@@ -62,7 +62,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// Update Usage
|
||||
if (result.usage) {
|
||||
await executeActivity(TaskQueueDb, updateTaskUsageActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateTaskUsageActivity, {
|
||||
taskId: task.id,
|
||||
inputTokens: result.usage.inputTokens,
|
||||
outputTokens: result.usage.outputTokens,
|
||||
@@ -72,14 +72,14 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// 7. Update Placeholder Comment
|
||||
if (placeholderCommentId) {
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: 'Embedding completed successfully.',
|
||||
})
|
||||
}
|
||||
|
||||
// Update status to completed
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
@@ -89,7 +89,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId) {
|
||||
try {
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: `Embedding failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
})
|
||||
@@ -99,7 +99,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// Update status to failed
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { ApplicationFailure } from '@temporalio/workflow'
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import { getActivities, executeActivity, TaskQueueDb } from '@shumai/workflow-core'
|
||||
import { getActivities, executeActivity, TaskQueueAgent } from '@shumai/workflow-core'
|
||||
|
||||
export async function agentToolCall(task: WorkflowTask): Promise<void> {
|
||||
const { updateTaskStatusActivity, executeAgentToolActivity } = getActivities()
|
||||
|
||||
try {
|
||||
// Update status to processing
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
@@ -22,8 +22,8 @@ export async function agentToolCall(task: WorkflowTask): Promise<void> {
|
||||
|
||||
const { toolName, args, userId } = payload.agentToolCall
|
||||
|
||||
// Execute the database activity on db_queue
|
||||
const result = await executeActivity(TaskQueueDb, executeAgentToolActivity, {
|
||||
// Execute the agent activity on agent_queue
|
||||
const result = await executeActivity(TaskQueueAgent, executeAgentToolActivity, {
|
||||
taskId: task.id,
|
||||
toolName,
|
||||
args,
|
||||
@@ -31,7 +31,7 @@ export async function agentToolCall(task: WorkflowTask): Promise<void> {
|
||||
})
|
||||
|
||||
// Update status to completed with output
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
output: result,
|
||||
@@ -40,7 +40,7 @@ export async function agentToolCall(task: WorkflowTask): Promise<void> {
|
||||
console.error(`AgentToolCall failed for task ${task.id}:`, err)
|
||||
|
||||
// Update status to failed
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import { getActivities, executeActivity, TaskQueueDb } from '@shumai/workflow-core'
|
||||
import { getActivities, executeActivity, TaskQueueAgent } from '@shumai/workflow-core'
|
||||
|
||||
export async function queryEmbeddingForSearch(task: WorkflowTask): Promise<void> {
|
||||
const { generateTextEmbeddingActivity, updateWorkflowTaskActivity } = getActivities()
|
||||
@@ -13,20 +13,20 @@ export async function queryEmbeddingForSearch(task: WorkflowTask): Promise<void>
|
||||
|
||||
try {
|
||||
// 1. Mark as processing
|
||||
await executeActivity(TaskQueueDb, updateWorkflowTaskActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateWorkflowTaskActivity, {
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
heartbeat: true,
|
||||
})
|
||||
|
||||
// 2. Generate embedding
|
||||
const result = await generateTextEmbeddingActivity({
|
||||
const result = await executeActivity(TaskQueueAgent, generateTextEmbeddingActivity, {
|
||||
text,
|
||||
teamId: task.teamId!,
|
||||
})
|
||||
|
||||
// 3. Save output and complete
|
||||
await executeActivity(TaskQueueDb, updateWorkflowTaskActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateWorkflowTaskActivity, {
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
output: { embedding: result.embedding },
|
||||
@@ -36,7 +36,7 @@ export async function queryEmbeddingForSearch(task: WorkflowTask): Promise<void>
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(`queryEmbeddingForSearch failed for task ${task.id}:`, err)
|
||||
await executeActivity(TaskQueueDb, updateWorkflowTaskActivity, {
|
||||
await executeActivity(TaskQueueAgent, updateWorkflowTaskActivity, {
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: {
|
||||
|
||||
Reference in New Issue
Block a user