totalum-sdk 1.11.0 → 1.12.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.
Files changed (51) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/_types/{coerce.d-BKhuaDya.d.ts → coerce.d-Cp5NZQN-.d.ts} +1 -1
  3. package/dist/_types/{errors.d-RTRkidv5.d.ts → errors.d-ve4rY-Hx.d.ts} +37 -5
  4. package/dist/_types/{integrations.d-CzTa9T-L.d.ts → integrations.d-BRhNKT7K.d.ts} +2 -2
  5. package/dist/_types/{ops.d-CNsrT4Ma.d.ts → ops.d-DIC4u0go.d.ts} +2 -2
  6. package/dist/ai/index.d.ts +275 -23
  7. package/dist/ai/index.js +305 -24
  8. package/dist/analytics/index.d.ts +58 -12
  9. package/dist/analytics/index.js +46 -3
  10. package/dist/browser/index.d.ts +228 -20
  11. package/dist/browser/index.js +122 -13
  12. package/dist/connections/index.d.ts +305 -23
  13. package/dist/connections/index.js +302 -21
  14. package/dist/cron/index.d.ts +147 -20
  15. package/dist/cron/index.js +157 -15
  16. package/dist/d1/errors.js +15 -0
  17. package/dist/d1/index.d.ts +254 -10
  18. package/dist/d1/index.js +24 -4
  19. package/dist/d1/session.js +26 -2
  20. package/dist/email/index.d.ts +65 -10
  21. package/dist/email/index.js +60 -5
  22. package/dist/errors.js +17 -0
  23. package/dist/files/index.d.ts +243 -20
  24. package/dist/files/index.js +247 -14
  25. package/dist/index.d.ts +25 -10
  26. package/dist/index.js +19 -5
  27. package/dist/logs/index.d.ts +48 -10
  28. package/dist/logs/index.js +39 -4
  29. package/dist/payments/index.d.ts +221 -23
  30. package/dist/payments/index.js +216 -18
  31. package/dist/pdf/index.d.ts +59 -9
  32. package/dist/pdf/index.js +54 -4
  33. package/dist/react/index.d.ts +78 -6
  34. package/dist/react/index.js +51 -5
  35. package/dist/realtime/index.d.ts +55 -8
  36. package/dist/realtime/index.js +53 -6
  37. package/dist/scan/index.d.ts +78 -10
  38. package/dist/scan/index.js +63 -3
  39. package/dist/seo/index.d.ts +1118 -8
  40. package/dist/seo/index.js +325 -4
  41. package/dist/speech/index.d.ts +34 -10
  42. package/dist/speech/index.js +25 -5
  43. package/dist/vectors/index.d.ts +96 -9
  44. package/dist/vectors/index.js +93 -7
  45. package/dist/web/index.d.ts +168 -15
  46. package/dist/web/index.js +163 -10
  47. package/dist/webhooks/index.d.ts +122 -15
  48. package/dist/webhooks/index.js +119 -13
  49. package/package.json +2 -1
  50. package/totalum-sdk.md +10336 -754
  51. package/totalum-sdk.signatures.json +69 -1
