|
| 1 | +import { createLogger } from '@sim/logger' |
| 2 | +import type { BlockOutput } from '@/blocks/types' |
| 3 | +import { BlockType } from '@/executor/constants' |
| 4 | +import type { BlockHandler, ExecutionContext } from '@/executor/types' |
| 5 | +import { buildAPIUrl, buildAuthHeaders, extractAPIErrorMessage } from '@/executor/utils/http' |
| 6 | +import type { SerializedBlock } from '@/serializer/types' |
| 7 | + |
| 8 | +const logger = createLogger('MothershipBlockHandler') |
| 9 | + |
| 10 | +/** |
| 11 | + * Handler for Mothership blocks that proxy requests to the Mothership AI agent. |
| 12 | + * |
| 13 | + * Unlike the Agent block (which calls LLM providers directly), the Mothership |
| 14 | + * block delegates to the full Mothership infrastructure: main agent, subagents, |
| 15 | + * integration tools, memory, and workspace context. |
| 16 | + */ |
| 17 | +export class MothershipBlockHandler implements BlockHandler { |
| 18 | + canHandle(block: SerializedBlock): boolean { |
| 19 | + return block.metadata?.id === BlockType.MOTHERSHIP |
| 20 | + } |
| 21 | + |
| 22 | + async execute( |
| 23 | + ctx: ExecutionContext, |
| 24 | + block: SerializedBlock, |
| 25 | + inputs: Record<string, any> |
| 26 | + ): Promise<BlockOutput> { |
| 27 | + const messages = this.resolveMessages(inputs) |
| 28 | + const responseFormat = this.parseResponseFormat(inputs.responseFormat) |
| 29 | + |
| 30 | + const memoryType = inputs.memoryType || 'none' |
| 31 | + const chatId = |
| 32 | + memoryType === 'conversation' && inputs.conversationId |
| 33 | + ? inputs.conversationId |
| 34 | + : crypto.randomUUID() |
| 35 | + |
| 36 | + const url = buildAPIUrl('/api/mothership/execute') |
| 37 | + const headers = await buildAuthHeaders() |
| 38 | + |
| 39 | + const body: Record<string, unknown> = { |
| 40 | + messages, |
| 41 | + workspaceId: ctx.workspaceId || '', |
| 42 | + userId: ctx.userId || '', |
| 43 | + chatId, |
| 44 | + } |
| 45 | + if (responseFormat) { |
| 46 | + body.responseFormat = responseFormat |
| 47 | + } |
| 48 | + |
| 49 | + logger.info('Executing Mothership block', { |
| 50 | + blockId: block.id, |
| 51 | + messageCount: messages.length, |
| 52 | + hasResponseFormat: !!responseFormat, |
| 53 | + memoryType, |
| 54 | + hasConversationId: memoryType === 'conversation', |
| 55 | + }) |
| 56 | + |
| 57 | + const response = await fetch(url.toString(), { |
| 58 | + method: 'POST', |
| 59 | + headers, |
| 60 | + body: JSON.stringify(body), |
| 61 | + }) |
| 62 | + |
| 63 | + if (!response.ok) { |
| 64 | + const errorMsg = await extractAPIErrorMessage(response) |
| 65 | + throw new Error(`Mothership execution failed: ${errorMsg}`) |
| 66 | + } |
| 67 | + |
| 68 | + const result = await response.json() |
| 69 | + |
| 70 | + if (responseFormat && result.content) { |
| 71 | + return this.processStructuredResponse(result) |
| 72 | + } |
| 73 | + |
| 74 | + return { |
| 75 | + content: result.content || '', |
| 76 | + model: result.model || 'mothership', |
| 77 | + tokens: result.tokens || {}, |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + private resolveMessages( |
| 82 | + inputs: Record<string, any> |
| 83 | + ): Array<{ role: string; content: string }> { |
| 84 | + const raw = inputs.messages |
| 85 | + if (!raw) { |
| 86 | + throw new Error('Messages input is required for the Mothership block') |
| 87 | + } |
| 88 | + |
| 89 | + let messages: unknown[] |
| 90 | + if (typeof raw === 'string') { |
| 91 | + try { |
| 92 | + messages = JSON.parse(raw) |
| 93 | + } catch { |
| 94 | + throw new Error('Messages must be a valid JSON array') |
| 95 | + } |
| 96 | + } else if (Array.isArray(raw)) { |
| 97 | + messages = raw |
| 98 | + } else { |
| 99 | + throw new Error('Messages must be an array of {role, content} objects') |
| 100 | + } |
| 101 | + |
| 102 | + return messages.map((msg: any, i: number) => { |
| 103 | + if (!msg.role || typeof msg.content !== 'string') { |
| 104 | + throw new Error( |
| 105 | + `Message at index ${i} must have "role" (string) and "content" (string)` |
| 106 | + ) |
| 107 | + } |
| 108 | + return { role: String(msg.role), content: msg.content } |
| 109 | + }) |
| 110 | + } |
| 111 | + |
| 112 | + private parseResponseFormat(responseFormat?: string | object): any { |
| 113 | + if (!responseFormat || responseFormat === '') return undefined |
| 114 | + |
| 115 | + if (typeof responseFormat === 'object') return responseFormat |
| 116 | + |
| 117 | + if (typeof responseFormat === 'string') { |
| 118 | + const trimmed = responseFormat.trim() |
| 119 | + if (!trimmed) return undefined |
| 120 | + if (trimmed.startsWith('<') || trimmed.startsWith('{{')) return undefined |
| 121 | + try { |
| 122 | + return JSON.parse(trimmed) |
| 123 | + } catch { |
| 124 | + logger.warn('Failed to parse responseFormat as JSON', { |
| 125 | + preview: trimmed.slice(0, 100), |
| 126 | + }) |
| 127 | + return undefined |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + return undefined |
| 132 | + } |
| 133 | + |
| 134 | + private processStructuredResponse(result: any): BlockOutput { |
| 135 | + const content = result.content |
| 136 | + try { |
| 137 | + const parsed = JSON.parse(content.trim()) |
| 138 | + return { |
| 139 | + ...parsed, |
| 140 | + model: result.model || 'mothership', |
| 141 | + tokens: result.tokens || {}, |
| 142 | + } |
| 143 | + } catch { |
| 144 | + logger.warn('Failed to parse structured response, returning raw content') |
| 145 | + return { |
| 146 | + content, |
| 147 | + model: result.model || 'mothership', |
| 148 | + tokens: result.tokens || {}, |
| 149 | + } |
| 150 | + } |
| 151 | + } |
| 152 | +} |
0 commit comments