import {z} from 'zod' export type GetApiAutomationsArgs = {limit?: number | undefined, cursor?: string | undefined, search?: string | undefined, enabled?: boolean | undefined}; export type GetApiAutomationsOptions = {baseUrl?: string | undefined, MotionApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const automationRun = z.object({id: z.string(), status: z.enum(["queued", "running", "completed", "skipped", "failed", "blocked"]), motionAgentChatId: z.string().nullable(), queuedAt: z.string(), startedAt: z.string().nullable().optional(), completedAt: z.string().nullable().optional(), attempt: z.number().int().optional(), resultSummary: z.string().nullable().optional(), error: z.string().nullable().optional()}).and(z.record(z.string(), z.unknown())); export const automationMemory = z.object({rememberProcessedItems: z.boolean(), includePreviousRuns: z.number().int().gte(0).lte(20), compactAfterRuns: z.number().int().gte(5).lte(100)}); export const automationConnectorCondition = z.object({eventTypes: z.array(z.enum(["schedule_once", "schedule_recurring", "youtube_video_uploaded", "twitch_stream_ended", "kick_stream_ended"])).optional(), payloadField: z.string().max(200).optional(), equals: z.string().max(2000).optional()}); export const automationConnectorGrant = z.object({connectorId: z.enum(["github", "notion", "figma", "google-drive", "dropbox", "getty"]), access: z.literal("read"), resources: z.array(z.string().min(1).max(2000)), condition: automationConnectorCondition.optional()}); export const automationConnectorPolicy = z.object({mode: z.enum(["none", "fixed", "conditional"]), onUnavailable: z.enum(["block", "run_without"]), grants: z.array(automationConnectorGrant)}); export const automation = z.object({id: z.string(), name: z.string(), enabled: z.boolean(), prompt: z.string(), trigger: z.object({type: z.string(), platform: z.string(), source: z.string()}).and(z.record(z.string(), z.unknown())), createdAt: z.string(), updatedAt: z.string(), nextRunAt: z.string().nullable(), runs: z.array(automationRun), memory: automationMemory.optional(), connectorPolicy: automationConnectorPolicy.optional(), maxConcurrentRuns: z.number().int().optional(), maxRunsPerHour: z.number().int().optional()}).and(z.record(z.string(), z.unknown())); export const automationList = z.object({automations: z.array(automation), has_more: z.boolean(), next_cursor: z.string().nullable()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * List automations * * GET /automations * * Also accepts auth: MotionOAuth */ export const getApiAutomations = async (args: GetApiAutomationsArgs, options?: GetApiAutomationsOptions) => { const {baseUrl = "https://api.motion.so/api/motion", fetch: fetchFn = fetch, MotionApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.limit != null) query.append("limit", String(args.limit)) if (args.cursor != null) query.append("cursor", String(args.cursor)) if (args.search != null) query.append("search", String(args.search)) if (args.enabled != null) query.append("enabled", String(args.enabled)) if (MotionApiKey !== undefined) headers.set('authorization', `Bearer ${MotionApiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/automations${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(automationList, await res.json()) };