package/CHANGELOG.md CHANGED
@@ -20,6 +20,26 @@ regenerated), plus the request each call sends to SDK-API (`compat/requests/*.js
20
20
  - **Dist-tags:** `next` is the newest release; `latest` moves only by a decision at launch. `dev` holds the old
21
21
  `0.1.0-dev.N` prereleases.
22
22
 
23
+ ## 1.12.0 — 2026-11-26
24
+
25
+ - **`totalum.seo` research** (`totalum-sdk/seo`): what ranks on Google and what AI assistants answer, for a country
26
+ and language — `serp.google` (organic results, featured snippet, "People also ask", related searches, AI
27
+ Overview), `serp.aiMode`, `serp.maps`; `ai.answer` (ChatGPT, Claude, Gemini, Perplexity), `ai.chatgptSearch`,
28
+ `ai.mentions`, `ai.keywordVolume`; `keywords.ideas`, `keywords.related`, `keywords.overview`, `keywords.trends`;
29
+ `domain.keywords`, `domain.competitors`, `domain.keywordGap`, `domain.backlinks`; `page.analyze`; and the free
30
+ `locations()`. Billed in credits (`usage.credits` on every result); the plan limits the calls per minute and per
31
+ month (`RATE_LIMIT_EXCEEDED`). New error codes documented: `NOT_AVAILABLE_IN_COUNTRY`, `SEO_REQUEST_REJECTED`,
32
+ `SEO_CITY_NOT_FOUND`.
33
+
34
+ ## 1.11.1 — 2026-10-11
35
+
36
+ - Documentation only: `totalum-sdk.md` is rewritten as a readable reference — a quick start, a table of contents, an
37
+ overview per module, and for every method a plain-language description, a parameters table (type, required, meaning,
38
+ allowed values), the result field by field, its errors and a real example with its result; every exported type has
39
+ a field table, and the browser session's 67 commands a table. `pnpm docs:coverage` (CI) fails when any exported
40
+ symbol, method, parameter, returned field, type field or browser command is undocumented. JSDoc only in `src/`: no
41
+ runtime, public type or request change; `totalum-sdk.signatures.json` keeps its rows.
42
+
23
43
  ## 1.11.0 — 2026-10-11
24
44
 
25
45
  - **New namespace `totalum.connections`** (`totalum-sdk/connections`): your app's users connect their own accounts of
@@ -1,4 +1,4 @@
1
- import { _ as _ZodNumber, z as $ZodNumberInternals } from './errors.d-RTRkidv5.js';
1
+ import { _ as _ZodNumber, C as $ZodNumberInternals } from './errors.d-ve4rY-Hx.js';
2
2
 
3
3
  interface ZodCoercedNumber<T = unknown> extends _ZodNumber<$ZodNumberInternals<T>> {
4
4
  }
@@ -1072,8 +1072,10 @@ type $InferZodRecordOutput<Key extends $ZodRecordKey = $ZodRecordKey, Value exte
1072
1072
  type $InferZodRecordInput<Key extends $ZodRecordKey = $ZodRecordKey, Value extends SomeType = $ZodType> = Key extends $partial ? Partial<Record<input<Key> & PropertyKey, input<Value>>> : [
1073
1073
  Value
1074
1074
  ] extends [OptionalInSchema] ? Partial<Record<input<Key> & PropertyKey, input<Value>>> : Record<input<Key> & PropertyKey, input<Value>>;
1075
- interface $ZodRecordInternals<Key extends $ZodRecordKey = $ZodRecordKey, Value extends SomeType = $ZodType> extends $ZodTypeInternals<$InferZodRecordOutput<Key, Value>, $InferZodRecordInput<Key, Value>> {
1075
+ interface $ZodRecordInternals<Key extends $ZodRecordKey = $ZodRecordKey, Value extends SomeType = $ZodType> extends $ZodTypeInternals {
1076
1076
  def: $ZodRecordDef<Key, Value>;
1077
+ output: $InferZodRecordOutput<Key, Value>;
1078
+ input: $InferZodRecordInput<Key, Value>;
1077
1079
  isst: $ZodIssueInvalidType | $ZodIssueInvalidKey<Record<PropertyKey, unknown>>;
1078
1080
  optin?: "optional" | undefined;
1079
1081
  optout?: "optional" | undefined;
@@ -2323,6 +2325,7 @@ declare const ErrorCode: ZodEnum<{
2323
2325
  PROJECT_SUSPENDED: "PROJECT_SUSPENDED";
2324
2326
  PROJECT_HIBERNATED: "PROJECT_HIBERNATED";
2325
2327
  PROJECT_DELETED: "PROJECT_DELETED";
2328
+ PROJECT_DELETE_PROTECTED: "PROJECT_DELETE_PROTECTED";
2326
2329
  PROJECT_PAUSED_BY_USER: "PROJECT_PAUSED_BY_USER";
2327
2330
  LIFECYCLE_NOT_APPLICABLE: "LIFECYCLE_NOT_APPLICABLE";
2328
2331
  PROJECT_NOT_PAUSED: "PROJECT_NOT_PAUSED";
@@ -2334,6 +2337,7 @@ declare const ErrorCode: ZodEnum<{
2334
2337
  INSUFFICIENT_CREDITS: "INSUFFICIENT_CREDITS";
2335
2338
  VCAAS_INSUFFICIENT_CREDITS: "VCAAS_INSUFFICIENT_CREDITS";
2336
2339
  PROJECT_CREDIT_LIMIT_REACHED: "PROJECT_CREDIT_LIMIT_REACHED";
2340
+ DEV_INFRASTRUCTURE_LIMIT_REACHED: "DEV_INFRASTRUCTURE_LIMIT_REACHED";
2337
2341
  FREE_PROMPTS_DISABLED: "FREE_PROMPTS_DISABLED";
2338
2342
  PLAN_REQUIRED: "PLAN_REQUIRED";
2339
2343
  FEATURE_LIMIT_REACHED: "FEATURE_LIMIT_REACHED";
@@ -2347,6 +2351,7 @@ declare const ErrorCode: ZodEnum<{
2347
2351
  IMPORT_IN_PROGRESS: "IMPORT_IN_PROGRESS";
2348
2352
  MIGRATION_TOO_LARGE: "MIGRATION_TOO_LARGE";
2349
2353
  MIGRATION_START_FAILED: "MIGRATION_START_FAILED";
2354
+ MIGRATION_ALREADY_PUBLISHED: "MIGRATION_ALREADY_PUBLISHED";
2350
2355
  TOO_MANY_RUN_REQUESTS: "TOO_MANY_RUN_REQUESTS";
2351
2356
  PROMPT_SECURITY_VIOLATION: "PROMPT_SECURITY_VIOLATION";
2352
2357
  NO_PROCESS_RUNNING: "NO_PROCESS_RUNNING";
@@ -2629,6 +2634,9 @@ declare const ErrorCode: ZodEnum<{
2629
2634
  LIVE_CRON_READ_ONLY: "LIVE_CRON_READ_ONLY";
2630
2635
  URL_NOT_PROJECT_HOST: "URL_NOT_PROJECT_HOST";
2631
2636
  INDEXNOW_ERROR: "INDEXNOW_ERROR";
2637
+ NOT_AVAILABLE_IN_COUNTRY: "NOT_AVAILABLE_IN_COUNTRY";
2638
+ SEO_REQUEST_REJECTED: "SEO_REQUEST_REJECTED";
2639
+ SEO_CITY_NOT_FOUND: "SEO_CITY_NOT_FOUND";
2632
2640
  MCP_VERIFY_FAILED: "MCP_VERIFY_FAILED";
2633
2641
  MCP_NAME_RESERVED: "MCP_NAME_RESERVED";
2634
2642
  MCP_LIMIT_REACHED: "MCP_LIMIT_REACHED";
@@ -2744,6 +2752,7 @@ declare const ErrorBody: ZodObject<{
2744
2752
  PROJECT_SUSPENDED: "PROJECT_SUSPENDED";
2745
2753
  PROJECT_HIBERNATED: "PROJECT_HIBERNATED";
2746
2754
  PROJECT_DELETED: "PROJECT_DELETED";
2755
+ PROJECT_DELETE_PROTECTED: "PROJECT_DELETE_PROTECTED";
2747
2756
  PROJECT_PAUSED_BY_USER: "PROJECT_PAUSED_BY_USER";
2748
2757
  LIFECYCLE_NOT_APPLICABLE: "LIFECYCLE_NOT_APPLICABLE";
2749
2758
  PROJECT_NOT_PAUSED: "PROJECT_NOT_PAUSED";
@@ -2755,6 +2764,7 @@ declare const ErrorBody: ZodObject<{
2755
2764
  INSUFFICIENT_CREDITS: "INSUFFICIENT_CREDITS";
2756
2765
  VCAAS_INSUFFICIENT_CREDITS: "VCAAS_INSUFFICIENT_CREDITS";
2757
2766
  PROJECT_CREDIT_LIMIT_REACHED: "PROJECT_CREDIT_LIMIT_REACHED";
2767
+ DEV_INFRASTRUCTURE_LIMIT_REACHED: "DEV_INFRASTRUCTURE_LIMIT_REACHED";
2758
2768
  FREE_PROMPTS_DISABLED: "FREE_PROMPTS_DISABLED";
2759
2769
  PLAN_REQUIRED: "PLAN_REQUIRED";
2760
2770
  FEATURE_LIMIT_REACHED: "FEATURE_LIMIT_REACHED";
@@ -2768,6 +2778,7 @@ declare const ErrorBody: ZodObject<{
2768
2778
  IMPORT_IN_PROGRESS: "IMPORT_IN_PROGRESS";
2769
2779
  MIGRATION_TOO_LARGE: "MIGRATION_TOO_LARGE";
2770
2780
  MIGRATION_START_FAILED: "MIGRATION_START_FAILED";
2781
+ MIGRATION_ALREADY_PUBLISHED: "MIGRATION_ALREADY_PUBLISHED";
2771
2782
  TOO_MANY_RUN_REQUESTS: "TOO_MANY_RUN_REQUESTS";
2772
2783
  PROMPT_SECURITY_VIOLATION: "PROMPT_SECURITY_VIOLATION";
2773
2784
  NO_PROCESS_RUNNING: "NO_PROCESS_RUNNING";
@@ -3050,6 +3061,9 @@ declare const ErrorBody: ZodObject<{
3050
3061
  LIVE_CRON_READ_ONLY: "LIVE_CRON_READ_ONLY";
3051
3062
  URL_NOT_PROJECT_HOST: "URL_NOT_PROJECT_HOST";
3052
3063
  INDEXNOW_ERROR: "INDEXNOW_ERROR";
3064
+ NOT_AVAILABLE_IN_COUNTRY: "NOT_AVAILABLE_IN_COUNTRY";
3065
+ SEO_REQUEST_REJECTED: "SEO_REQUEST_REJECTED";
3066
+ SEO_CITY_NOT_FOUND: "SEO_CITY_NOT_FOUND";
3053
3067
  MCP_VERIFY_FAILED: "MCP_VERIFY_FAILED";
3054
3068
  MCP_NAME_RESERVED: "MCP_NAME_RESERVED";
3055
3069
  MCP_LIMIT_REACHED: "MCP_LIMIT_REACHED";
@@ -3144,17 +3158,18 @@ type ErrorBody = output<typeof ErrorBody>;
3144
3158
  interface TotalumClientOptions {
3145
3159
  /** Project key `tlm_pk_…`; default `TOTALUM_PROJECT_KEY`. Server-side only. */
3146
3160
  key?: string;
3147
- /** Default `TOTALUM_SDK_API_URL`, else `https://sdk-api.totalum.app`. */
3161
+ /** The Totalum API's URL: default `TOTALUM_SDK_API_URL`, else `https://sdk-api.totalum.app`. */
3148
3162
  apiUrl?: string;
3149
3163
  /** Sent as `x-totalum-env` on every call (the database it targets, and dev vs live usage); default `TOTALUM_ENV`, else `live`. */
3150
3164
  env?: 'dev' | 'live';
3151
3165
  }
