import {z} from 'zod' export type UUIDSchema = string; export type ImageSourceTag = string; export type ImageSource = UUIDSchema | ImageSourceTag; export type InstanceResourcesLimits = {max_layer_bytes?: number | undefined}; export type InstanceNetworking = {enabled?: boolean | undefined}; export type ClosableStreamRepr = {value: string, encoding?: ('ascii' | 'base64') | undefined, close?: boolean | undefined}; export type InstanceSpawnRequest = {command: string, disposable?: boolean | undefined, hostname?: string | undefined, image: ImageSource, args?: Array | undefined, shell?: boolean | undefined, env?: ({[key: string]: string} | null) | undefined, preserve_env?: boolean | undefined, cwd?: string | undefined, uid?: number | undefined, gid?: number | undefined, resources_limits?: InstanceResourcesLimits | undefined, networking?: InstanceNetworking | undefined, stdin?: ClosableStreamRepr | undefined, timeout?: number | undefined, truncate_output_at?: number | undefined, files?: ({[key: string]: {uuid?: UUIDSchema | undefined, uid?: number | undefined, gid?: number | undefined, mode?: string | undefined}}) | undefined}; export type CreateApiInstancesArgs = {body: InstanceSpawnRequest}; export type CreateApiInstancesOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const uUIDSchema = z.string(); export const instanceResourcesLimits = z.object({max_layer_bytes: z.number().int().gte(1).optional()}); export const instanceNetworking = z.object({enabled: z.boolean().optional()}); export const closableStreamRepr = z.object({value: z.string(), encoding: z.enum(["ascii", "base64"]).optional(), close: z.boolean().optional()}); export const streamRepr = z.object({value: z.string(), encoding: z.enum(["ascii", "base64"]), truncated: z.boolean().optional()}); export const instanceResult = z.object({resources: z.object({block_input: z.number().int().optional(), block_output: z.number().int().optional(), cost: z.number().optional(), elapsed_time: z.number().optional(), involuntary_switches: z.number().int().optional(), max_rss: z.number().int().optional(), monotonic_time: z.number().optional(), page_faults: z.number().int().optional(), page_faults_io: z.number().int().optional(), shared_memory: z.number().int().optional(), signals: z.number().int().optional(), swaps: z.number().int().optional(), system_cpu_time: z.number().optional(), unshared_memory: z.number().int().optional(), user_cpu_time: z.number().optional(), voluntary_switches: z.number().int().optional()}).optional(), state: z.object({continued: z.boolean().optional(), core_dump: z.boolean().optional(), exit_code: z.number().int().optional(), pid: z.number().int().optional(), signal: z.number().int().optional(), stopped: z.boolean().optional(), timed_out: z.boolean().optional()}).optional(), stdout: streamRepr.optional(), stderr: streamRepr.optional()}); export const instanceSpawnResponse = z.object({uuid: uUIDSchema.optional(), command: z.string().optional(), image: uUIDSchema.optional(), hostname: z.string().optional(), args: z.array(z.string()).optional(), shell: z.boolean().optional(), env: z.record(z.string(), z.string()).nullable().optional(), preserve_env: z.boolean().optional(), cwd: z.string().optional(), uid: z.number().int().optional(), gid: z.number().int().optional(), resources_limits: instanceResourcesLimits.optional(), networking: instanceNetworking.optional(), stdin: closableStreamRepr.optional(), timeout: z.number().int().optional(), truncate_output_at: z.number().int().optional(), disposable: z.boolean().optional(), files: z.record(z.string(), z.object({uuid: uUIDSchema.optional(), uid: z.number().int().optional(), gid: z.number().int().optional(), mode: z.string().optional()})).optional(), result: instanceResult.nullable().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 }; /** * Spawn a new container instance * * POST /instances */ export const createApiInstances = async (args: CreateApiInstancesArgs, options?: CreateApiInstancesOptions) => { const {baseUrl = "https://api.tokenfactory.nebius.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/instances${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(instanceSpawnResponse, await res.json()) };