mirror of
https://github.com/simstudioai/sim.git
synced 2026-11-01 05:20:52 +08:00
* feat(instagram): add Instagram Login OAuth, tools, and block * feat(instagram): add Gmail-style media uploads for publish ops Resolve UserFiles to Meta-fetchable presigned HTTPS URLs (600s TTL) via internal publish routes, and fix OAuth scope storage plus connect-draft wiring so Instagram Login publishing is testable end-to-end. Co-authored-by: Cursor <cursoragent@cursor.com> * refactor(instagram): simplify messaging tools to direct requests, clean up types * fix(instagram): parallelize carousel child polling, enforce 2-10 items, extend poll window and insights periods, use canonical user_id in OAuth callback * fix(instagram): resolve user id from user_id only, accept numeric user_id Co-authored-by: Cursor <cursoragent@cursor.com> * fix(instagram): use form/query params for publish and comment endpoints, request message timestamps explicitly Co-authored-by: Cursor <cursoragent@cursor.com> * fix(instagram): normalize Graph ID outputs to strings so downstream .trim() calls are safe Co-authored-by: Cursor <cursoragent@cursor.com> * style(instagram): use brand gradient tile for the block icon Match the official Instagram look by filling the tile with the orange–pink–purple radial gradient so the white camera glyph sits on a full-bleed brand background. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(instagram): tighten publish defaults and cloud-storage upload UX Default Reel share-to-feed to Yes, drop unused media fields params, share publish transform helpers, and warn when cloud storage is missing for Meta-fetchable uploads. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(instagram): fail closed when cloud storage status is unknown Treat loading/error as blocked for requiresCloudStorage uploads, show the warning once the check finishes, and disable selecting local workspace files Meta cannot fetch. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(instagram): proactively refresh long-lived tokens before expiry Meta only allows refreshing still-valid Instagram tokens, so refresh within 14 days of expiry (after the 24h age gate) instead of waiting until after accessTokenExpiresAt. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(oauth): restore TikTok clientIdParamName JSDoc after merge The staging merge dropped the opening /** on ProviderAuthConfig.clientIdParamName, which broke TypeScript parse in CI. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(api): Zod-contract storage-status and ratchet validation baseline Wire /api/files/storage-status through a shared route contract so the strict API validation audit stays at zero non-Zod routes after the new Instagram cloud-storage check. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(instagram): match Gmail advanced media placeholders Drop public-URL paste hints from advanced fields and the cloud-storage banner so the UI mirrors Gmail attachments. Co-authored-by: Cursor <cursoragent@cursor.com> * code review + hide from toolbar * address comments * fix(instagram): drop hidden Instagram from OAuth catalog pin test Instagram is hideFromToolbar so it is excluded from integrations.json; the pinned slug map must not expect it until the block is visible again. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(instagram): validate client ID before creating connect draft Avoid orphan pending credential drafts when INSTAGRAM_CLIENT_ID is missing, matching the Shopify authorize ordering. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Bill Leoutsakos <billleoutsakos@Bills-MacBook-Pro.local> Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: Vikhyath Mondreti <vikhyath@simstudio.ai>
249 lines
7.5 KiB
TypeScript
249 lines
7.5 KiB
TypeScript
import { createLogger } from '@sim/logger'
|
|
import { toError } from '@sim/utils/errors'
|
|
import { isUserFile } from '@/lib/core/utils/user-file'
|
|
import { uploadExecutionFile, uploadFileFromRawData } from '@/lib/uploads/contexts/execution'
|
|
import { downloadFileFromUrl } from '@/lib/uploads/utils/file-utils.server'
|
|
import { MAX_FILE_SIZE, sniffImageContentType } from '@/lib/uploads/utils/validation'
|
|
import type { ExecutionContext, UserFile } from '@/executor/types'
|
|
import type { ToolConfig, ToolFileData } from '@/tools/types'
|
|
|
|
const logger = createLogger('FileToolProcessor')
|
|
|
|
const IMAGE_FILE_EXTENSIONS: Record<string, string> = {
|
|
'image/gif': 'gif',
|
|
'image/jpeg': 'jpg',
|
|
'image/png': 'png',
|
|
'image/webp': 'webp',
|
|
}
|
|
|
|
function assertFileSize(size: number, fileName: string): void {
|
|
if (size > MAX_FILE_SIZE) {
|
|
throw new Error(`File '${fileName}' exceeds the maximum allowed size of ${MAX_FILE_SIZE} bytes`)
|
|
}
|
|
}
|
|
|
|
function resolveStoredFileMetadata(
|
|
fileName: string,
|
|
declaredMimeType: string,
|
|
buffer: Buffer
|
|
): { fileName: string; mimeType: string } {
|
|
if (!declaredMimeType.startsWith('image/')) {
|
|
return { fileName, mimeType: declaredMimeType }
|
|
}
|
|
|
|
const mimeType = sniffImageContentType(buffer)
|
|
if (!mimeType) {
|
|
return {
|
|
fileName: `${fileName.replace(/\.[^.]+$/, '')}.bin`,
|
|
mimeType: 'application/octet-stream',
|
|
}
|
|
}
|
|
|
|
const extension = IMAGE_FILE_EXTENSIONS[mimeType]
|
|
return {
|
|
fileName: extension ? `${fileName.replace(/\.[^.]+$/, '')}.${extension}` : fileName,
|
|
mimeType,
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Processes tool outputs and converts file-typed outputs to UserFile objects.
|
|
* This enables tools to return file data that gets automatically stored in the
|
|
* execution filesystem and made available as UserFile objects for workflow use.
|
|
*/
|
|
export class FileToolProcessor {
|
|
/**
|
|
* Process tool outputs and convert file-typed outputs to UserFile objects
|
|
*/
|
|
static async processToolOutputs(
|
|
toolOutput: any,
|
|
toolConfig: ToolConfig,
|
|
executionContext: ExecutionContext
|
|
): Promise<any> {
|
|
if (!toolConfig.outputs) {
|
|
return toolOutput
|
|
}
|
|
|
|
const processedOutput = { ...toolOutput }
|
|
|
|
for (const [outputKey, outputDef] of Object.entries(toolConfig.outputs)) {
|
|
if (!FileToolProcessor.isFileOutput(outputDef.type)) {
|
|
continue
|
|
}
|
|
|
|
const fileData = processedOutput[outputKey]
|
|
if (!fileData) {
|
|
logger.warn(`File-typed output '${outputKey}' is missing from tool result`)
|
|
continue
|
|
}
|
|
|
|
try {
|
|
processedOutput[outputKey] = await FileToolProcessor.processFileOutput(
|
|
fileData,
|
|
outputDef.type,
|
|
outputKey,
|
|
executionContext
|
|
)
|
|
} catch (error) {
|
|
logger.error(`Error processing file output '${outputKey}':`, error)
|
|
const errorMessage = toError(error).message
|
|
throw new Error(`Failed to process file output '${outputKey}': ${errorMessage}`)
|
|
}
|
|
}
|
|
|
|
return processedOutput
|
|
}
|
|
|
|
/**
|
|
* Check if an output type is file-related
|
|
*/
|
|
private static isFileOutput(type: string): boolean {
|
|
return type === 'file' || type === 'file[]'
|
|
}
|
|
|
|
/**
|
|
* Process a single file output (either single file or array of files)
|
|
*/
|
|
private static async processFileOutput(
|
|
fileData: any,
|
|
outputType: string,
|
|
outputKey: string,
|
|
executionContext: ExecutionContext
|
|
): Promise<UserFile | UserFile[]> {
|
|
if (outputType === 'file[]') {
|
|
return FileToolProcessor.processFileArray(fileData, outputKey, executionContext)
|
|
}
|
|
return FileToolProcessor.processFileData(fileData, executionContext)
|
|
}
|
|
|
|
/**
|
|
* Process an array of files
|
|
*/
|
|
private static async processFileArray(
|
|
fileData: any,
|
|
outputKey: string,
|
|
executionContext: ExecutionContext
|
|
): Promise<UserFile[]> {
|
|
if (!Array.isArray(fileData)) {
|
|
throw new Error(`Output '${outputKey}' is marked as file[] but is not an array`)
|
|
}
|
|
|
|
const files: UserFile[] = []
|
|
for (const file of fileData) {
|
|
files.push(await FileToolProcessor.processFileData(file, executionContext))
|
|
}
|
|
return files
|
|
}
|
|
|
|
/**
|
|
* Convert various file data formats to UserFile by storing in execution filesystem.
|
|
* If the input is already a UserFile, returns it unchanged.
|
|
*/
|
|
private static async processFileData(
|
|
fileData: ToolFileData | UserFile,
|
|
context: ExecutionContext
|
|
): Promise<UserFile> {
|
|
// If already a UserFile (e.g., from tools that handle their own file storage),
|
|
// return it directly without re-processing
|
|
if (isUserFile(fileData)) {
|
|
return fileData as UserFile
|
|
}
|
|
|
|
const data = fileData as ToolFileData
|
|
try {
|
|
let buffer: Buffer | null = null
|
|
|
|
if (Buffer.isBuffer(data.data)) {
|
|
assertFileSize(data.data.length, data.name)
|
|
buffer = data.data
|
|
} else if (
|
|
data.data &&
|
|
typeof data.data === 'object' &&
|
|
'type' in data.data &&
|
|
'data' in data.data
|
|
) {
|
|
const serializedBuffer = data.data as { type: string; data: number[] }
|
|
if (serializedBuffer.type === 'Buffer' && Array.isArray(serializedBuffer.data)) {
|
|
assertFileSize(serializedBuffer.data.length, data.name)
|
|
buffer = Buffer.from(serializedBuffer.data)
|
|
} else {
|
|
throw new Error(`Invalid serialized buffer format for ${data.name}`)
|
|
}
|
|
} else if (typeof data.data === 'string' && data.data) {
|
|
let base64Data = data.data
|
|
|
|
if (base64Data.includes('-') || base64Data.includes('_')) {
|
|
base64Data = base64Data.replace(/-/g, '+').replace(/_/g, '/')
|
|
}
|
|
|
|
const paddingBytes = base64Data.endsWith('==') ? 2 : base64Data.endsWith('=') ? 1 : 0
|
|
assertFileSize(Math.floor((base64Data.length * 3) / 4) - paddingBytes, data.name)
|
|
buffer = Buffer.from(base64Data, 'base64')
|
|
}
|
|
|
|
if (!buffer && data.url) {
|
|
buffer = await downloadFileFromUrl(data.url, {
|
|
maxBytes: MAX_FILE_SIZE,
|
|
userId: context.userId,
|
|
})
|
|
}
|
|
|
|
if (buffer) {
|
|
if (buffer.length === 0) {
|
|
throw new Error(`File '${data.name}' has zero bytes`)
|
|
}
|
|
assertFileSize(buffer.length, data.name)
|
|
const storedMetadata = resolveStoredFileMetadata(data.name, data.mimeType, buffer)
|
|
|
|
return await uploadExecutionFile(
|
|
{
|
|
workspaceId: context.workspaceId || '',
|
|
workflowId: context.workflowId,
|
|
executionId: context.executionId || '',
|
|
},
|
|
buffer,
|
|
storedMetadata.fileName,
|
|
storedMetadata.mimeType,
|
|
context.userId
|
|
)
|
|
}
|
|
|
|
if (!data.data) {
|
|
throw new Error(
|
|
`File data for '${data.name}' must have either 'data' (Buffer/base64) or 'url' property`
|
|
)
|
|
}
|
|
|
|
return uploadFileFromRawData(
|
|
{
|
|
name: data.name,
|
|
data: data.data,
|
|
mimeType: data.mimeType,
|
|
},
|
|
{
|
|
workspaceId: context.workspaceId || '',
|
|
workflowId: context.workflowId,
|
|
executionId: context.executionId || '',
|
|
},
|
|
context.userId
|
|
)
|
|
} catch (error) {
|
|
logger.error(`Error processing file data for '${data.name}':`, error)
|
|
throw error
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Check if a tool has any file-typed outputs
|
|
*/
|
|
static hasFileOutputs(toolConfig: ToolConfig): boolean {
|
|
if (!toolConfig.outputs) {
|
|
return false
|
|
}
|
|
|
|
return Object.values(toolConfig.outputs).some(
|
|
(output) => output.type === 'file' || output.type === 'file[]'
|
|
)
|
|
}
|
|
}
|