3152
3166
  /** What a call was charged, in Totalum credits: the only usage Totalum shows (never a vendor, units or a cost). */
3153
3167
  interface Usage {
3168
+ /** Credits charged for this call. */
3154
3169
  credits: number;
3155
3170
  }
3156
3171
 
3157
- /** Every code a `TotalumError` can carry: the Totalum API's frozen codes plus the client-side ones. */
3172
+ /** Every code a `TotalumError` can carry: the Totalum API's frozen codes plus the client-side ones (see Errors). */
3158
3173
  type TotalumErrorCode = ErrorCode | SdkClientErrorCode;
3159
3174
  /**
3160
3175
  * The one error every `totalum-sdk` call throws: the Totalum API envelope's frozen `errorCode`, the HTTP
@@ -3162,10 +3177,13 @@ type TotalumErrorCode = ErrorCode | SdkClientErrorCode;
3162
3177
  * extend it, so one `isTotalumError(e)` check covers the whole package.
3163
3178
  */
3164
3179
  declare class TotalumError extends Error {
3180
+ /** `'TotalumError'` (or the subclass's name). */
3165
3181
  name: string;
3182
+ /** The frozen error code (`FILE_NOT_FOUND`, `INSUFFICIENT_CREDITS`, …): branch on it, never on `message`. */
3166
3183
  readonly errorCode: TotalumErrorCode;
3167
3184
  /** HTTP status; 0 for network errors, 500 for client-side refusals. */
3168
3185
  readonly status: number;
3186
+ /** Extra data about the failure (`maxBytes`, `retryAfterMs`, the field that failed validation), when any. */
3169
3187
  readonly details: Record<string, unknown> | undefined;
3170
3188
  /** the Totalum API's request id, for support and the logs explorer. */
3171
3189
  readonly requestId: string | undefined;
@@ -3175,7 +3193,21 @@ declare class TotalumError extends Error {
3175
3193
  /** Every field a log or `Response.json` needs (undefined ones drop out); workerd's tail logs an Error through this. */
3176
3194
  toJSON(): Record<string, unknown>;
3177
3195
  }
3196
+ /**
3197
+ * Whether `e` is an error thrown by `totalum-sdk` (`TotalumError` or a subclass): then `e.errorCode`, `e.status`,
3198
+ * `e.details` and `e.requestId` are typed.
3199
+ *
3200
+ * @param e - Anything caught.
3201
+ * @returns `true` for a `TotalumError`.
3202
+ * @example
3203
+ * try {
3204
+ * await totalum.email.send(msg);
3205
+ * } catch (e) {
3206
+ * if (isTotalumError(e) && e.errorCode === 'INSUFFICIENT_CREDITS') return Response.json({ error: 'Out of credits' }, { status: 402 });
3207
+ * throw e;
3208
+ * }
3209
+ */
3178
3210
  declare function isTotalumError(e: unknown): e is TotalumError;
3179
3211
 
3180
- export { ErrorBody as E, ZodObject as Z, TotalumError as a, ZodOptional as c, ZodString as d, ZodArray as e, ZodEnum as f, ZodUnknown as g, ZodRecord as h, isTotalumError as i, ZodBoolean as j, ZodNumber as k, ZodUnion as n, ZodURL as p, ZodLiteral as r, ZodType as s, ZodISODateTime as u, ZodNullable as w, ZodEmail as y };
3181
- export type { $loose as $, SdkClientErrorCode as S, TotalumClientOptions as T, Usage as U, _ZodNumber as _, TotalumErrorCode as b, ZodInt as l, $strip as m, output as o, $partial as q, $ZodTypeInternals as t, $catchall as v, $strict as x, $ZodNumberInternals as z };
3212
+ export { ZodEmail as B, ErrorBody as E, ZodObject as Z, TotalumError as a, ZodOptional as c, ZodString as d, ZodArray as e, ZodEnum as f, ZodUnknown as g, ZodRecord as h, isTotalumError as i, ZodBoolean as j, ZodNumber as k, ZodUnion as n, ZodURL as p, ZodLiteral as r, ZodType as s, ZodISODateTime as u, ZodNullable as w, ZodDefault as x, ZodPipe as y, ZodTransform as z };
3213
+ export type { $loose as $, $strict as A, $ZodNumberInternals as C, SdkClientErrorCode as S, TotalumClientOptions as T, Usage as U, _ZodNumber as _, TotalumErrorCode as b, ZodInt as l, $strip as m, output as o, $partial as q, $ZodTypeInternals as t, $catchall as v };
@@ -1,5 +1,5 @@
1
- import { Z as ZodObject, d as ZodString, c as ZodOptional, f as ZodEnum, k as ZodNumber, j as ZodBoolean, m as $strip, o as output, p as ZodURL, e as ZodArray, n as ZodUnion, l as ZodInt, h as ZodRecord, w as ZodNullable, u as ZodISODateTime, y as ZodEmail, r as ZodLiteral, g as ZodUnknown } from './errors.d-RTRkidv5.js';
2
- import { Z as ZodCoercedNumber } from './coerce.d-BKhuaDya.js';
1
+ import { Z as ZodObject, d as ZodString, c as ZodOptional, f as ZodEnum, k as ZodNumber, j as ZodBoolean, m as $strip, o as output, p as ZodURL, e as ZodArray, n as ZodUnion, l as ZodInt, h as ZodRecord, w as ZodNullable, u as ZodISODateTime, B as ZodEmail, r as ZodLiteral, g as ZodUnknown } from './errors.d-ve4rY-Hx.js';
2
+ import { Z as ZodCoercedNumber } from './coerce.d-Cp5NZQN-.js';
3
3
 
4
4
  /** `202` of every async integration call; `estimatedCredits` = the reserved estimate (settled to the real cost). */
5
5
  declare const JobCreated: ZodObject<{
@@ -1,5 +1,5 @@
1
- import { Z as ZodObject, c as ZodOptional, e as ZodArray, u as ZodISODateTime, v as $catchall, k as ZodNumber, d as ZodString, f as ZodEnum, m as $strip, r as ZodLiteral, j as ZodBoolean, o as output, w as ZodNullable, l as ZodInt } from './errors.d-RTRkidv5.js';
2
- import { Z as ZodCoercedNumber } from './coerce.d-BKhuaDya.js';
1
+ import { Z as ZodObject, c as ZodOptional, e as ZodArray, u as ZodISODateTime, v as $catchall, k as ZodNumber, d as ZodString, f as ZodEnum, m as $strip, r as ZodLiteral, j as ZodBoolean, o as output, w as ZodNullable, l as ZodInt } from './errors.d-ve4rY-Hx.js';
2
+ import { Z as ZodCoercedNumber } from './coerce.d-Cp5NZQN-.js';
3
3
 
4
4
  declare const SiteMetric: ZodEnum<{
5
5
  bytes: "bytes";
@@ -1,8 +1,8 @@
1
1
  import { SpeechAudio } from '../speech/index.js';
2
- import { Z as ZodObject, c as ZodOptional, d as ZodString, e as ZodArray, f as ZodEnum, g as ZodUnknown, $ as $loose, h as ZodRecord, j as ZodBoolean, k as ZodNumber, l as ZodInt, m as $strip, o as output, n as ZodUnion, p as ZodURL, q as $partial, r as ZodLiteral, T as TotalumClientOptions, U as Usage } from '../_types/errors.d-RTRkidv5.js';
3
- export { a as TotalumError, b as TotalumErrorCode, i as isTotalumError } from '../_types/errors.d-RTRkidv5.js';
2
+ import { Z as ZodObject, c as ZodOptional, d as ZodString, e as ZodArray, f as ZodEnum, g as ZodUnknown, $ as $loose, h as ZodRecord, j as ZodBoolean, k as ZodNumber, l as ZodInt, m as $strip, o as output, n as ZodUnion, p as ZodURL, q as $partial, r as ZodLiteral, T as TotalumClientOptions, U as Usage } from '../_types/errors.d-ve4rY-Hx.js';
3
+ export { a as TotalumError, b as TotalumErrorCode, i as isTotalumError } from '../_types/errors.d-ve4rY-Hx.js';
4
4
  import { SpeakInput, StoredMedia, TranscribeInput } from '../index.js';
5
- import '../_types/coerce.d-BKhuaDya.js';
5
+ import '../_types/coerce.d-Cp5NZQN-.js';
6
6
 
7
7
  /**
8
8
  * Named model presets: the Totalum API resolves each to an model id refreshed from the model catalogue to the newest non-deprecated model of the preset's family. A `model`
@@ -203,12 +203,14 @@ declare const AiModelsOutput: ZodObject<{
203
203
  }, $strip>;
204
204
  type AiModelsOutput = output<typeof AiModelsOutput>;
205
205
 
206
+ /** The options of `totalumAi()`: the client options plus the AI gateway URL `gatewayConfig()` returns. */
206
207
  interface TotalumAiOptions extends TotalumClientOptions {
207
208
  /** The OpenAI-compatible AI gateway `gatewayConfig()` returns; default `TOTALUM_AI_BASE_URL`, else `https://ai.totalum.app/api/v1`. */
208
209
  aiBaseUrl?: string;
209
210
  }
210
211
  /** What a call was charged, in Totalum credits — the only usage Totalum shows (no tokens). */
211
212
  interface ChatUsage {
213
+ /** Credits charged for this call. */
212
214
  credits: number;
213
215
  /** @deprecated Since 1.1.0: always 0 — Totalum shows only `credits`. */
214
216
  inputTokens: number;
@@ -216,45 +218,117 @@ interface ChatUsage {
216
218
  outputTokens: number;
217
219
  }
218
220
  interface ToolCall {
221
+ /** The call's id: send the tool's answer back as a `tool` message with this `tool_call_id`. */
219
222
  id: string;
223
+ /** Always `function`. */
220
224
  type: string;
225
+ /** The function the model wants to call. */
221
226
  function: {
227
+ /** The tool's name, as you declared it in `tools`. */
222
228
  name: string;
229
+ /** Its arguments as a JSON string: `JSON.parse` it. */
223
230
  arguments: string;
224
231
  };
225
232
  }
226
233
  /** `ai.chat()`: the first choice read out, the raw completion kept. */
227
234
  interface ChatResult {
235
+ /** The completion's id. */
228
236
  id: string;
237
+ /** The model that answered (a preset resolves to the model it currently points to). */
229
238
  model: string;
239
+ /** The answer's text (empty when the model only called tools). */
230
240
  text: string;
241
+ /** The tools the model asks you to call (with `tools`); empty otherwise. */
231
242
  toolCalls: ToolCall[];
243
+ /** Why it stopped: `stop` (finished), `length` (hit `maxTokens`), `tool_calls`, `content_filter`, or `null`. */
232
244
  finishReason: string | null;
245
+ /** What the call cost. */
233
246
  usage: ChatUsage;
247
+ /** The whole OpenAI-format completion, as received. */
234
248
  raw: unknown;
235
249
  }
236
250
  /** `ai.chat.stream()`: the OpenAI-format SSE (`raw`), its text deltas, and the result once it ends. */
237
251
  interface ChatStream {
252
+ /**
253
+ * The OpenAI-format server-sent events, as received: return them from a route (`new Response(stream.raw)`) to
254
+ * stream to the browser. Read either `raw` or `text()`, not both.
255
+ */
238
256
  readonly raw: ReadableStream<Uint8Array>;
257
+ /**
258
+ * The answer's text pieces as they arrive (one pass): `for await (const piece of stream.text())`.
259
+ *
260
+ * @returns An async iterable of text pieces.
261
+ * @example
262
+ * const stream = await totalum.ai.chat.stream({ model: 'fast', messages: [{ role: 'user', content: 'Count 1 to 3.' }] });
263
+ * for await (const piece of stream.text()) process.stdout.write(piece);
264
+ * //=>
265
+ * "1" ", " "2" ", " "3" "."
266
+ */
239
267
  text(): AsyncIterable<string>;
268
+ /**
269
+ * The final result once the stream ends, with its credits (reads the rest of the stream if needed).
270
+ *
271
+ * @returns The same result `chat()` returns; `raw` holds the accumulated text.
272
+ * @throws AI_STREAM_ERROR (502) The stream broke before the end.
273
+ * @example
274
+ * const stream = await totalum.ai.chat.stream({ model: 'fast', messages: [{ role: 'user', content: 'Count 1 to 3.' }] });
275
+ * const result = await stream.result();
276
+ * //=>
277
+ * {
278
+ * "id": "gen-1791740371-wfMT8WhpKYrAEa1s9XKT",
279
+ * "model": "openai/gpt-6-luna",
280
+ * "text": "1, 2, 3.",
281
+ * "toolCalls": [],
282
+ * "finishReason": "stop",
283
+ * "usage": { "credits": 0.0005, "inputTokens": 0, "outputTokens": 0 },
284
+ * "raw": { "id": "gen-1791740371-wfMT8WhpKYrAEa1s9XKT", "model": "openai/gpt-6-luna", "text": "1, 2, 3.", "choices": [{ "message": { "content": "1, 2, 3." }, "finish_reason": "stop" }] }
285
+ * }
286
+ */
240
287
  result(): Promise<ChatResult>;
241
288
  }
242
289
  /**
243
- * `totalum.ai` over the Totalum API `/v1/ai/*` (scope `ai`): a `model` is a preset (`fast`,
290
+ * Creates the `ai` namespace (the same object as `totalum.ai`, scope `ai`): a `model` is a preset (`fast`,
244
291
  * `smart`, `reasoning`, `vision`, `image`, `image-edit`, `video`, `tts`, `stt`, `embed` — each follows the newest model
245
- * of its family, resolved by Totalum) or a pinned model id; every call returned with the Totalum credits it was
246
- * charged (`usage.credits`, never tokens). No `ai.agent()` — the
247
- * agent loop is the template's `src/agents/` on the Vercel AI SDK, pointed at `gatewayConfig()`.
292
+ * of its family, resolved by Totalum) or a pinned model id; every call returns the Totalum credits it was charged
293
+ * (`usage.credits`, never tokens). There is no `ai.agent()`: an agent loop runs on an OpenAI-compatible library (the
294
+ * template's `src/agents/` uses the Vercel AI SDK) pointed at `gatewayConfig()`, which reaches the same models with the
295
+ * same key, billed in credits. Vector search is `totalum.vectors`.
248
296
  *
249
- * New app code calls OpenRouter's API through the AI gateway instead (`gatewayConfig()`: same key, billed in
250
- * credits): text, vision, images, video jobs, text-to-speech, transcription, embeddings and rerank, any OpenRouter
251
- * model. These methods keep working; vector search is `totalum.vectors`.
297
+ * @param options - The project key, API URL, environment and AI gateway URL; each falls back to its environment
298
+ * variable.
299
+ * @returns The `ai` namespace: the methods below.
300
+ * @example
301
+ * import { totalumAi } from 'totalum-sdk/ai';
302
+ *
303
+ * const ai = totalumAi();
304
+ * const { text } = await ai.chat({ messages: [{ role: 'user', content: 'Hello' }] });
252
305
  */
253
306
  declare function totalumAi(options?: TotalumAiOptions): {
254
307
  chat: ((req: Omit<AiChatInput, "stream">) => Promise<ChatResult>) & {
255
308
  /**
256
- * The same request streamed: `raw` is the OpenAI-format SSE (return it from a route), `text()` its deltas,
257
- * `result()` the final result with its credits.
309
+ * The same request, streamed: the answer arrives piece by piece, for a chat UI that types as it goes. `raw` is
310
+ * the OpenAI-format server-sent events (return it from a route), `text()` the text pieces, `result()` the final
311
+ * result with its credits.
312
+ *
313
+ * @param req - The same input as `chat()`.
314
+ * @returns The stream handle: `raw`, `text()` and `result()`.
315
+ * @throws AI_STREAM_ERROR (502) The model returned no stream.
316
+ * @throws AI_MODEL_UNKNOWN (400) No such preset or model id.
317
+ * @throws AI_MODEL_NOT_ALLOWED (403) The model is not available on this plan.
318
+ * @example
319
+ * // src/app/api/chat/route.ts — stream the answer to the browser
320
+ * export async function POST(request: Request) {
321
+ * const { messages } = await request.json();
322
+ * const stream = await totalum.ai.chat.stream({ model: 'fast', messages });
323
+ * return new Response(stream.raw, { headers: { 'content-type': 'text/event-stream' } });
324
+ * }
325
+ * @example
326
+ * const stream = await totalum.ai.chat.stream({ model: 'fast', messages: [{ role: 'user', content: 'Count 1 to 3.' }] });
327
+ * let text = '';
328
+ * for await (const piece of stream.text()) text += piece;
329
+ * const { usage } = await stream.result();
330
+ * //=>
331
+ * text = "1, 2, 3." usage = { credits: 0.0005, inputTokens: 0, outputTokens: 0 }
258
332
  */
259
333
  stream: (req: Omit<AiChatInput, "stream">) => Promise<ChatStream>;
260
334
  };
@@ -265,19 +339,54 @@ declare function totalumAi(options?: TotalumAiOptions): {
265
339
  model?: string;
266
340
  healing?: boolean;
267
341
  }) => Promise<{
342
+ /** The JSON object, matching `schema`. */
268
343
  object: unknown;
344
+ /** What the call cost. */
269
345
  usage: Usage;
270
346
  }>;
271
- /** Sugar over `generateObject`: one of `options`, chosen by the model. */
347
+ /**
348
+ * Picks one label out of your list for an input — route a support ticket, tag a review, detect a language. Sugar
349
+ * over `generateObject`.
350
+ *
351
+ * @param req - The input, the labels and optional instructions.
352
+ * @param req.input - The text to classify.
353
+ * @param req.options - The labels to choose from.
354
+ * @param req.model - A preset or model id. Default `smart`.
355
+ * @param req.instructions - How to choose, in words. Default: "Classify the input into exactly one label."
356
+ * @returns `{ label }`: one of `options` (or `''` if the model gave none).
357
+ * @throws AI_INVALID_SCHEMA (502) The model did not answer a label.
358
+ * @throws AI_MODEL_UNKNOWN (400) No such preset or model id.
359
+ * @example
360
+ * const { label } = await totalum.ai.classify({
361
+ * input: 'My card was charged twice',
362
+ * options: ['billing', 'bug', 'other'],
363
+ * model: 'fast',
364
+ * });
365
+ * //=>
366
+ * { "label": "billing" }
367
+ */
272
368
  classify(req: {
273
369
  input: string;
274
370
  options: readonly string[];
275
371
  model?: string;
276
372
  instructions?: string;
277
373
  }): Promise<{
374
+ /** The chosen label: one of `options`, or `''` when the model gave none. */
278
375
  label: string;
279
376
  }>;
280
- /** Embedding vectors for one or more texts. */
377
+ /**
378
+ * Turns texts into embedding vectors (lists of numbers whose distance measures meaning). To store and search them,
379
+ * `totalum.vectors` does the embedding for you; use this for your own similarity maths.
380
+ *
381
+ * @param req - The texts and the model.
382
+ * @returns One vector per input, in order, and what it cost.
383
+ * @throws AI_MODEL_UNKNOWN (400) No such preset or model id.
384
+ * @throws AI_PROVIDER_UNAVAILABLE (502) The model did not answer; retry.
385
+ * @example
386
+ * const { embeddings } = await totalum.ai.embed({ input: ['red shoes', 'blue sandals'] });
387
+ * //=>
388
+ * { "embeddings": [[0.0138, -0.0121, 0.0125, …], [0.0042, -0.0337, 0.0198, …]], "usage": { "credits": 0.0001 } }
389
+ */
281
390
  embed: (req: AiEmbedInput) => Promise<{
282
391
  embeddings: number[][];
283
392
  usage: {
@@ -285,7 +394,30 @@ declare function totalumAi(options?: TotalumAiOptions): {
285
394
  };
286
395
  }>;
287
396
  image: {
288
- /** Images from a prompt; `store: true` keeps them as project files. */
397
+ /**
398
+ * Generates images from a prompt — illustrations, product shots, avatars, hero images — and stores each one as a
399
+ * public project file. Generate once and save the `key`: never generate on every page view.
400
+ *
401
+ * @param req - The prompt, the model, the size and how many.
402
+ * @returns The stored images and what they cost.
403
+ * @throws AI_MODEL_UNKNOWN (400) No such preset or model id.
404
+ * @throws AI_MODEL_NOT_ALLOWED (403) The model is not available on this plan.
405
+ * @throws AI_PROVIDER_UNAVAILABLE (502) The model returned no image; retry or change the prompt.
406
+ * @example
407
+ * const { images } = await totalum.ai.image.generate({
408
+ * prompt: 'A watercolor fox reading a book, warm light',
409
+ * aspectRatio: '16:9',
410
+ * });
411
+ * //=>
412
+ * {
413
+ * "images": [
414
+ * { "key": "p/acme-crm/01M4P1J2K3L4M5N6P7Q8R9S0TV.png", "url": "https://files.totalum-project.com/p/acme-crm/01M4P1J2K3L4M5N6P7Q8R9S0TV.png", "mediaType": "image/png", "width": 1344, "height": 768 }
415
+ * ],
416
+ * "usage": { "credits": 0.2741 },
417
+ * "fileName": "01M4P1J2K3L4M5N6P7Q8R9S0TV.png",
418
+ * "imageUrl": "https://files.totalum-project.com/p/acme-crm/01M4P1J2K3L4M5N6P7Q8R9S0TV.png"
419
+ * }
420
+ */
289
421
  generate: (req: AiImageInput) => Promise<{
290
422
  images: {
291
423
  key: string;
@@ -300,7 +432,28 @@ declare function totalumAi(options?: TotalumAiOptions): {
300
432
  fileName?: string | undefined;
301
433
  imageUrl?: string | undefined;
302
434
  }>;
303
- /** An image edited by a prompt. */
435
+ /**
436
+ * Edits images with a prompt — remove a background, change a colour, put a product in a new scene — and stores
437
+ * the result as a public project file.
438
+ *
439
+ * @param req - The instruction and the images to edit.
440
+ * @returns The stored result image(s) and what they cost.
441
+ * @throws AI_MODEL_UNKNOWN (400) No such preset or model id.
442
+ * @throws FILE_NOT_FOUND (404) An input image key does not exist.
443
+ * @throws AI_PROVIDER_UNAVAILABLE (502) The model returned no image; retry.
444
+ * @example
445
+ * const { images } = await totalum.ai.image.edit({
446
+ * prompt: 'Put this sneaker on a white marble pedestal, studio light',
447
+ * images: [product.photo.url],
448
+ * });
449
+ * //=>
450
+ * {
451
+ * "images": [{ "key": "p/acme-crm/01M4P1K3L4M5N6P7Q8R9S0T1UW.png", "url": "https://files.totalum-project.com/p/acme-crm/01M4P1K3L4M5N6P7Q8R9S0T1UW.png", "mediaType": "image/png" }],
452
+ * "usage": { "credits": 0.3012 },
453
+ * "fileName": "01M4P1K3L4M5N6P7Q8R9S0T1UW.png",
454
+ * "imageUrl": "https://files.totalum-project.com/p/acme-crm/01M4P1K3L4M5N6P7Q8R9S0T1UW.png"
455
+ * }
456
+ */
304
457
  edit: (req: AiImageEditInput) => Promise<{
305
458
  images: {
306
459
  key: string;
@@ -317,13 +470,31 @@ declare function totalumAi(options?: TotalumAiOptions): {
317
470
  }>;
318
471
  };
319
472
  video: {
320
- /** `202`: the job and the credits reserved for it; poll `get(jobId)` (the clip is stored when it completes). */
473
+ /**
474
+ * Starts generating a video clip (up to 30 s) from a prompt, optionally from a first/last frame or reference
475
+ * images. It takes minutes: store the `jobId` and read `get(jobId)` later (a page refresh, a cron job); the clip
476
+ * is stored as a project file when it completes.
477
+ *
478
+ * @param req - The prompt, the duration and the look.
479
+ * @returns The job id and the credits reserved for it (settled when it ends).
480
+ * @throws AI_MODEL_UNKNOWN (400) No such preset or model id.
481
+ * @throws AI_VIDEO_FAILED (502) The video could not be started.
482
+ * @throws AI_MEDIA_PAUSED_THIS_HOUR (429) Image, video and speech AI are paused until the hour ends.
483
+ * @example
484
+ * const job = await totalum.ai.video.generate({
485
+ * prompt: 'A paper boat sailing down a rainy street, cinematic',
486
+ * durationSec: 5,
487
+ * aspectRatio: '16:9',
488
+ * });
489
+ * // save job.jobId on the row, then read ai.video.get(jobId) later
490
+ * //=>
491
+ * { "jobId": "vid_8m2k4n6p8q0r", "status": "queued", "estimatedCredits": 21.5 }
492
+ */
321
493
  generate: (req: AiVideoInput) => Promise<{
322
494
  jobId: string;
323
495
  status: "queued";
324
496
  estimatedCredits: number;
325
497
  }>;
326
- /** The video job: `status`, and the stored clip once completed. */
327
498
  get: (jobId: string) => Promise<{
328
499
  jobId: string;
329
500
  status: "queued" | "running" | "completed" | "failed" | "cancelled" | "expired";
@@ -342,8 +513,23 @@ declare function totalumAi(options?: TotalumAiOptions): {
342
513
  }>;
343
514
  /**
344
515
  * ⚠ NODE-ONLY: polls `get(jobId)` until the job leaves `queued`/`running` (default every 5 s, at most 45 min —
345
- * the longest clip, 30 s at 1080p, renders in about 22 min).
346
- * In a Worker it throws `NODE_ONLY` — store the `jobId` and read `get(jobId)` later instead.
516
+ * the longest clip, 30 s at 1080p, renders in about 22 min). For scripts (`npx tsx scripts/…`); in a Worker (the
517
+ * preview and the published app) it throws `NODE_ONLY` — store the `jobId` and read `get(jobId)` later instead.
518
+ *
519
+ * @param jobId - The `jobId` from `video.generate()`.
520
+ * @param opts - How often and how long to poll.
521
+ * @param opts.intervalMs - Milliseconds between polls. Default 5000.
522
+ * @param opts.timeoutMs - Stop polling after this long and return the job as it is. Default 2700000 (45 min).
523
+ * @returns The job once it finished (or when the timeout passed).
524
+ * @throws NODE_ONLY Called inside a Worker; `details.replacement` says what to do instead.
525
+ * @throws AI_VIDEO_JOB_NOT_FOUND (404) No such job in this project.
526
+ * @example
527
+ * // scripts/make-intro-video.ts, run with: npx tsx scripts/make-intro-video.ts
528
+ * const { jobId } = await totalum.ai.video.generate({ prompt: 'Logo reveal on black', durationSec: 5 });
529
+ * const job = await totalum.ai.video.wait(jobId);
530
+ * console.log(job.status, job.video?.url);
531
+ * //=>
532
+ * completed https://files.totalum-project.com/p/acme-crm/01M4P1M5N6P7Q8R9S0T1U2V3WX.mp4
347
533
  */
348
534
  wait(jobId: string, opts?: {
349
535
  intervalMs?: number;
@@ -351,7 +537,23 @@ declare function totalumAi(options?: TotalumAiOptions): {
351
537
  }): Promise<AiVideoJob>;
352
538
  };
353
539
  vision: {
354
- /** A text description of an image (URL, data URL or project file key). */
540
+ /**
541
+ * Describes an image in words, or answers a question about it — alt text, moderation, reading a chart, checking a
542
+ * photo. The image can be a project file key, a files URL, an `https://` URL or a data URL.
543
+ *
544
+ * @param req - The image, the question and the model.
545
+ * @returns The answer's text and what it cost.
546
+ * @throws FILE_NOT_FOUND (404) The image key does not exist.
547
+ * @throws AI_PROVIDER_UNAVAILABLE (502) The model could not read the image (for example the URL refused the
548
+ * download); retry with a project file.
549
+ * @example
550
+ * const { text } = await totalum.ai.vision.describe({
551
+ * image: 'p/acme-crm/01M4P1J2K3L4M5N6P7Q8R9S0TV.png',
552
+ * prompt: 'Write alt text for this image in one sentence.',
553
+ * });
554
+ * //=>
555
+ * { "text": "A watercolor fox sits under a lamp reading an open book.", "usage": { "credits": 0.0019 } }
556
+ */
355
557
  describe: (req: AiVisionDescribeInput) => Promise<{
356
558
  text: string;
357
559
  usage: {
@@ -389,7 +591,35 @@ declare function totalumAi(options?: TotalumAiOptions): {
389
591
  }>;
390
592
  };
391
593
  models: {
392
- /** Each preset's current model and the models a project may call, with their prices. */
594
+ /**
595
+ * Each preset's current model and the catalogue of models this project may call (their ids, names, inputs and
596
+ * context sizes) — to let an admin pick a model, or to pin one. Free.
597
+ *
598
+ * @returns The presets and the model catalogue.
599
+ * @throws AI_PROVIDER_UNAVAILABLE (503) The model catalogue is unavailable; retry.
600
+ * @example
601
+ * const { presets, models } = await totalum.ai.models.list();
602
+ * //=>
603
+ * {
604
+ * "presets": {
605
+ * "fast": "openai/gpt-6-luna",
606
+ * "smart": "openai/gpt-6.1-sol",
607
+ * "reasoning": "anthropic/claude-opus-5.5",
608
+ * "vision": "openai/gpt-6-luna",
609
+ * "image": "microsoft/mai-image-2.6-flash",
610
+ * "image-edit": "microsoft/mai-image-2.6-flash",
611
+ * "video": "alibaba/wan-3.0",
612
+ * "tts": "microsoft/mai-voice-2.1-flash",
613
+ * "stt": "openai/whisper-large-v3-turbo",
614
+ * "embed": "openai/text-embedding-3-small",
615
+ * "embed-image": "google/gemini-embedding-2"
616
+ * },
617
+ * "models": [
618
+ * { "slug": "anthropic/claude-haiku-5.5", "name": "Anthropic: Claude Haiku 5.5", "inputModalities": ["text", "image", "file"], "pricing": {}, "contextLength": 1000000 },
619
+ * …
620
+ * ]
621
+ * }
622
+ */
393
623
  list: () => Promise<{
394
624
  presets: Partial<Record<"fast" | "reasoning" | "video" | "image" | "smart" | "vision" | "image-edit" | "tts" | "stt" | "embed" | "embed-image", string>>;
395
625
  models: {
@@ -402,9 +632,31 @@ declare function totalumAi(options?: TotalumAiOptions): {
402
632
  denylist?: string[] | undefined;
403
633
  }>;
404
634
  };
405
- /** The OpenAI-compatible API for any OpenAI-compatible client: `new OpenAI(ai.gatewayConfig())`. Server-side only. */
635
+ /**
636
+ * The URL and key of Totalum's OpenAI-compatible AI gateway, for any library that takes an OpenAI client: the
637
+ * Vercel AI SDK, `openai`, LangChain. Same models, same key, billed in credits. Server-side only: the key is the
638
+ * project key. No request is made.
639
+ *
640
+ * @returns `{ baseURL, apiKey }` to pass to the client.
641
+ * @throws SDK_NOT_CONFIGURED No project key is set.
642
+ * @example
643
+ * import OpenAI from 'openai';
644
+ *
645
+ * const openai = new OpenAI(totalum.ai.gatewayConfig());
646
+ * const r = await openai.chat.completions.create({ model: 'fast', messages: [{ role: 'user', content: 'Hi' }] });
647
+ * @example
648
+ * import { createOpenAI } from '@ai-sdk/openai';
649
+ * import { generateText } from 'ai';
650
+ *
651
+ * const gateway = createOpenAI(totalum.ai.gatewayConfig());
652
+ * const { text } = await generateText({ model: gateway('smart'), prompt: 'Write a haiku about Mondays' });
653
+ * //=>
654
+ * { "baseURL": "https://ai.totalum.app/api/v1", "apiKey": "tlm_pk_…" }
655
+ */
406
656
  gatewayConfig: () => {
657
+ /** The gateway's OpenAI-compatible base URL: `TOTALUM_AI_BASE_URL`, else `https://ai.totalum.app/api/v1`. */
407
658
  baseURL: string;
659
+ /** The project key, used as the API key. */
408
660
  apiKey: string;
409
661
  };
410
662
  };