import {z} from 'zod' export type GetApiV1RunsArgs = {page?: number | undefined, per_page?: number | undefined}; export type GetApiV1RunsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const agentsRunStatus = z.enum(["running", "completed", "error", "interrupted"]); export const agentsRunRequester = z.object({id: z.string(), name: z.string(), email: z.string().nullable().optional()}); export const agentsSource = z.object({url: z.string(), source_name: z.string().optional(), source_tier: z.string().optional(), source_type: z.string().optional()}); export const agentsArtifact = z.object({title: z.string(), type: z.string(), confidence: z.string().nullable().optional(), summary: z.string().nullable().optional(), sources: z.array(agentsSource).optional()}); export const agentsRunOutput = z.object({artifacts: z.array(agentsArtifact)}); export const agentsRunInterruptsItem = z.object({id: z.string(), value: z.record(z.string(), z.unknown()), agent: z.string().nullable().optional()}); export const agentsStepType = z.enum(["activity", "output", "interrupt", "error"]); export const agentsStepStatus = z.enum(["running", "completed", "error"]); export const agentsStepResultResolution = z.enum(["auto_approve", "skip"]); export const agentsStepResult = z.object({resolution: agentsStepResultResolution.optional()}); export const agentsStep: z.ZodType = z.object({id: z.string(), run_id: z.string(), agent: z.string().optional(), type: agentsStepType, name: z.string(), label: z.string(), parent_step_id: z.string().nullable().optional(), status: agentsStepStatus, started_at: z.string(), completed_at: z.string().nullable().optional(), steps: z.array(z.lazy(() => agentsStep)).optional(), result: agentsStepResult.optional(), artifacts: z.array(agentsArtifact).optional()}); export const agentsRun = z.object({object: z.string(), id: z.string(), created_at: z.string(), updated_at: z.string(), status: agentsRunStatus, thread_id: z.string().optional(), business_id: z.string().nullable().optional(), agent: z.string().optional(), requester: agentsRunRequester.nullable().optional(), started_at: z.string().nullable().optional(), ended_at: z.string().nullable().optional(), output: agentsRunOutput.nullable().optional(), interrupts: z.array(agentsRunInterruptsItem).optional(), steps: z.array(agentsStep).optional()}); export const runsListAgentRunsResponse = z.object({data: z.array(agentsRun), object: z.string(), has_more: z.boolean(), total_count: z.number().int().optional()}); 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 agent runs * * GET /v1/runs */ export const getApiV1Runs = async (args: GetApiV1RunsArgs, options?: GetApiV1RunsOptions) => { const {baseUrl = "https://api.middesk.com", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.page != null) query.append("page", String(args.page)) if (args.per_page != null) query.append("per_page", String(args.per_page)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/runs${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(runsListAgentRunsResponse, await res.json()) };