@picsart/ai-sdk 5.39.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts CHANGED
@@ -12,7 +12,6 @@ interface WorkflowJobHandle {
12
12
  workflow: string;
13
13
  id: string;
14
14
  }
15
- type WorkflowStatus = 'ACCEPTED' | 'IN_PROGRESS' | 'COMPLETED' | 'FAILED' | 'CANCELED' | 'UNKNOWN';
16
15
  interface WorkflowProgress {
17
16
  percent?: number;
18
17
  estimatedSecondsLeft?: number;
@@ -44,45 +43,59 @@ interface CreditUsage {
44
43
  /** The remaining balance. */
45
44
  balance?: number;
46
45
  }
47
- interface WorkflowStatusResult<TResult = unknown> {
48
- handle: WorkflowJobHandle;
49
- status: WorkflowStatus;
46
+ interface WorkflowPollOptions {
47
+ intervalMs?: number;
48
+ maxAttempts?: number;
49
+ signal?: AbortSignal;
50
+ }
51
+ /**
52
+ * What a transport hands back from `execute` / `poll` / `status`: the task
53
+ * result the SDK parses, the platform's credit usage, and — when the
54
+ * transport has an envelope distinct from the result — the raw payload
55
+ * (text models read it as a fallback).
56
+ */
57
+ interface TransportResult<TResult = unknown> {
50
58
  result?: TResult;
51
- error?: string;
52
- /** Platform error `reason` on a failed task, when the response carried one. */
53
- reason?: string;
54
- /** Numeric status on the error payload, when the response carried one. */
55
- statusCode?: number;
56
- progress?: WorkflowProgress;
57
- /** Credit usage reported by the platform, when present on the response. */
58
59
  usage?: CreditUsage;
59
- raw: unknown;
60
+ /** Raw payload as the transport received it. Defaults to `result`. */
61
+ raw?: unknown;
62
+ }
63
+ /** Poll controls plus the progress sink `ai.subscribe()` drains. */
64
+ interface TransportPollOptions extends WorkflowPollOptions {
65
+ onProgress?: (progress: WorkflowProgress) => void;
60
66
  }
61
67
  /**
62
- * The transport contract for talking to the workflows backend.
68
+ * The transport contract for talking to the generation backend — the one seam
69
+ * every SDK request passes through. `createClient({ apiUrl, apiKey })` builds
70
+ * the default implementation over @picsart/workflows-client;
71
+ * `createClient({ transport })` replaces it wholesale (a different gateway, a
72
+ * signed proxy, a test double).
63
73
  *
64
- * `execute` (one-shot synchronous generation) is the only required method.
65
- * `submit` + `status` are the async submit-and-poll pair — optional, so an
66
- * execute-only transport can omit them. `options` is the SDK-level
67
- * credit-estimation call. When a transport omits `submit`, the client routes
68
- * all generation through `execute`; calling the async lifecycle methods
69
- * (submit/status/result/subscribe) on such a client throws.
74
+ * `execute` (one-shot synchronous run) is the only required method — it serves
75
+ * `syncExecute` models and every catalog task. `submit` + `poll` are the async
76
+ * submit-and-wait pair: when either is missing, the client routes ALL
77
+ * generation through `execute`, and the async lifecycle (`submit()` /
78
+ * `result()` / `subscribe()`) rejects with `unsupported_transport`. `status` is
79
+ * a single non-blocking read, used to probe which route a bare generation id
80
+ * was submitted on; `options` is the credit-estimation call behind
81
+ * `getCredits()`. Omitted optional methods degrade the matching feature rather
82
+ * than breaking the client.
83
+ *
84
+ * Failures should be thrown as {@link ApiError} — anything else reaches the
85
+ * caller as a 502 `generation_failed`. An `AbortError` is never wrapped.
70
86
  */
71
87
  interface SdkTransport<TPayload = Record<string, unknown>> {
72
- execute(request: WorkflowSubmitRequest<TPayload>): Promise<unknown>;
73
- submit?(request: WorkflowSubmitRequest<TPayload>): Promise<WorkflowJobHandle>;
74
- status?(handle: WorkflowJobHandle, signal?: AbortSignal): Promise<unknown>;
88
+ /** One-shot synchronous run: submit and return the finished result. */
89
+ execute(request: WorkflowSubmitRequest<TPayload>): Promise<TransportResult>;
90
+ /** Start an async job and return its generation id. */
91
+ submit?(request: WorkflowSubmitRequest<TPayload>): Promise<string>;
92
+ /** Wait for a submitted job to reach a terminal state, reporting progress. */
93
+ poll?(handle: WorkflowJobHandle, options?: TransportPollOptions): Promise<TransportResult>;
94
+ /** Read a submitted job's current state in one request — no waiting. */
95
+ status?(handle: WorkflowJobHandle, signal?: AbortSignal): Promise<TransportResult>;
96
+ /** Credits this request would cost, or null when pricing is unavailable. */
75
97
  options?(workflow: string, payload: Record<string, unknown>): Promise<number | null>;
76
98
  }
77
- interface WorkflowPollOptions {
78
- intervalMs?: number;
79
- maxAttempts?: number;
80
- signal?: AbortSignal;
81
- }
82
- interface WorkflowRunOptions extends WorkflowPollOptions {
83
- mode?: 'async' | 'sync';
84
- }
85
- type WorkflowSubscribeOptions = WorkflowPollOptions;
86
99
 
87
100
  /**
88
101
  * Per-model compile-time input contracts generated from specs/vendors catalog.
@@ -566,9 +579,11 @@ type ModelInputById = {
566
579
  };
567
580
  "ideogram-v4": {
568
581
  prompt: string;
569
- resolution?: "2048x2048" | "1440x2880" | "2880x1440" | "1664x2496" | "2496x1664" | "1792x2240" | "2240x1792" | "1440x2560" | "2560x1440" | "1600x2560" | "2560x1600" | "1728x2304" | "2304x1728" | "1296x3168" | "3168x1296" | "1152x2944" | "2944x1152" | "1248x3328" | "3328x1248" | "1280x3072" | "3072x1280";
582
+ resolution?: "2048x2048" | "1440x2880" | "2880x1440" | "1664x2496" | "2496x1664" | "1792x2240" | "2240x1792" | "1440x2560" | "2560x1440" | "1600x2560" | "2560x1600" | "1728x2304" | "2304x1728" | "1296x3168" | "3168x1296" | "1152x2944" | "2944x1152" | "1248x3328" | "3328x1248" | "1280x3072" | "3072x1280" | "1024x3072" | "3072x1024" | "1024x1024" | "896x1120" | "1120x896" | "864x1152" | "1152x864" | "832x1248" | "1248x832" | "800x1280" | "1280x800" | "720x1280" | "1280x720" | "720x1440" | "1440x720" | "512x1536" | "1536x512";
570
583
  renderingSpeed?: "TURBO" | "DEFAULT" | "QUALITY";
571
584
  enableCopyrightDetection?: boolean;
585
+ imageUrls?: string[];
586
+ imageWeight?: number;
572
587
  };
573
588
  "kling-3.0-image": {
574
589
  prompt: string;
@@ -846,11 +861,6 @@ type ModelInputById = {
846
861
  prompt: string;
847
862
  imageUrls?: string[];
848
863
  };
849
- "minimax-02-hd": {
850
- language?: string;
851
- accent?: string;
852
- prompt: string;
853
- };
854
864
  "minimax-h3": {
855
865
  prompt: string;
856
866
  startFrame?: string;
@@ -1862,6 +1872,8 @@ type ApiSchemas = WorkflowTypes;
1862
1872
  * The `ai.apis` surface — direct, low-level access to the Picsart model APIs.
1863
1873
  * Known API names (keys of {@link ApiSchemas}) get typed params + result;
1864
1874
  * unknown names take an open payload and return an unknown result.
1875
+ *
1876
+ * Failures arrive as {@link ApiError}, the same as the generation surface.
1865
1877
  */
1866
1878
  interface ApisClient {
1867
1879
  /** Run an API by name (mirrors WorkflowsClient.run()). */
@@ -2069,8 +2081,6 @@ interface ModelParamsAccessor {
2069
2081
  hasFileInput(): boolean;
2070
2082
  getDefault(key: string): unknown;
2071
2083
  getDefaults(): Record<string, unknown>;
2072
- /** @deprecated Use `enum(key)` instead — returns full `EnumEntry` with `.options`, `.default`, etc. */
2073
- getEnumOptions(key: string): (string | number)[] | null;
2074
2084
  toSchema(): ModelParamSchema;
2075
2085
  transferValues(prev: Record<string, unknown>): Record<string, unknown>;
2076
2086
  }
@@ -2106,7 +2116,7 @@ interface CreditTier {
2106
2116
  }
2107
2117
  /** Top-level model accessor with grouped sub-accessors. */
2108
2118
  /** Result of validating generation input against a model's params. */
2109
- interface ValidationResult$1 {
2119
+ interface ValidationResult {
2110
2120
  valid: boolean;
2111
2121
  errors?: string[];
2112
2122
  }
@@ -2119,7 +2129,7 @@ interface ModelDescriptor {
2119
2129
  meta(): ModelMeta;
2120
2130
  /** Validate generation input against this model's params. Returns
2121
2131
  * `{ valid: true }` or `{ valid: false, errors }` — never throws. */
2122
- validate(input: unknown): ValidationResult$1;
2132
+ validate(input: unknown): ValidationResult;
2123
2133
  /** Get the credit range for this model, plus the per-tier breakdown in
2124
2134
  * `.tiers`. Pass context to narrow by resolution/audio. Returns the per-unit
2125
2135
  * range — callers with time-based parameters should scale by the value
@@ -2135,15 +2145,15 @@ interface ModelDescriptor {
2135
2145
  };
2136
2146
  }
2137
2147
  /** Filter criteria for `catalog.find()`. */
2138
- interface ModelFilter$1 {
2148
+ interface ModelFilter {
2139
2149
  output?: GenerationMode;
2140
2150
  provider?: string;
2141
2151
  /**
2142
2152
  * Release tiers to include. Omitted ⇒ the default visible set
2143
2153
  * (`['production', 'general-availability']`). List the tiers you want
2144
2154
  * explicitly to opt into `preview` — e.g. `['preview']` for stage-only
2145
- * models, or all three to include everything. `disabled`/`deprecated`
2146
- * models stay hidden regardless.
2155
+ * models, or all three to include everything. `deprecated` models stay
2156
+ * hidden regardless.
2147
2157
  */
2148
2158
  release?: ReleaseTag[];
2149
2159
  }
@@ -2329,17 +2339,12 @@ interface ModelDefinition {
2329
2339
  badge?: BadgeType[];
2330
2340
  /** ISO YYYY-MM-DD date the model was added. The 'new' badge is derived from this — see core/badges.ts. */
2331
2341
  addedAt?: string;
2332
- /**
2333
- * Marks a model as operationally unavailable — backend not deployed,
2334
- * pricing unconfirmed, catalog/runtime mismatch, etc. Expected to flip
2335
- * back on once the gate clears. Hidden from default catalog lookups.
2336
- */
2337
- disabled?: boolean;
2338
2342
  /**
2339
2343
  * Marks a model as retired — superseded by a newer model or otherwise no
2340
2344
  * longer offered. Will not come back. Catalog row stays so workflow IDs
2341
2345
  * and toolIds remain resolvable for historical jobs and pricing. Hidden
2342
- * from default catalog lookups, same as `disabled`.
2346
+ * from default catalog lookups. (Operationally-gated models use
2347
+ * `release: 'preview'` instead.)
2343
2348
  */
2344
2349
  deprecated?: boolean;
2345
2350
  release?: ReleaseTag;
@@ -2412,8 +2417,6 @@ interface CatalogResult {
2412
2417
  /** `null` when the list is complete. */
2413
2418
  nextCursor: string | null;
2414
2419
  }
2415
- /** @deprecated No longer drives behavior — catalogs are addressed by param key. */
2416
- type CatalogKind = 'voices' | 'avatars';
2417
2420
  /** Binds a param's options to a platform catalog task. */
2418
2421
  interface CatalogSource {
2419
2422
  /** Catalog workflow name, e.g. `heygen/v1/catalog/voices`. */
@@ -2480,6 +2483,87 @@ interface CatalogsOptions {
2480
2483
  preload?: boolean;
2481
2484
  }
2482
2485
 
2486
+ /**
2487
+ * Per-item vendor metadata promoted from the response. Every key is
2488
+ * best-effort: present when the vendor reports it, absent otherwise.
2489
+ */
2490
+ interface GenerateResultItemMetadata {
2491
+ /** Explore image id (recraft explore models). */
2492
+ exploreImageId?: string;
2493
+ /** Voice preview id (ElevenLabs voice design/remix) — pass to the vendor's
2494
+ * create-voice-from-preview step to persist the voice. */
2495
+ generatedVoiceId?: string;
2496
+ /** Generation seed, when the vendor echoes it. */
2497
+ seed?: number;
2498
+ /** Vendor safety flag for this item (e.g. `has_nsfw_concepts[i]`). */
2499
+ nsfw?: boolean;
2500
+ width?: number;
2501
+ height?: number;
2502
+ contentType?: string;
2503
+ /** Video duration in seconds. */
2504
+ duration?: number;
2505
+ /** Video frame rate. */
2506
+ fps?: number;
2507
+ /** Video file size in bytes. */
2508
+ fileSize?: number;
2509
+ }
2510
+
2511
+ /**
2512
+ * Failure codes the SDK synthesizes when the platform supplies no `reason`.
2513
+ * An API-supplied `reason` passes through unchanged, so the open `string`
2514
+ * member keeps arbitrary platform reasons assignable while preserving
2515
+ * autocomplete on the known set.
2516
+ */
2517
+ type ApiErrorCode = 'unknown_model' | 'wrong_model_mode' | 'validation_error' | 'unsupported_transport' | 'timeout' | 'aborted' | 'canceled' | 'generation_failed' | 'invalid_response' | 'bad_request' | 'unauthorized' | 'payment_required' | 'forbidden' | 'not_found' | 'rate_limited' | 'server_error' | (string & {});
2518
+ /** Everything but the message needed to build a {@link ApiError}. */
2519
+ interface ApiErrorInit {
2520
+ /**
2521
+ * HTTP status of the failing response. When no HTTP exchange took place the
2522
+ * SDK synthesizes the semantically matching code: 400 for input the SDK
2523
+ * itself rejects, 408 for a poll deadline, 499 for an abort or cancel, 502
2524
+ * for a response it cannot make sense of.
2525
+ */
2526
+ status: number;
2527
+ /** Platform `reason` when present, otherwise an SDK-synthesized code. */
2528
+ code: ApiErrorCode;
2529
+ }
2530
+ /**
2531
+ * The single error type the SDK throws — the generation surface
2532
+ * (`generate()`, `generateText()`, `submit()`, `result()`), `ai.catalogs`,
2533
+ * and `ai.apis` alike.
2534
+ *
2535
+ * Unrelated to the `Api*` types (`ApiResponse`, `ApiRunOptions`, …), which
2536
+ * describe the low-level `ai.apis` surface — though that surface throws this
2537
+ * error too. ApiError is the only error type the SDK exposes.
2538
+ *
2539
+ * ```ts
2540
+ * try {
2541
+ * await ai.generate(Models.Flux2Pro, { prompt: 'a cat' });
2542
+ * } catch (err) {
2543
+ * if (err instanceof ApiError) {
2544
+ * if (err.status === 402) return topUpCredits();
2545
+ * if (err.status === 429 || err.status >= 500) return retry();
2546
+ * if (err.code === 'validation_error') return showFormError(err.message);
2547
+ * }
2548
+ * throw err;
2549
+ * }
2550
+ * ```
2551
+ *
2552
+ * Aborts raised by `fetch` itself are never wrapped — a caller checking
2553
+ * `err.name === 'AbortError'` on a `DOMException` keeps working.
2554
+ */
2555
+ declare class ApiError extends Error {
2556
+ /** HTTP status, or the synthesized equivalent for non-HTTP failures. */
2557
+ readonly status: number;
2558
+ /** Platform `reason`, or an SDK-synthesized code. Always equal to {@link reason}. */
2559
+ readonly code: ApiErrorCode;
2560
+ /** Alias of {@link code}, named after the platform's own error field. */
2561
+ readonly reason: ApiErrorCode;
2562
+ constructor(message: string, init: ApiErrorInit);
2563
+ }
2564
+
2565
+ /** Worker-reported progress on a generation.progress event. */
2566
+ type GenerationProgress = WorkflowProgress;
2483
2567
  /** A fetch-like function that handles authentication (headers, cookies, etc.). */
2484
2568
  type AuthenticatedFetch = (url: string, init?: RequestInit) => Promise<Response>;
2485
2569
  /** Drive configuration — enables auto-saving generations to Picsart Drive. */
@@ -2501,16 +2585,30 @@ interface AppIdentity {
2501
2585
  id: string;
2502
2586
  type: AppType;
2503
2587
  }
2588
+ /** Settings that apply whichever transport serves the client. */
2589
+ interface ClientConfigBase {
2590
+ /** Enable Drive integration — auto-save generations to a Drive folder. */
2591
+ drive?: DriveConfig;
2592
+ /**
2593
+ * Input-transformation defaults applied to every generation. A per-call
2594
+ * `options.inputsTransformation` overrides this field by field.
2595
+ */
2596
+ inputsTransformation?: PayloadInputsTransformationOptions;
2597
+ /**
2598
+ * Voice/avatar catalog behavior. `{ preload: true }` loads the first page
2599
+ * of every catalog-bound param in the background at client creation.
2600
+ */
2601
+ catalogs?: CatalogsOptions;
2602
+ }
2504
2603
  /**
2505
- * Simple client config — pass the API base URL plus one auth source, and the
2506
- * SDK handles the rest. The SDK knows the Picsart API endpoints and response
2507
- * shapes internally.
2604
+ * The usual config: the API base URL plus one auth source, and the SDK builds
2605
+ * its own transport over @picsart/workflows-client.
2508
2606
  *
2509
2607
  * Provide exactly one of:
2510
2608
  * - `fetch` — your own authenticated fetch (you add headers/cookies), or
2511
2609
  * - `apiKey` — the SDK builds a fetch that sends `Authorization: Bearer <apiKey>`.
2512
2610
  */
2513
- interface ClientConfig {
2611
+ interface HttpClientConfig extends ClientConfigBase {
2514
2612
  /**
2515
2613
  * Authenticated fetch function. The SDK calls this for all HTTP requests.
2516
2614
  * Provide this or `apiKey`. Takes precedence over `apiKey` when both are set.
@@ -2524,34 +2622,54 @@ interface ClientConfig {
2524
2622
  apiKey?: string;
2525
2623
  /** API base URL (e.g. 'https://api.picsart.com'). */
2526
2624
  apiUrl: string;
2527
- /** Enable Drive integration — auto-save generations to a Drive folder. */
2528
- drive?: DriveConfig;
2529
- /**
2530
- * Input-transformation defaults applied to every generation. A per-call
2531
- * `options.inputsTransformation` overrides this field by field.
2532
- */
2533
- inputsTransformation?: PayloadInputsTransformationOptions;
2534
- /**
2535
- * Voice/avatar catalog behavior. `{ preload: true }` loads the first page
2536
- * of every catalog-bound param in the background at client creation.
2537
- */
2538
- catalogs?: CatalogsOptions;
2625
+ transport?: undefined;
2539
2626
  }
2627
+ /**
2628
+ * Config for a caller-supplied {@link SdkTransport} — you own the wire, so
2629
+ * `apiUrl` and the auth source are yours to bake into the transport and are
2630
+ * not required here (the SDK never passes them to it).
2631
+ *
2632
+ * Two surfaces still speak the workflows protocol directly and therefore keep
2633
+ * needing `apiUrl` plus `fetch`/`apiKey` when you use them: `ai.drive`, and
2634
+ * `ai.apis`. Everything else — generate, the async lifecycle, `getCredits`,
2635
+ * `ai.catalogs` — goes through the transport.
2636
+ */
2637
+ interface TransportClientConfig extends ClientConfigBase {
2638
+ /** Transport the client runs on, in place of the built-in one. */
2639
+ transport: SdkTransport;
2640
+ /** Only needed for `ai.drive` / `ai.apis`. */
2641
+ apiUrl?: string;
2642
+ /** Only needed for `ai.drive` / `ai.apis`. */
2643
+ fetch?: AuthenticatedFetch;
2644
+ /** Only needed for `ai.drive` / `ai.apis`. */
2645
+ apiKey?: string;
2646
+ }
2647
+ /**
2648
+ * Client config — either the built-in transport's shape or a custom
2649
+ * transport's. The two halves are deliberately unexported: they carry the same
2650
+ * fields and differ only in which are required, so `ClientConfig` is the single
2651
+ * name to annotate with.
2652
+ */
2653
+ type ClientConfig = HttpClientConfig | TransportClientConfig;
2654
+
2540
2655
  interface GenerateResultItem {
2541
2656
  url: string;
2542
- metadata?: Record<string, unknown>;
2657
+ metadata?: GenerateResultItemMetadata;
2543
2658
  }
2659
+ /** Result of a media generation. */
2544
2660
  interface GenerateResult {
2545
- /** Primary result URL (convenience shortcut for results[0].url). */
2661
+ /** Primary result URL (convenience shortcut for items[0].url). */
2546
2662
  url: string;
2547
- /** All result items — single item for normal models, multiple for explore/multi-result models. */
2663
+ /** All result items — one for normal models, multiple for explore/multi-result models. */
2664
+ items: GenerateResultItem[];
2665
+ /** @deprecated Use {@link items} — same array; removed in the next major. */
2548
2666
  results: GenerateResultItem[];
2549
- /** Model ID that produced this result. */
2550
- model: string;
2551
- /** Job handle for status tracking. */
2552
- handle: WorkflowJobHandle;
2553
- /** Raw parsed output for advanced consumers. */
2554
- raw: unknown;
2667
+ /**
2668
+ * The generation id — pass to result()/subscribe() together with the model
2669
+ * id. Absent for syncExecute models: their generation completes inline in
2670
+ * one request, so there is no job to poll or recover.
2671
+ */
2672
+ generationId?: string;
2555
2673
  /** Credit usage reported by the platform — same structure as the pluggable APIs' GenAITaskResponse. */
2556
2674
  usage?: CreditUsage;
2557
2675
  /** Present when Drive is enabled and the file was saved. */
@@ -2563,13 +2681,43 @@ interface GenerateTextResult {
2563
2681
  text: string;
2564
2682
  /** Model ID that produced this result. */
2565
2683
  model: string;
2566
- /** Job handle for status tracking. */
2567
- handle: WorkflowJobHandle;
2568
2684
  /** Raw parsed output — carries vendor token usage, finish reason, thinking trace, etc. */
2569
2685
  raw: unknown;
2570
2686
  /** Credit usage reported by the platform — same structure as the pluggable APIs' GenAITaskResponse. */
2571
2687
  usage?: CreditUsage;
2572
2688
  }
2689
+
2690
+ /**
2691
+ * Named constants for the {@link GenerationEvent} discriminant — sugar over
2692
+ * the string literals for consumers who prefer `GenerationEventType.Completed`
2693
+ * to `'generation.completed'`. Both compare fine: the event `type` field stays
2694
+ * a literal union, so raw strings keep working (and keep autocompleting).
2695
+ */
2696
+ declare const GenerationEventType: {
2697
+ readonly Progress: "generation.progress";
2698
+ readonly Completed: "generation.completed";
2699
+ readonly Failed: "generation.failed";
2700
+ };
2701
+ type GenerationEventType = (typeof GenerationEventType)[keyof typeof GenerationEventType];
2702
+ /**
2703
+ * One `ai.subscribe()` update.
2704
+ * - `generation.progress` — a non-terminal poll; `progress` is present when
2705
+ * the worker reports it (percent, ETA).
2706
+ * - `generation.completed` — terminal; carries the parsed
2707
+ * {@link GenerateResult} in `result`, no follow-up `ai.result()` needed.
2708
+ * - `generation.failed` — terminal (worker FAILED or the job was canceled);
2709
+ * carries the same {@link ApiError} that `ai.result()` would have thrown.
2710
+ */
2711
+ type GenerationEvent = {
2712
+ type: 'generation.progress';
2713
+ progress?: GenerationProgress;
2714
+ } | {
2715
+ type: 'generation.completed';
2716
+ result: GenerateResult;
2717
+ } | {
2718
+ type: 'generation.failed';
2719
+ error: ApiError;
2720
+ };
2573
2721
  /** Input-transformation settings injected into the workflow payload as
2574
2722
  * `options.inputs_transformation` (GenAIOptions, alongside `drive`). */
2575
2723
  interface PayloadInputsTransformationOptions {
@@ -2582,6 +2730,14 @@ interface PayloadInputsTransformationOptions {
2582
2730
  */
2583
2731
  downscaleOversizedImages?: boolean;
2584
2732
  }
2733
+ /** Polling controls for result()/subscribe() on an already-submitted job. */
2734
+ interface GenerationOptions {
2735
+ /** Poll interval in ms. Overrides the model's `pollOptions` and the mode default. */
2736
+ intervalMs?: number;
2737
+ /** Max poll attempts before timing out. Overrides the model's `pollOptions` and the mode default. */
2738
+ maxAttempts?: number;
2739
+ signal?: AbortSignal;
2740
+ }
2585
2741
  /** Options for individual generate() / submit() calls. */
2586
2742
  interface GenerateOptions {
2587
2743
  signal?: AbortSignal;
@@ -2620,18 +2776,20 @@ interface AiClient {
2620
2776
  generateText<M extends TextModelId>(model: M, params: TextModelInputById[M], options?: GenerateOptions): Promise<GenerateTextResult>;
2621
2777
  /** Get exact credit cost for a model with specific parameters. */
2622
2778
  getCredits<M extends TypedModelId>(model: M, params: ModelInputById[M]): Promise<number | null>;
2623
- /** Submit a generation job and get a handle back. Media models only. */
2624
- submit<M extends MediaModelId>(model: M, params: ModelInputById[M], options?: GenerateOptions): Promise<WorkflowJobHandle>;
2625
- /** Check the current status of a submitted job. */
2626
- status(handle: WorkflowJobHandle, signal?: AbortSignal): Promise<WorkflowStatusResult<unknown>>;
2779
+ /** Submit a generation job and get its generation id back. Media models only. */
2780
+ submit<M extends MediaModelId>(model: M, params: ModelInputById[M], options?: GenerateOptions): Promise<string>;
2627
2781
  /** Poll a submitted job until it completes and return the parsed result. Media models only. */
2628
- result(handle: WorkflowJobHandle, model: MediaModelId, options?: WorkflowPollOptions): Promise<GenerateResult>;
2629
- /** Subscribe to live status updates for a submitted job. */
2630
- subscribe(handle: WorkflowJobHandle, options?: WorkflowSubscribeOptions): AsyncGenerator<WorkflowStatusResult<unknown>, WorkflowStatusResult<unknown>, void>;
2782
+ result(model: MediaModelId, generationId: string, options?: GenerationOptions): Promise<GenerateResult>;
2783
+ /**
2784
+ * Subscribe to live updates for a submitted job. Yields one
2785
+ * {@link GenerationEvent} per poll; the terminal `generation.completed`
2786
+ * event carries the parsed result in `event.result`, and failures/cancels
2787
+ * arrive as `generation.failed` events (with the {@link ApiError}), not as
2788
+ * exceptions.
2789
+ */
2790
+ subscribe(model: MediaModelId, generationId: string, options?: GenerationOptions): AsyncGenerator<GenerationEvent, void, void>;
2631
2791
  /** Build the vendor-specific payload for a model without submitting. */
2632
2792
  buildPayload<M extends TypedModelId>(model: M, params: ModelInputById[M]): Record<string, unknown>;
2633
- /** @deprecated Use `apis.run()` instead. Run a raw workflow (not tied to a model). */
2634
- runWorkflow<TResult = unknown>(workflow: string, payload: Record<string, unknown>, options?: WorkflowRunOptions): Promise<TResult>;
2635
2793
  /**
2636
2794
  * Direct, low-level access to the Picsart model APIs — run any API by name.
2637
2795
  * See {@link ApisClient}.
@@ -2661,22 +2819,15 @@ interface AiClient {
2661
2819
  * drive: { folder: 'AI Playground' },
2662
2820
  * });
2663
2821
  * ```
2822
+ *
2823
+ * @example With your own transport — the SDK stops talking to the workflows
2824
+ * API entirely, so `apiUrl` and the auth source are the transport's business:
2825
+ * ```ts
2826
+ * const ai = createClient({ transport: myTransport });
2827
+ * ```
2664
2828
  */
2665
- declare function createClient(config: ClientConfig | SdkTransport): AiClient;
2666
-
2667
- /**
2668
- * Typed Models constants and namespace.
2669
- * Regenerate with: npm run build:model-constants
2670
- */
2829
+ declare function createClient(config: ClientConfig): AiClient;
2671
2830
 
2672
- interface ValidationResult {
2673
- valid: boolean;
2674
- errors?: string[];
2675
- }
2676
- interface ModelFilter {
2677
- mode?: GenerationMode;
2678
- provider?: string;
2679
- }
2680
2831
  declare const Models: {
2681
2832
  readonly AsyncFlashV1: "async-flash-v1";
2682
2833
  readonly BytedanceOmnihumanV15: "bytedance-omnihuman-v1.5";
@@ -2793,7 +2944,6 @@ declare const Models: {
2793
2944
  readonly Lyria3Clip: "lyria-3-clip";
2794
2945
  readonly Lyria3Pro: "lyria-3-pro";
2795
2946
  readonly Lyria35: "lyria-3.5";
2796
- readonly Minimax02Hd: "minimax-02-hd";
2797
2947
  readonly MinimaxH3: "minimax-h3";
2798
2948
  readonly MinimaxH3Max: "minimax-h3-max";
2799
2949
  readonly MinimaxH3MaxCameraControls: "minimax-h3-max-camera-controls";
@@ -2903,21 +3053,6 @@ declare const Models: {
2903
3053
  readonly Wan27VideoEdit: "wan-2.7-video-edit";
2904
3054
  readonly Wan30Video: "wan-3.0-video";
2905
3055
  readonly Wan30VideoPrime: "wan-3.0-video-prime";
2906
- /** @deprecated Use the `catalog` accessor (`catalog.all()` / `catalog.find({ output, provider })`) instead. */
2907
- readonly list: (filter?: ModelFilter) => ModelDefinition[];
2908
- /** @deprecated Use `Model(id).validate(input)` instead. */
2909
- readonly validate: (model: string, input: unknown) => ValidationResult;
2910
- /** @deprecated Use `Model(id).params().toSchema()` instead. */
2911
- readonly toSchema: (id: string) => ModelParamSchema;
2912
- /** @deprecated Use `Model(id).params().file(key)` instead. */
2913
- readonly getFileParam: (id: string, key: string) => {
2914
- required: boolean;
2915
- max: number;
2916
- label?: string;
2917
- accept?: string;
2918
- } | null;
2919
- /** @deprecated Use `Model(id).params().hasParam(key)` instead. */
2920
- readonly hasParam: (id: string, key: string) => boolean;
2921
3056
  };
2922
3057
 
2923
3058
  /**
@@ -2927,61 +3062,6 @@ declare const Models: {
2927
3062
  */
2928
3063
 
2929
3064
  declare function getVoiceById(id: string): VoiceOption | undefined;
2930
- /** @deprecated Load the model's catalog instead (`ai.catalogs.voices(modelId)`) — loaded voices are searched automatically. */
2931
- declare function getVoiceById(id: string, extra: VoiceOption[] | undefined): VoiceOption | undefined;
2932
-
2933
- /**
2934
- * Failure codes the SDK synthesizes when the platform supplies no `reason`.
2935
- * An API-supplied `reason` passes through unchanged, so the open `string`
2936
- * member keeps arbitrary platform reasons assignable while preserving
2937
- * autocomplete on the known set.
2938
- */
2939
- type ApiErrorCode = 'unknown_model' | 'wrong_model_mode' | 'validation_error' | 'unsupported_transport' | 'timeout' | 'aborted' | 'canceled' | 'generation_failed' | 'invalid_response' | 'bad_request' | 'unauthorized' | 'payment_required' | 'forbidden' | 'not_found' | 'rate_limited' | 'server_error' | (string & {});
2940
- /** Everything but the message needed to build a {@link ApiError}. */
2941
- interface ApiErrorInit {
2942
- /**
2943
- * HTTP status of the failing response. When no HTTP exchange took place the
2944
- * SDK synthesizes the semantically matching code: 400 for input the SDK
2945
- * itself rejects, 408 for a poll deadline, 499 for an abort or cancel, 502
2946
- * for a response it cannot make sense of.
2947
- */
2948
- status: number;
2949
- /** Platform `reason` when present, otherwise an SDK-synthesized code. */
2950
- code: ApiErrorCode;
2951
- }
2952
- /**
2953
- * The single error type thrown by the SDK's generation surface —
2954
- * `generate()`, `generateText()`, `submit()`, and `result()`.
2955
- *
2956
- * Unrelated to the `Api*` types (`ApiResponse`, `ApiRunOptions`, …), which
2957
- * describe the low-level `ai.apis` surface. `ai.apis.run()` throws the
2958
- * workflows client's own errors, not this.
2959
- *
2960
- * ```ts
2961
- * try {
2962
- * await ai.generate(Models.Flux2Pro, { prompt: 'a cat' });
2963
- * } catch (err) {
2964
- * if (err instanceof ApiError) {
2965
- * if (err.status === 402) return topUpCredits();
2966
- * if (err.status === 429 || err.status >= 500) return retry();
2967
- * if (err.code === 'validation_error') return showFormError(err.message);
2968
- * }
2969
- * throw err;
2970
- * }
2971
- * ```
2972
- *
2973
- * Aborts raised by `fetch` itself are never wrapped — a caller checking
2974
- * `err.name === 'AbortError'` on a `DOMException` keeps working.
2975
- */
2976
- declare class ApiError extends Error {
2977
- /** HTTP status, or the synthesized equivalent for non-HTTP failures. */
2978
- readonly status: number;
2979
- /** Platform `reason`, or an SDK-synthesized code. Always equal to {@link reason}. */
2980
- readonly code: ApiErrorCode;
2981
- /** Alias of {@link code}, named after the platform's own error field. */
2982
- readonly reason: ApiErrorCode;
2983
- constructor(message: string, init: ApiErrorInit);
2984
- }
2985
3065
 
2986
3066
  /**
2987
3067
  * Pricing internals — owns the ModelPricingClient, the per-model cache, and
@@ -3025,7 +3105,7 @@ type ModelFunction = (id: string) => ModelDescriptor;
3025
3105
  declare function _all(filter?: {
3026
3106
  release?: readonly ReleaseTag[];
3027
3107
  }): ModelDescriptor[];
3028
- declare function _find(filter: ModelFilter$1): ModelDescriptor[];
3108
+ declare function _find(filter: ModelFilter): ModelDescriptor[];
3029
3109
  declare function _search(query: string, filter?: {
3030
3110
  release?: readonly ReleaseTag[];
3031
3111
  }): ModelDescriptor[];
@@ -3070,15 +3150,21 @@ declare function encodeDeepLinkPayload(modelId: string, context: Partial<Generat
3070
3150
  */
3071
3151
  declare function decodeDeepLinkPayload(encoded: string): DeepLinkResult | null;
3072
3152
 
3073
- /** All models from all vendors. */
3153
+ /**
3154
+ * All models from all vendors.
3155
+ * @deprecated Use `catalog.all()` — the descriptor accessors are the supported
3156
+ * surface; this raw array will be removed in the next major.
3157
+ */
3074
3158
  declare const ALL_MODELS: ModelDefinition[];
3075
3159
  /**
3076
3160
  * Models for a generation mode. By default returns only default-visible models
3077
- * (production / general-availability — preview, disabled and deprecated are
3078
- * hidden). `includeDisabled = true` returns every model of the mode, bypassing
3079
- * all gates. For release-tier filtering use `catalog.find({ output, release })`.
3161
+ * (production / general-availability — preview and deprecated are hidden).
3162
+ * `includeHidden = true` returns every model of the mode, bypassing all gates.
3163
+ * For release-tier filtering use `catalog.find({ output, release })`.
3164
+ * @deprecated Use `catalog.all().filter(m => m.mode === mode)` (or
3165
+ * `catalog.find({ output })`) — removed in the next major.
3080
3166
  */
3081
- declare const getModelsByMode: (mode: ModelDefinition["mode"], includeDisabled?: boolean) => ModelDefinition[];
3167
+ declare const getModelsByMode: (mode: ModelDefinition["mode"], includeHidden?: boolean) => ModelDefinition[];
3082
3168
 
3083
3169
  /**
3084
3170
  * Release tags shown by default in discovery. `preview` is stage-only and
@@ -3091,24 +3177,22 @@ declare const releaseOf: (m: ModelDefinition) => ReleaseTag;
3091
3177
  * Whether `m` is visible for the requested `releases` (default: the production
3092
3178
  * + general-availability set).
3093
3179
  *
3094
- * `disabled` and `deprecated` are hard hides layered on top of `release`: a
3095
- * model carrying either is never visible, regardless of its release tag or the
3096
- * requested set. (`disabled` is being phased out in favour of
3097
- * `release: 'preview'`, but is still honoured during the migration.)
3180
+ * `deprecated` is a hard hide layered on top of `release`: a deprecated model
3181
+ * is never visible, regardless of its release tag or the requested set.
3098
3182
  */
3099
3183
  declare function isVisibleForReleases(m: ModelDefinition, releases?: readonly ReleaseTag[]): boolean;
3100
3184
 
3101
- /** Look up a model by its ID or vendor modelId. */
3185
+ /**
3186
+ * Look up a model by its ID or vendor modelId.
3187
+ * @deprecated Use the `Model(id)` accessor (or `catalog.find(id)`) — this
3188
+ * raw-definition lookup will be removed in the next major.
3189
+ */
3102
3190
  declare const getModel: (id: string) => ModelDefinition | undefined;
3103
- /** Find a model by ID, workflow name, or display name (case-insensitive). */
3104
- declare const findModel: (ref: string) => ModelDefinition | undefined;
3105
-
3106
3191
  /**
3107
- * Effect scenes that require two input images (e.g. hugs, kisses, swaps).
3108
- * @deprecated Read `meta.imageSlots` on the `kling/v1/catalog/templates`
3109
- * catalog items instead this frozen copy is no longer maintained and will be
3110
- * removed in the next major.
3192
+ * Find a model by ID, workflow name, or display name (case-insensitive).
3193
+ * @deprecated Use `catalog.find(ref)` / `catalog.search(query)` — this
3194
+ * raw-definition lookup will be removed in the next major.
3111
3195
  */
3112
- declare const KLING_DUAL_IMAGE_EFFECTS: ReadonlySet<string>;
3196
+ declare const findModel: (ref: string) => ModelDefinition | undefined;
3113
3197
 
3114
- export { ALL_MODELS, type AiClient, ApiError, type ApiErrorCode, type ApiErrorInit, type ApiResponse, type ApiRunOptions, type ApiSchemas, type ApisClient, type AppIdentity, type AppType, type AuthenticatedFetch, type AvatarOption, type BooleanDescriptor, type BooleanEntry, type CatalogDescriptor, type CatalogEntry, type CatalogItem, type CatalogKind, type CatalogPage, type CatalogPageOptions, type CatalogPreview, type CatalogQuery, type CatalogResult, type CatalogSource, type CatalogsClient, type CatalogsOptions, type ClientConfig, type CreditRange, type CreditRangeContext, type CreditTier, type CreditUsage, DEFAULT_VISIBLE_RELEASES, type DeepLinkResult, type DriveAttributes, type DriveClient, type DriveConfig, type DriveFile, type DriveFileDetails, type DriveFolder, type DriveMediaItem, type DriveSaveResult, type EntryMeta, type EnumDescriptor, type EnumEntry, type EnumOption, type FileDescriptor, type FileEntry, type FlatParamEntry, type GenerateOptions, type GenerateResult, type GenerateResultItem, type GenerateTextResult, type GenerationContext, type GenerationFile, type GenerationMode, KLING_DUAL_IMAGE_EFFECTS, type ListOptions, type MediaModelId, type MediaTypeFilter, Model, type ModelDefinition, type ModelDescriptor, type ModelFilter$1 as ModelFilter, type ModelInput, type ModelInputById, type ModelMeta, type ModelParams, type ModelParamsAccessor, Models, type ObjectDescriptor, type ObjectEntry, type ParamDescriptor, type ParamEntry, type ParamOption, type PayloadDriveFolderOptions, type PayloadDriveOptions, type PayloadInputsTransformationOptions, type PricingOptions, type ProviderInfo, type RangeDescriptor, type RangeEntry, type ReleaseTag, type SaveParams, type SdkPayload, type SdkTransport, type TextDescriptor, type TextEntry, type TextModelId, type TextModelInputById, type ToolUsage, type TypedModelId, type UserReaction, type ValidationResult$1 as ValidationResult, type VoiceOption, type WorkflowJobHandle, buildFilename, buildGenerationAttributes, catalog, createClient, decodeDeepLinkPayload, encodeDeepLinkPayload, findModel, getModel, getModelsByMode, getVoiceById, inferResourceType, isVisibleForReleases, parseGeneration, releaseOf, toAvatarOption, toVoiceOption };
3198
+ export { ALL_MODELS, type AiClient, ApiError, type ApiErrorCode, type ApiErrorInit, type ApiResponse, type ApiRunOptions, type ApiSchemas, type ApisClient, type AppIdentity, type AppType, type AuthenticatedFetch, type AvatarOption, type BooleanDescriptor, type BooleanEntry, type CatalogDescriptor, type CatalogEntry, type CatalogItem, type CatalogPage, type CatalogPageOptions, type CatalogPreview, type CatalogQuery, type CatalogResult, type CatalogSource, type CatalogsClient, type CatalogsOptions, type ClientConfig, type CreditRange, type CreditRangeContext, type CreditTier, type CreditUsage, DEFAULT_VISIBLE_RELEASES, type DeepLinkResult, type DriveAttributes, type DriveClient, type DriveConfig, type DriveFile, type DriveFileDetails, type DriveFolder, type DriveMediaItem, type DriveSaveResult, type EntryMeta, type EnumDescriptor, type EnumEntry, type EnumOption, type FileDescriptor, type FileEntry, type FlatParamEntry, type GenerateOptions, type GenerateResult, type GenerateResultItem, type GenerateResultItemMetadata, type GenerateTextResult, type GenerationContext, type GenerationEvent, GenerationEventType, type GenerationFile, type GenerationMode, type GenerationOptions, type GenerationProgress, type ListOptions, type MediaModelId, type MediaTypeFilter, Model, type ModelDefinition, type ModelDescriptor, type ModelFilter, type ModelInput, type ModelInputById, type ModelMeta, type ModelParams, type ModelParamsAccessor, Models, type ObjectDescriptor, type ObjectEntry, type ParamDescriptor, type ParamEntry, type ParamOption, type PayloadDriveFolderOptions, type PayloadDriveOptions, type PayloadInputsTransformationOptions, type PricingOptions, type ProviderInfo, type RangeDescriptor, type RangeEntry, type ReleaseTag, type SaveParams, type SdkPayload, type SdkTransport, type TextDescriptor, type TextEntry, type TextModelId, type TextModelInputById, type ToolUsage, type TransportPollOptions, type TransportResult, type TypedModelId, type UserReaction, type ValidationResult, type VoiceOption, type WorkflowJobHandle, type WorkflowSubmitRequest, buildFilename, buildGenerationAttributes, catalog, createClient, decodeDeepLinkPayload, encodeDeepLinkPayload, findModel, getModel, getModelsByMode, getVoiceById, inferResourceType, isVisibleForReleases, parseGeneration, releaseOf, toAvatarOption, toVoiceOption };