@lumibase/sdk 1.0.0-rc.4 → 1.0.1

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/dist/index.cjs CHANGED
@@ -22,6 +22,7 @@ var index_exports = {};
22
22
  __export(index_exports, {
23
23
  ACCESS_EXPORT_SCHEMA: () => ACCESS_EXPORT_SCHEMA,
24
24
  AudienceClient: () => AudienceClient,
25
+ DECISION_ERROR_CODES: () => DECISION_ERROR_CODES,
25
26
  DEFAULT_IMPORT_SOURCE: () => DEFAULT_IMPORT_SOURCE,
26
27
  LumiError: () => LumiError,
27
28
  RealtimeClient: () => RealtimeClient,
@@ -33,7 +34,9 @@ __export(index_exports, {
33
34
  createCdcPipeline: () => createCdcPipeline,
34
35
  createCdcSubscription: () => createCdcSubscription,
35
36
  createLumiClient: () => createLumiClient,
37
+ decide: () => decide,
36
38
  decideAgentApproval: () => decideAgentApproval,
39
+ decisionErrorCode: () => decisionErrorCode,
37
40
  deleteBookmark: () => deleteBookmark,
38
41
  deleteCdcPipeline: () => deleteCdcPipeline,
39
42
  deleteCdcSubscription: () => deleteCdcSubscription,
@@ -46,6 +49,8 @@ __export(index_exports, {
46
49
  generateAgentApp: () => generateAgentApp,
47
50
  generateTypes: () => generateTypes,
48
51
  getEffectivePreset: () => getEffectivePreset,
52
+ getReview: () => getReview,
53
+ getReviewProfile: () => getReviewProfile,
49
54
  graphql: () => graphql,
50
55
  importAccessManifest: () => importAccessManifest,
51
56
  jsonLdScript: () => jsonLdScript,
@@ -59,6 +64,8 @@ __export(index_exports, {
59
64
  listCdcPipelines: () => listCdcPipelines,
60
65
  listCdcSubscriptionDeliveries: () => listCdcSubscriptionDeliveries,
61
66
  listCdcSubscriptions: () => listCdcSubscriptions,
67
+ listReviewProfiles: () => listReviewProfiles,
68
+ listReviews: () => listReviews,
62
69
  mediaUrl: () => mediaUrl,
63
70
  publishAgentArtifact: () => publishAgentArtifact,
64
71
  readAgentMemoryContext: () => readAgentMemoryContext,
@@ -71,13 +78,17 @@ __export(index_exports, {
71
78
  readItems: () => readItems,
72
79
  replayCdcSubscription: () => replayCdcSubscription,
73
80
  retryAgentRun: () => retryAgentRun,
81
+ reviewContentHash: () => reviewContentHash,
82
+ reviewDraft: () => reviewDraft,
74
83
  rollbackAgentArtifact: () => rollbackAgentArtifact,
75
84
  rollbackCdcDeployment: () => rollbackCdcDeployment,
76
85
  saveUserView: () => saveUserView,
77
86
  search: () => search,
78
87
  startCdcPipeline: () => startCdcPipeline,
79
88
  stopCdcPipeline: () => stopCdcPipeline,
89
+ submitReviewFeedback: () => submitReviewFeedback,
80
90
  toNextMetadata: () => toNextMetadata,
91
+ toWebSocketBase: () => toWebSocketBase,
81
92
  updateBookmark: () => updateBookmark,
82
93
  updateCdcPipeline: () => updateCdcPipeline,
83
94
  updateCdcSubscription: () => updateCdcSubscription,
@@ -88,15 +99,29 @@ module.exports = __toCommonJS(index_exports);
88
99
 
89
100
  // src/client.ts
90
101
  var LumiError = class extends Error {
91
- constructor(status, body) {
102
+ constructor(status, body, headers) {
92
103
  super(body?.errors?.[0]?.message ?? `LumiBase ${status}`);
93
104
  this.status = status;
94
105
  this.body = body;
95
106
  this.name = "LumiError";
107
+ this.retryAfter = parseRetryAfter(headers?.get("retry-after") ?? null);
96
108
  }
97
109
  status;
98
110
  body;
111
+ /**
112
+ * Seconds the server asked the caller to wait (`Retry-After`), or `null`
113
+ * when the response carried none — e.g. a 429 site budget or rate limit.
114
+ */
115
+ retryAfter;
99
116
  };
117
+ function parseRetryAfter(value) {
118
+ if (value === null) return null;
119
+ const trimmed = value.trim();
120
+ if (/^\d+$/.test(trimmed)) return Number(trimmed);
121
+ const at = Date.parse(trimmed);
122
+ if (Number.isNaN(at)) return null;
123
+ return Math.max(0, Math.ceil((at - Date.now()) / 1e3));
124
+ }
100
125
  function parseResponseBody(text) {
101
126
  if (!text) return null;
102
127
  try {
@@ -187,7 +212,7 @@ function createLumiClient(opts) {
187
212
  } catch {
188
213
  }
189
214
  }
190
- throw new LumiError(res.status, toErrorBody(res.status, body));
215
+ throw new LumiError(res.status, toErrorBody(res.status, body), res.headers);
191
216
  }
192
217
  return body;
193
218
  }
@@ -213,6 +238,24 @@ function createLumiClient(opts) {
213
238
  // src/types.ts
214
239
  var ACCESS_EXPORT_SCHEMA = "lumibase.access@v1";
215
240
 
241
+ // src/realtime/ws-url.ts
242
+ function toWebSocketBase(baseUrl) {
243
+ const trimmed = trimTrailingSlashes(baseUrl);
244
+ let absolute = trimmed;
245
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) {
246
+ const origin = globalThis.location?.origin;
247
+ if (origin && origin !== "null") {
248
+ absolute = trimTrailingSlashes(new URL(trimmed || "/", origin).toString());
249
+ }
250
+ }
251
+ return absolute.replace(/^http/i, "ws");
252
+ }
253
+ function trimTrailingSlashes(value) {
254
+ let end = value.length;
255
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
256
+ return end === value.length ? value : value.slice(0, end);
257
+ }
258
+
216
259
  // src/realtime/audience.ts
217
260
  var WS_OPEN = 1;
218
261
  var AudienceClient = class {
@@ -302,8 +345,7 @@ var AudienceClient = class {
302
345
  return;
303
346
  }
304
347
  if (this.stopped) return;
305
- const wsBase = this.opts.baseUrl.replace(/^http/, "ws");
306
- const url = `${wsBase}/api/v1/realtime?ticket=${encodeURIComponent(ticket)}`;
348
+ const url = `${toWebSocketBase(this.opts.baseUrl)}/api/v1/realtime?ticket=${encodeURIComponent(ticket)}`;
307
349
  const factory = this.opts.webSocketFactory ?? ((u) => new WebSocket(u));
308
350
  let ws;
309
351
  try {
@@ -486,8 +528,14 @@ var RealtimeClient = class {
486
528
  return;
487
529
  }
488
530
  if (this.stopped) return;
489
- const wsBase = baseUrl.replace(/^http/, "ws");
490
- const url = new URL(`${wsBase}/api/v1/realtime`);
531
+ let url;
532
+ try {
533
+ url = new URL(`${toWebSocketBase(baseUrl)}/api/v1/realtime`);
534
+ } catch (err) {
535
+ console.warn("[RealtimeClient] Cannot build the realtime URL from baseUrl", baseUrl, err);
536
+ this.stopped = true;
537
+ return;
538
+ }
491
539
  url.searchParams.set("ticket", ticket);
492
540
  url.searchParams.set("site", siteId);
493
541
  url.searchParams.set("siteId", siteId);
@@ -1298,6 +1346,139 @@ function mediaUrl(key, transform, opts) {
1298
1346
  };
1299
1347
  }
1300
1348
 
1349
+ // src/rest/decisions.ts
1350
+ var DECISION_ERROR_CODES = [
1351
+ "VALIDATION",
1352
+ "FORBIDDEN",
1353
+ // Governance (#511): checked before the provider is called.
1354
+ "DECISION_DISABLED",
1355
+ "DECISION_FIELD_NOT_ALLOWED",
1356
+ "DECISION_QUOTA_EXCEEDED",
1357
+ "DECISION_CONCURRENCY_LIMITED",
1358
+ "DECISION_QUOTA_UNAVAILABLE",
1359
+ // Provider and limits (#504, #509).
1360
+ "DECISION_NOT_CONFIGURED",
1361
+ "DECISION_AUTH",
1362
+ "DECISION_VALIDATION",
1363
+ "DECISION_RATE_LIMITED",
1364
+ "DECISION_UNAVAILABLE",
1365
+ "DECISION_UPSTREAM",
1366
+ "DECISION_PARSE_FAILED",
1367
+ "DECISION_TIMEOUT",
1368
+ "DECISION_CANCELLED",
1369
+ "DECISION_INPUT_TOO_LARGE",
1370
+ // Draft review (#512).
1371
+ "REVIEW_PROFILE_NOT_FOUND",
1372
+ "REVIEW_PROFILE_EXISTS",
1373
+ "REVIEW_PROFILE_CONFLICT",
1374
+ "REVIEW_ITEM_NOT_FOUND",
1375
+ "REVIEW_RUN_NOT_FOUND",
1376
+ "REVIEW_FIELD_NOT_ALLOWED",
1377
+ "REVIEW_COLLECTION_MISMATCH",
1378
+ "REVIEW_NOT_COMPLETE",
1379
+ "REVIEW_STALE",
1380
+ // Draft-review pilot sessions (#516).
1381
+ "REVIEW_SESSION_MODE_MISMATCH",
1382
+ "REVIEW_SESSION_RUN_INVALID",
1383
+ "INTERNAL"
1384
+ ];
1385
+ var KNOWN_CODES = new Set(DECISION_ERROR_CODES);
1386
+ function decisionErrorCode(err) {
1387
+ if (!(err instanceof LumiError)) return null;
1388
+ const code = err.body?.errors?.[0]?.code;
1389
+ return typeof code === "string" && KNOWN_CODES.has(code) ? code : null;
1390
+ }
1391
+ function decide(request, options = {}) {
1392
+ return async (client) => {
1393
+ const res = await client.rawRequest("/api/v1/ai/decisions", {
1394
+ method: "POST",
1395
+ body: JSON.stringify(request),
1396
+ signal: options.signal
1397
+ });
1398
+ return res.data;
1399
+ };
1400
+ }
1401
+
1402
+ // src/rest/reviews.ts
1403
+ function canonicalize(value) {
1404
+ if (Array.isArray(value)) return value.map(canonicalize);
1405
+ if (value && typeof value === "object") {
1406
+ const out = {};
1407
+ for (const key of Object.keys(value).sort()) out[key] = canonicalize(value[key]);
1408
+ return out;
1409
+ }
1410
+ return value;
1411
+ }
1412
+ async function reviewContentHash(values) {
1413
+ const canonical = JSON.stringify(canonicalize(JSON.parse(JSON.stringify(values ?? null))));
1414
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical)));
1415
+ return `sha256:${Array.from(digest, (b) => b.toString(16).padStart(2, "0")).join("")}`;
1416
+ }
1417
+ var BASE = "/api/v1/ai";
1418
+ function withQuery2(path, params) {
1419
+ const qs = new URLSearchParams();
1420
+ for (const [key, value] of Object.entries(params)) if (value !== void 0) qs.set(key, value);
1421
+ const s = qs.toString();
1422
+ return s ? `${path}?${s}` : path;
1423
+ }
1424
+ function listReviewProfiles(params = {}, options = {}) {
1425
+ return async (client) => {
1426
+ const res = await client.rawRequest(
1427
+ withQuery2(`${BASE}/review-profiles`, { collection: params.collection }),
1428
+ { signal: options.signal }
1429
+ );
1430
+ return res.data;
1431
+ };
1432
+ }
1433
+ function getReviewProfile(key, params = {}, options = {}) {
1434
+ return async (client) => {
1435
+ const res = await client.rawRequest(
1436
+ withQuery2(`${BASE}/review-profiles/${encodeURIComponent(key)}`, {
1437
+ version: params.version === void 0 ? void 0 : String(params.version)
1438
+ }),
1439
+ { signal: options.signal }
1440
+ );
1441
+ return res.data;
1442
+ };
1443
+ }
1444
+ function reviewDraft(request, options = {}) {
1445
+ return async (client) => {
1446
+ const res = await client.rawRequest(`${BASE}/reviews`, {
1447
+ method: "POST",
1448
+ body: JSON.stringify(request),
1449
+ signal: options.signal
1450
+ });
1451
+ return res.data;
1452
+ };
1453
+ }
1454
+ function getReview(id, options = {}) {
1455
+ return async (client) => {
1456
+ const res = await client.rawRequest(`${BASE}/reviews/${encodeURIComponent(id)}`, {
1457
+ signal: options.signal
1458
+ });
1459
+ return res.data;
1460
+ };
1461
+ }
1462
+ function listReviews(params, options = {}) {
1463
+ return async (client) => {
1464
+ const res = await client.rawRequest(
1465
+ withQuery2(`${BASE}/reviews`, { collection: params.collection, itemId: params.itemId }),
1466
+ { signal: options.signal }
1467
+ );
1468
+ return res.data;
1469
+ };
1470
+ }
1471
+ function submitReviewFeedback(runId, request, options = {}) {
1472
+ return async (client) => {
1473
+ const res = await client.rawRequest(`${BASE}/reviews/${encodeURIComponent(runId)}/feedback`, {
1474
+ method: "POST",
1475
+ body: JSON.stringify(request),
1476
+ signal: options.signal
1477
+ });
1478
+ return res.data;
1479
+ };
1480
+ }
1481
+
1301
1482
  // src/rest/index.ts
1302
1483
  function search(query, params) {
1303
1484
  return async (client) => {
@@ -1865,6 +2046,7 @@ function jsonLdScript(item) {
1865
2046
  0 && (module.exports = {
1866
2047
  ACCESS_EXPORT_SCHEMA,
1867
2048
  AudienceClient,
2049
+ DECISION_ERROR_CODES,
1868
2050
  DEFAULT_IMPORT_SOURCE,
1869
2051
  LumiError,
1870
2052
  RealtimeClient,
@@ -1876,7 +2058,9 @@ function jsonLdScript(item) {
1876
2058
  createCdcPipeline,
1877
2059
  createCdcSubscription,
1878
2060
  createLumiClient,
2061
+ decide,
1879
2062
  decideAgentApproval,
2063
+ decisionErrorCode,
1880
2064
  deleteBookmark,
1881
2065
  deleteCdcPipeline,
1882
2066
  deleteCdcSubscription,
@@ -1889,6 +2073,8 @@ function jsonLdScript(item) {
1889
2073
  generateAgentApp,
1890
2074
  generateTypes,
1891
2075
  getEffectivePreset,
2076
+ getReview,
2077
+ getReviewProfile,
1892
2078
  graphql,
1893
2079
  importAccessManifest,
1894
2080
  jsonLdScript,
@@ -1902,6 +2088,8 @@ function jsonLdScript(item) {
1902
2088
  listCdcPipelines,
1903
2089
  listCdcSubscriptionDeliveries,
1904
2090
  listCdcSubscriptions,
2091
+ listReviewProfiles,
2092
+ listReviews,
1905
2093
  mediaUrl,
1906
2094
  publishAgentArtifact,
1907
2095
  readAgentMemoryContext,
@@ -1914,13 +2102,17 @@ function jsonLdScript(item) {
1914
2102
  readItems,
1915
2103
  replayCdcSubscription,
1916
2104
  retryAgentRun,
2105
+ reviewContentHash,
2106
+ reviewDraft,
1917
2107
  rollbackAgentArtifact,
1918
2108
  rollbackCdcDeployment,
1919
2109
  saveUserView,
1920
2110
  search,
1921
2111
  startCdcPipeline,
1922
2112
  stopCdcPipeline,
2113
+ submitReviewFeedback,
1923
2114
  toNextMetadata,
2115
+ toWebSocketBase,
1924
2116
  updateBookmark,
1925
2117
  updateCdcPipeline,
1926
2118
  updateCdcSubscription,
package/dist/index.d.cts CHANGED
@@ -1570,7 +1570,12 @@ interface LumiErrorBody {
1570
1570
  declare class LumiError extends Error {
1571
1571
  status: number;
1572
1572
  body: LumiErrorBody | any;
1573
- constructor(status: number, body: LumiErrorBody | any);
1573
+ /**
1574
+ * Seconds the server asked the caller to wait (`Retry-After`), or `null`
1575
+ * when the response carried none — e.g. a 429 site budget or rate limit.
1576
+ */
1577
+ readonly retryAfter: number | null;
1578
+ constructor(status: number, body: LumiErrorBody | any, headers?: Headers);
1574
1579
  }
1575
1580
  interface LumiClient<TSchema extends DefaultSchema = DefaultSchema> {
1576
1581
  url: string;
@@ -1667,6 +1672,19 @@ declare class AudienceClient {
1667
1672
  private sendRaw;
1668
1673
  }
1669
1674
 
1675
+ /**
1676
+ * Turn the client's HTTP `baseUrl` into the WebSocket origin for
1677
+ * `/api/v1/realtime`.
1678
+ *
1679
+ * `baseUrl` may legitimately be `''` or a path such as `/cms`: a browser app
1680
+ * served from the same origin as the CMS (Studio inside the Docker image)
1681
+ * talks to the API with relative URLs. `new URL('/api/v1/realtime')` throws
1682
+ * for those, so relative bases are resolved against `location` when one
1683
+ * exists. Outside a browser there is nothing to resolve against, and the
1684
+ * original error surfaces to the caller.
1685
+ */
1686
+ declare function toWebSocketBase(baseUrl: string): string;
1687
+
1670
1688
  /**
1671
1689
  * RealtimeClient — typed WebSocket client for the LumiBase realtime API.
1672
1690
  *
@@ -2277,6 +2295,292 @@ declare function mediaUrl(key: string, transform?: MediaTransform | {
2277
2295
  sign?: string;
2278
2296
  }): (client: LumiClient) => string;
2279
2297
 
2298
+ /**
2299
+ * SDK command for the decision model endpoint (`POST /api/v1/ai/decisions`):
2300
+ * typed `noul` / `choice` / `score` questions answered with probabilities by
2301
+ * TypeSafe Jev or the configured equivalent. Command factory
2302
+ * `(client) => Promise<T>`, matching the rest of the REST module.
2303
+ *
2304
+ * Provider keys never reach the SDK: the CMS holds them and the client only
2305
+ * sends its usual bearer + `X-Lumi-Site` headers.
2306
+ */
2307
+
2308
+ /** Free-form payload: plain text or structured data. */
2309
+ type DecisionPayload = string | Record<string, unknown> | unknown[];
2310
+ interface NoulQuestion {
2311
+ type: "noul";
2312
+ instructions: DecisionPayload;
2313
+ criteria: {
2314
+ true: DecisionPayload;
2315
+ false: DecisionPayload;
2316
+ };
2317
+ }
2318
+ interface ChoiceQuestion {
2319
+ type: "choice";
2320
+ instructions: DecisionPayload;
2321
+ /** Option key → description, or `null` when the key is self-explanatory. 2–255 options. */
2322
+ criteria: Record<string, DecisionPayload | null>;
2323
+ }
2324
+ interface ScoreQuestion {
2325
+ type: "score";
2326
+ instructions: DecisionPayload;
2327
+ /** Ordered rubric levels, lowest first. 2–10 levels. */
2328
+ criteria: DecisionPayload[];
2329
+ }
2330
+ type DecisionQuestion = NoulQuestion | ChoiceQuestion | ScoreQuestion;
2331
+ interface DecisionRequest {
2332
+ state: DecisionPayload;
2333
+ /** 1–32 questions keyed by `[A-Za-z0-9_-]{1,64}`. */
2334
+ questions: Record<string, DecisionQuestion>;
2335
+ }
2336
+ interface NoulAnswer {
2337
+ type: "noul";
2338
+ /** P(the `true` criterion holds), 0..1. */
2339
+ noul: number;
2340
+ }
2341
+ interface ChoiceAnswer {
2342
+ type: "choice";
2343
+ choice: string;
2344
+ probabilities: Record<string, number>;
2345
+ confidence: number;
2346
+ }
2347
+ interface ScoreAnswer {
2348
+ type: "score";
2349
+ score: number;
2350
+ legend: Record<string, unknown>;
2351
+ probabilities: Record<string, number>;
2352
+ confidence: number;
2353
+ }
2354
+ type DecisionAnswer = NoulAnswer | ChoiceAnswer | ScoreAnswer;
2355
+ interface DecisionResult {
2356
+ /** `typesafe`, `openrouter` or `llm`. */
2357
+ provider: string;
2358
+ model: string;
2359
+ /**
2360
+ * `false` when `DECISION_PROVIDER=llm`: probabilities are self-reported by
2361
+ * the LLM. `true` is the provider's claim, not a calibration on your data.
2362
+ */
2363
+ calibrated: boolean;
2364
+ answers: Record<string, DecisionAnswer>;
2365
+ /** `null` when the provider did not report the count (unknown, not zero). */
2366
+ usage: {
2367
+ inputTokens: number | null;
2368
+ outputTokens: number | null;
2369
+ };
2370
+ }
2371
+ /**
2372
+ * Every `errors[0].code` the decision and draft review endpoints return
2373
+ * (`POST /ai/decisions`, `/ai/review-profiles*`, `/ai/reviews*`), carried on
2374
+ * `LumiError.body`. Read it with {@link decisionErrorCode}.
2375
+ */
2376
+ declare const DECISION_ERROR_CODES: readonly ["VALIDATION", "FORBIDDEN", "DECISION_DISABLED", "DECISION_FIELD_NOT_ALLOWED", "DECISION_QUOTA_EXCEEDED", "DECISION_CONCURRENCY_LIMITED", "DECISION_QUOTA_UNAVAILABLE", "DECISION_NOT_CONFIGURED", "DECISION_AUTH", "DECISION_VALIDATION", "DECISION_RATE_LIMITED", "DECISION_UNAVAILABLE", "DECISION_UPSTREAM", "DECISION_PARSE_FAILED", "DECISION_TIMEOUT", "DECISION_CANCELLED", "DECISION_INPUT_TOO_LARGE", "REVIEW_PROFILE_NOT_FOUND", "REVIEW_PROFILE_EXISTS", "REVIEW_PROFILE_CONFLICT", "REVIEW_ITEM_NOT_FOUND", "REVIEW_RUN_NOT_FOUND", "REVIEW_FIELD_NOT_ALLOWED", "REVIEW_COLLECTION_MISMATCH", "REVIEW_NOT_COMPLETE", "REVIEW_STALE", "REVIEW_SESSION_MODE_MISMATCH", "REVIEW_SESSION_RUN_INVALID", "INTERNAL"];
2377
+ type DecisionErrorCode = (typeof DECISION_ERROR_CODES)[number];
2378
+ /**
2379
+ * The typed `errors[0].code` of a rejected decision or review call, or `null`
2380
+ * when `err` is not a `LumiError` with a known code (network failure, abort,
2381
+ * or a code this SDK version does not know — read `err.body` for those).
2382
+ */
2383
+ declare function decisionErrorCode(err: unknown): DecisionErrorCode | null;
2384
+ interface DecideOptions {
2385
+ /**
2386
+ * Aborts the HTTP request; the promise rejects with the fetch `AbortError`.
2387
+ * The CMS sees the disconnect, aborts its upstream call and does not retry.
2388
+ */
2389
+ signal?: AbortSignal;
2390
+ }
2391
+ /**
2392
+ * Ask the decision model typed questions about `state`. Read-only on the
2393
+ * server. Rejects with `LumiError` on non-2xx — e.g. 503 with
2394
+ * `DECISION_NOT_CONFIGURED` when the CMS has no `DECISION_PROVIDER`.
2395
+ *
2396
+ * Call it from a server with a secret API key or from Studio: a publishable
2397
+ * API key (`lbk_pub_…`) or a frontend session gets 403 `FORBIDDEN`, even when
2398
+ * its role grants `ai:decide`.
2399
+ *
2400
+ * The caller needs the `ai:decide` capability (403 `FORBIDDEN`), the site
2401
+ * must have opted in (403 `DECISION_DISABLED`), and each site has hourly,
2402
+ * concurrency and daily budgets (429 `DECISION_QUOTA_EXCEEDED` /
2403
+ * `DECISION_CONCURRENCY_LIMITED`, with `Retry-After`).
2404
+ */
2405
+ declare function decide(request: DecisionRequest, options?: DecideOptions): (client: LumiClient) => Promise<DecisionResult>;
2406
+
2407
+ /**
2408
+ * SDK commands for draft review (#512): read the site's versioned review
2409
+ * profiles, review a saved item or an unsaved draft, read a run with its
2410
+ * staleness, and record editor feedback. Command factories
2411
+ * `(client) => Promise<T>`, like {@link decide}.
2412
+ *
2413
+ * A review only suggests. None of these calls writes to an item; applying a
2414
+ * suggestion is the caller's own item update, under its own permissions.
2415
+ *
2416
+ * The SDK has no runtime dependencies, so these types mirror the CMS
2417
+ * contracts (`@lumibase/contracts` `decision-review.ts`). A type-equality test
2418
+ * (`__tests__/reviews.contract.test.ts`) fails the SDK typecheck when the two
2419
+ * drift. Provider keys stay on the CMS; the client only sends its usual
2420
+ * bearer and `X-Lumi-Site` headers.
2421
+ */
2422
+
2423
+ type ReviewPreset = "taxonomy" | "brand-voice" | "brief-alignment";
2424
+ type ReviewRunStatus = "running" | "success" | "abstained" | "error";
2425
+ type ReviewVerdict = "accept" | "edit" | "reject";
2426
+ /** `content_changed` / `revision_changed`: the item moved on; `item_unavailable`: it is gone or unreadable. */
2427
+ type ReviewStaleReason = "content_changed" | "revision_changed" | "item_unavailable";
2428
+ /** A versioned review profile. Rows are immutable; a new version archives the previous one. */
2429
+ interface ReviewProfile {
2430
+ id: string;
2431
+ key: string;
2432
+ version: number;
2433
+ status: "active" | "archived";
2434
+ /** Collection the profile applies to; `null` = any collection. */
2435
+ collection: string | null;
2436
+ preset: ReviewPreset | null;
2437
+ /** Top-level item fields the review reads. */
2438
+ fields: string[];
2439
+ questions: Record<string, DecisionQuestion>;
2440
+ sourceField: string | null;
2441
+ minConfidence: number | null;
2442
+ /** Caveat, e.g. "no source — not a fact-check". */
2443
+ note: string | null;
2444
+ createdBy: string | null;
2445
+ createdAt: string;
2446
+ }
2447
+ /** `POST /ai/reviews`. Give exactly one of `itemId` (saved item) or `snapshot` (unsaved draft). */
2448
+ interface ReviewRunRequest {
2449
+ /** Profile key. */
2450
+ profile: string;
2451
+ /** Defaults to the active version. */
2452
+ profileVersion?: number;
2453
+ collection: string;
2454
+ itemId?: string;
2455
+ /** Unsaved field values. Every key must be a profile field the caller may read and write. */
2456
+ snapshot?: Record<string, unknown>;
2457
+ /**
2458
+ * 8–128 chars. Same key from the same principal → the stored run, no second
2459
+ * provider call, whatever the content now is. The key must therefore change
2460
+ * when the content or profile version does: build it from
2461
+ * {@link reviewContentHash} and the profile version, never from a fixed id.
2462
+ */
2463
+ idempotencyKey?: string;
2464
+ }
2465
+ interface ReviewRun {
2466
+ /** uuidv7. */
2467
+ id: string;
2468
+ profileId: string;
2469
+ profileKey: string;
2470
+ profileVersion: number;
2471
+ collection: string;
2472
+ itemId: string | null;
2473
+ revisionId: string | null;
2474
+ /** `sha256:<hex>` of the canonical JSON of the reviewed fields. */
2475
+ contentHash: string;
2476
+ source: "item" | "snapshot";
2477
+ /** Profile fields the caller could not read; they were not sent. */
2478
+ omittedFields: string[];
2479
+ /** `abstained`: every choice was `other`/`unknown`, or a confidence fell below the profile minimum. */
2480
+ status: ReviewRunStatus;
2481
+ provider: string | null;
2482
+ model: string | null;
2483
+ /** `null` until the run completes; `false` when the CMS answers with `DECISION_PROVIDER=llm`. */
2484
+ calibrated: boolean | null;
2485
+ /** Keyed by question; `null` until the run completes or when it failed. */
2486
+ answers: Record<string, DecisionAnswer> | null;
2487
+ /** `null` until the run completes; a `null` count is unknown, not zero. */
2488
+ usage: {
2489
+ inputTokens: number | null;
2490
+ outputTokens: number | null;
2491
+ } | null;
2492
+ latencyMs: number | null;
2493
+ /** The decision error code when `status` is `error`. */
2494
+ errorCode: string | null;
2495
+ createdAt: string;
2496
+ completedAt: string | null;
2497
+ /** Item runs: the item changed since the run. Snapshot runs report `false` (checked on feedback). */
2498
+ stale: boolean;
2499
+ staleReason: ReviewStaleReason | null;
2500
+ note: string | null;
2501
+ }
2502
+ interface ReviewFeedbackEntry {
2503
+ questionKey: string;
2504
+ verdict: ReviewVerdict;
2505
+ /** Required for `edit`: the value the editor chose instead. */
2506
+ editedValue?: unknown;
2507
+ }
2508
+ /** `POST /ai/reviews/:id/feedback`. One entry per question. */
2509
+ interface ReviewFeedbackRequest {
2510
+ entries: ReviewFeedbackEntry[];
2511
+ /** Accept/edit on a stale run is refused (409 `REVIEW_STALE`) unless this is `true`. */
2512
+ acknowledgeStale?: boolean;
2513
+ /**
2514
+ * Snapshot runs: {@link reviewContentHash} of the draft the editor sees now.
2515
+ * A value other than `run.contentHash` makes accept/edit fail with 409
2516
+ * `REVIEW_STALE`. Without it (or with `run.contentHash` itself) a changed
2517
+ * draft is not detected, because the CMS cannot re-read an unsaved draft.
2518
+ */
2519
+ contentHash?: string;
2520
+ }
2521
+ /** Stored feedback. The first verdict per run, question and principal is final. */
2522
+ interface ReviewFeedback {
2523
+ id: string;
2524
+ runId: string;
2525
+ questionKey: string;
2526
+ verdict: ReviewVerdict;
2527
+ editedValue: unknown;
2528
+ principalType: string;
2529
+ principalId: string;
2530
+ createdAt: string;
2531
+ }
2532
+ interface ReviewRequestOptions {
2533
+ /** Aborts the HTTP request; the promise rejects with the fetch `AbortError`. */
2534
+ signal?: AbortSignal;
2535
+ }
2536
+ /**
2537
+ * `sha256:<64 hex>` of the canonical JSON (sorted keys, dates serialised,
2538
+ * `undefined` dropped) of `values`, computed exactly as the CMS computes
2539
+ * `ReviewRun.contentHash`. Uses WebCrypto (`crypto.subtle`), so it runs in
2540
+ * browsers, Node 18+ and Workers.
2541
+ *
2542
+ * Use it on the draft the editor sees now:
2543
+ * - pass it as `contentHash` to {@link submitReviewFeedback} on a snapshot run,
2544
+ * so the CMS answers 409 `REVIEW_STALE` when the draft changed after the
2545
+ * review. Sending the run's own `contentHash` back disables that check;
2546
+ * - build the `idempotencyKey` of {@link reviewDraft} from it, so a changed
2547
+ * draft gets a new run instead of a replay of the old one.
2548
+ *
2549
+ * For a snapshot run, hash the same fields you sent as `snapshot`.
2550
+ */
2551
+ declare function reviewContentHash(values: Record<string, unknown>): Promise<string>;
2552
+ /** Active profiles of the site; with `collection`, those bound to it or to any collection. Needs `ai:decide`. */
2553
+ declare function listReviewProfiles(params?: {
2554
+ collection?: string;
2555
+ }, options?: ReviewRequestOptions): (client: LumiClient) => Promise<ReviewProfile[]>;
2556
+ /** One profile: the active version, or `version`. 404 `REVIEW_PROFILE_NOT_FOUND`. */
2557
+ declare function getReviewProfile(key: string, params?: {
2558
+ version?: number;
2559
+ }, options?: ReviewRequestOptions): (client: LumiClient) => Promise<ReviewProfile>;
2560
+ /**
2561
+ * Review a saved item (`itemId`) or an unsaved draft (`snapshot`) with a
2562
+ * profile. Runs the governed decision path: rejects with `LumiError` carrying
2563
+ * the same codes as {@link decide} (403 `DECISION_DISABLED`, 429 with
2564
+ * `retryAfter`, 504 `DECISION_TIMEOUT`, …) plus 422 `REVIEW_FIELD_NOT_ALLOWED`
2565
+ * for a snapshot field outside the profile or the caller's permissions.
2566
+ * Resolves with the run — a replay of the same `idempotencyKey` returns the
2567
+ * stored run without a second provider call.
2568
+ */
2569
+ declare function reviewDraft(request: ReviewRunRequest, options?: ReviewRequestOptions): (client: LumiClient) => Promise<ReviewRun>;
2570
+ /** A run with its current staleness. 404 `REVIEW_RUN_NOT_FOUND` also when the caller cannot read what it reviewed. */
2571
+ declare function getReview(id: string, options?: ReviewRequestOptions): (client: LumiClient) => Promise<ReviewRun>;
2572
+ /** Runs of one item the caller may see, newest first (50 at most). */
2573
+ declare function listReviews(params: {
2574
+ collection: string;
2575
+ itemId: string;
2576
+ }, options?: ReviewRequestOptions): (client: LumiClient) => Promise<ReviewRun[]>;
2577
+ /**
2578
+ * Record accept / edit / reject on a run's answers. A retry returns the
2579
+ * stored rows and adds none. `accept`/`edit` on a stale run rejects with 409
2580
+ * `REVIEW_STALE` unless `acknowledgeStale: true`. Never changes the item.
2581
+ */
2582
+ declare function submitReviewFeedback(runId: string, request: ReviewFeedbackRequest, options?: ReviewRequestOptions): (client: LumiClient) => Promise<ReviewFeedback[]>;
2583
+
2280
2584
  /**
2281
2585
  * Full-text search via `GET /api/v1/search`. Omit `params.collection` for a
2282
2586
  * cross-collection (global) search that fans out over every collection of the
@@ -2446,4 +2750,5 @@ declare function toNextMetadata(item: unknown): Record<string, unknown>;
2446
2750
  */
2447
2751
  declare function jsonLdScript(item: unknown): string | undefined;
2448
2752
 
2449
- export { ACCESS_EXPORT_SCHEMA, type AIApproval, type AIApprovalStatus, type AIChatResponse, type AIChatStatus, type AIContentAssistResult, type AIConversation, type AIFieldSuggestion, type AIMessage, type AccessConflict, type AccessConflictCheckInput, type AccessConflictReport, type AccessExportApiKey, type AccessExportBindings, type AccessExportManifest, type AccessExportPermission, type AccessExportPolicy, type AccessExportRole, type AccessImportApplyResult, type AccessImportDiff, type AccessImportDiffEntry, type AccessImportDiffSection, type AccessImportDryRunResult, type AccessImportIssue, type AccessImportMode, type AccessImportOptions, type AccessImportSummary, type ActivityResource, type AgentApprovalResource, type AgentArtifactCreateInput, type AgentArtifactResource, type AgentArtifactType, type AgentEvaluationResource, type AgentGenerateAppInput, type AgentGenerateAppResult, type AgentGoalCreateInput, type AgentGoalResource, type AgentMemoryContext, type AgentMemoryResource, type AgentMemoryWriteInput, type AgentRiskLevel, type AgentRunResource, type AgentToolResource, type ApiKeyCreateInput, type ApiKeyPolicyAttachment, type ApiKeyResource, type ApiKeyRoleAttachment, type ApiKeyRotateInput, type ApiKeySecretResult, AudienceClient, type AudienceClientOptions, type AudienceEvent, type AudienceNotification, type Brand, type CdcActorType, type CdcConnectorType, type CdcDeliveryResource, type CdcDeployInput, type CdcDeploymentResult, type CdcDeploymentStatus, type CdcDeploymentStep, type CdcDeploymentTarget, type CdcEnvValidationResult, type CdcEventEnvelope, type CdcFeedPage, type CdcFeedReadParams, type CdcHealthCheckResult, type CdcHealthMetricEntry, type CdcOperation, type CdcPayloadMode, type CdcPipelineCreateInput, type CdcPipelineMetrics, type CdcPipelinePatchInput, type CdcPipelineResource, type CdcPipelineStatus, type CdcReplayInput, type CdcRollbackResult, type CdcSource, type CdcSubscriptionCreateInput, type CdcSubscriptionKind, type CdcSubscriptionPatchInput, type CdcSubscriptionResource, type CdcSubscriptionStatus, type CdcValidateEnvInput, type ChannelEventCallback, type CollectionInput, type CollectionResource, type CompiledPermission, type ConnectionStatus, type ContentVersion, type CreateSCIMTokenParams, DEFAULT_IMPORT_SOURCE, type DefaultSchema, type DeliverySeo, type DeploymentResource, type DeploymentTargetResource, type DomainCreateInput, type DomainResource, type DomainVerificationRecord, type ExtensionResource, type FieldDeleteOptions, type FieldInput, type FieldMutationOptions, type FieldRenameInput, type FieldResource, type FileResource, type FlowGraph, type FlowNode, type FlowResource, type FlowRun, type FlowRunResult, type FlowRunStatus, type FlowStatus, type FlowTriggerType, type FolderResource, type GenerateOptions, type GrantAction, type GraphQLExtension, type ID, type ItemFilter, type ItemFilterOp, type ItemRow, type ListItemsParams, type ListItemsResponse, type ListMarketplaceExtensionsParams, type Locale, type LumiClient, type LumiClientOptions, LumiError, type LumiErrorBody, type LumiResponse, type MarketplaceExtension, type MarketplaceListResponse, type MaterializeDataResponse, type MaterializeProjection, type MaterializeRefreshResult, type MaterializeRefreshStrategy, type MaterializedCollection, type MediaTransform, type NotificationCallback, type PermissionAction, type PermissionBundle, type PermissionCheckResult, type PermissionRow, type PolicyDetail, type PolicyResource, type PresenceCallback, type PresenceEntry, type PresetResource, type PresetScope, type PrimaryKeyType, type RealmAccessDescriptor, type RealmAccessGrant, type RealmAccessState, type RealmGrantInput, RealtimeClient, type RealtimeEvent, type RealtimeEventCallback, type RelationInput, type RelationResource, type RelationType, type RevisionRow, type RoleDetail, type RoleResource, type SCIMTokenCreated, type SCIMTokenMeta, type SCIMTokenRotated, type SchemaApplyInput, type SchemaApplyResult, type SchemaChangedEvent, type SchemaDiff, type SchemaDiffEntry, type SchemaDiffInput, type SchemaDiffRisk, type SchemaRuntimeImpact, type ScopedViewPreset, type SearchHit, type SearchHitMeta, type SearchParams, type SearchResponse, type SettingResource, type ShareCreateInput, type ShareResource, type ShareSecretResult, type SiteConfigUpdate, type SiteResource, type StatusCallback, type StorageMode, type TeamMemberResource, type TeamResource, type TmEntry, type TmSource, type TmSuggestion, type TranslationResource, type TypegenCollection, type TypegenField, type TypegenManifest, type TypegenRelation, type TypegenSchemaFilters, type UploadConfigResource, type UploadTypeCatalogueEntry, type UserPreferencesPayload, type UserResource, type VersionCompare, type VersionFieldChange, type ViewPreset, type WebSocketFactory, type WebSocketLike, type WebhookResource, ackCdcSubscription, checkCdcPipelineHealth, createAgentArtifact, createAgentGoal, createBookmark, createCdcPipeline, createCdcSubscription, createLumiClient, decideAgentApproval, deleteBookmark, deleteCdcPipeline, deleteCdcSubscription, deployCdc, dispatchCdcSubscription, dryRunAccessImport, evaluateAgentArtifact, exportAccessManifest, extractSeo, generateAgentApp, generateTypes, getEffectivePreset, graphql, importAccessManifest, jsonLdScript, legacyRest, listAgentApprovals, listAgentArtifacts, listAgentGoals, listAgentRuns, listAgentTools, listBookmarks, listCdcPipelines, listCdcSubscriptionDeliveries, listCdcSubscriptions, mediaUrl, publishAgentArtifact, readAgentMemoryContext, readCdcEvents, readCdcPipeline, readCdcPipelineMetricHistory, readCdcPipelineMetrics, readCdcSubscription, readItem, readItems, replayCdcSubscription, retryAgentRun, rollbackAgentArtifact, rollbackCdcDeployment, saveUserView, search, startCdcPipeline, stopCdcPipeline, toNextMetadata, updateBookmark, updateCdcPipeline, updateCdcSubscription, validateCdcDeploymentEnv, writeAgentMemory };
2753
+ export { ACCESS_EXPORT_SCHEMA, AudienceClient, DECISION_ERROR_CODES, DEFAULT_IMPORT_SOURCE, LumiError, RealtimeClient, ackCdcSubscription, checkCdcPipelineHealth, createAgentArtifact, createAgentGoal, createBookmark, createCdcPipeline, createCdcSubscription, createLumiClient, decide, decideAgentApproval, decisionErrorCode, deleteBookmark, deleteCdcPipeline, deleteCdcSubscription, deployCdc, dispatchCdcSubscription, dryRunAccessImport, evaluateAgentArtifact, exportAccessManifest, extractSeo, generateAgentApp, generateTypes, getEffectivePreset, getReview, getReviewProfile, graphql, importAccessManifest, jsonLdScript, legacyRest, listAgentApprovals, listAgentArtifacts, listAgentGoals, listAgentRuns, listAgentTools, listBookmarks, listCdcPipelines, listCdcSubscriptionDeliveries, listCdcSubscriptions, listReviewProfiles, listReviews, mediaUrl, publishAgentArtifact, readAgentMemoryContext, readCdcEvents, readCdcPipeline, readCdcPipelineMetricHistory, readCdcPipelineMetrics, readCdcSubscription, readItem, readItems, replayCdcSubscription, retryAgentRun, reviewContentHash, reviewDraft, rollbackAgentArtifact, rollbackCdcDeployment, saveUserView, search, startCdcPipeline, stopCdcPipeline, submitReviewFeedback, toNextMetadata, toWebSocketBase, updateBookmark, updateCdcPipeline, updateCdcSubscription, validateCdcDeploymentEnv, writeAgentMemory };
2754
+ export type { AIApproval, AIApprovalStatus, AIChatResponse, AIChatStatus, AIContentAssistResult, AIConversation, AIFieldSuggestion, AIMessage, AccessConflict, AccessConflictCheckInput, AccessConflictReport, AccessExportApiKey, AccessExportBindings, AccessExportManifest, AccessExportPermission, AccessExportPolicy, AccessExportRole, AccessImportApplyResult, AccessImportDiff, AccessImportDiffEntry, AccessImportDiffSection, AccessImportDryRunResult, AccessImportIssue, AccessImportMode, AccessImportOptions, AccessImportSummary, ActivityResource, AgentApprovalResource, AgentArtifactCreateInput, AgentArtifactResource, AgentArtifactType, AgentEvaluationResource, AgentGenerateAppInput, AgentGenerateAppResult, AgentGoalCreateInput, AgentGoalResource, AgentMemoryContext, AgentMemoryResource, AgentMemoryWriteInput, AgentRiskLevel, AgentRunResource, AgentToolResource, ApiKeyCreateInput, ApiKeyPolicyAttachment, ApiKeyResource, ApiKeyRoleAttachment, ApiKeyRotateInput, ApiKeySecretResult, AudienceClientOptions, AudienceEvent, AudienceNotification, Brand, CdcActorType, CdcConnectorType, CdcDeliveryResource, CdcDeployInput, CdcDeploymentResult, CdcDeploymentStatus, CdcDeploymentStep, CdcDeploymentTarget, CdcEnvValidationResult, CdcEventEnvelope, CdcFeedPage, CdcFeedReadParams, CdcHealthCheckResult, CdcHealthMetricEntry, CdcOperation, CdcPayloadMode, CdcPipelineCreateInput, CdcPipelineMetrics, CdcPipelinePatchInput, CdcPipelineResource, CdcPipelineStatus, CdcReplayInput, CdcRollbackResult, CdcSource, CdcSubscriptionCreateInput, CdcSubscriptionKind, CdcSubscriptionPatchInput, CdcSubscriptionResource, CdcSubscriptionStatus, CdcValidateEnvInput, ChannelEventCallback, ChoiceAnswer, ChoiceQuestion, CollectionInput, CollectionResource, CompiledPermission, ConnectionStatus, ContentVersion, CreateSCIMTokenParams, DecideOptions, DecisionAnswer, DecisionErrorCode, DecisionPayload, DecisionQuestion, DecisionRequest, DecisionResult, DefaultSchema, DeliverySeo, DeploymentResource, DeploymentTargetResource, DomainCreateInput, DomainResource, DomainVerificationRecord, ExtensionResource, FieldDeleteOptions, FieldInput, FieldMutationOptions, FieldRenameInput, FieldResource, FileResource, FlowGraph, FlowNode, FlowResource, FlowRun, FlowRunResult, FlowRunStatus, FlowStatus, FlowTriggerType, FolderResource, GenerateOptions, GrantAction, GraphQLExtension, ID, ItemFilter, ItemFilterOp, ItemRow, ListItemsParams, ListItemsResponse, ListMarketplaceExtensionsParams, Locale, LumiClient, LumiClientOptions, LumiErrorBody, LumiResponse, MarketplaceExtension, MarketplaceListResponse, MaterializeDataResponse, MaterializeProjection, MaterializeRefreshResult, MaterializeRefreshStrategy, MaterializedCollection, MediaTransform, NotificationCallback, NoulAnswer, NoulQuestion, PermissionAction, PermissionBundle, PermissionCheckResult, PermissionRow, PolicyDetail, PolicyResource, PresenceCallback, PresenceEntry, PresetResource, PresetScope, PrimaryKeyType, RealmAccessDescriptor, RealmAccessGrant, RealmAccessState, RealmGrantInput, RealtimeEvent, RealtimeEventCallback, RelationInput, RelationResource, RelationType, ReviewFeedback, ReviewFeedbackEntry, ReviewFeedbackRequest, ReviewPreset, ReviewProfile, ReviewRequestOptions, ReviewRun, ReviewRunRequest, ReviewRunStatus, ReviewStaleReason, ReviewVerdict, RevisionRow, RoleDetail, RoleResource, SCIMTokenCreated, SCIMTokenMeta, SCIMTokenRotated, SchemaApplyInput, SchemaApplyResult, SchemaChangedEvent, SchemaDiff, SchemaDiffEntry, SchemaDiffInput, SchemaDiffRisk, SchemaRuntimeImpact, ScopedViewPreset, ScoreAnswer, ScoreQuestion, SearchHit, SearchHitMeta, SearchParams, SearchResponse, SettingResource, ShareCreateInput, ShareResource, ShareSecretResult, SiteConfigUpdate, SiteResource, StatusCallback, StorageMode, TeamMemberResource, TeamResource, TmEntry, TmSource, TmSuggestion, TranslationResource, TypegenCollection, TypegenField, TypegenManifest, TypegenRelation, TypegenSchemaFilters, UploadConfigResource, UploadTypeCatalogueEntry, UserPreferencesPayload, UserResource, VersionCompare, VersionFieldChange, ViewPreset, WebSocketFactory, WebSocketLike, WebhookResource };
package/dist/index.d.ts CHANGED
@@ -1570,7 +1570,12 @@ interface LumiErrorBody {
1570
1570
  declare class LumiError extends Error {
1571
1571
  status: number;
1572
1572
  body: LumiErrorBody | any;
1573
- constructor(status: number, body: LumiErrorBody | any);
1573
+ /**
1574
+ * Seconds the server asked the caller to wait (`Retry-After`), or `null`
1575
+ * when the response carried none — e.g. a 429 site budget or rate limit.
1576
+ */
1577
+ readonly retryAfter: number | null;
1578
+ constructor(status: number, body: LumiErrorBody | any, headers?: Headers);
1574
1579
  }
1575
1580
  interface LumiClient<TSchema extends DefaultSchema = DefaultSchema> {
1576
1581
  url: string;
@@ -1667,6 +1672,19 @@ declare class AudienceClient {
1667
1672
  private sendRaw;
1668
1673
  }
1669
1674
 
1675
+ /**
1676
+ * Turn the client's HTTP `baseUrl` into the WebSocket origin for
1677
+ * `/api/v1/realtime`.
1678
+ *
1679
+ * `baseUrl` may legitimately be `''` or a path such as `/cms`: a browser app
1680
+ * served from the same origin as the CMS (Studio inside the Docker image)
1681
+ * talks to the API with relative URLs. `new URL('/api/v1/realtime')` throws
1682
+ * for those, so relative bases are resolved against `location` when one
1683
+ * exists. Outside a browser there is nothing to resolve against, and the
1684
+ * original error surfaces to the caller.
1685
+ */
1686
+ declare function toWebSocketBase(baseUrl: string): string;
1687
+
1670
1688
  /**
1671
1689
  * RealtimeClient — typed WebSocket client for the LumiBase realtime API.
1672
1690
  *
@@ -2277,6 +2295,292 @@ declare function mediaUrl(key: string, transform?: MediaTransform | {
2277
2295
  sign?: string;
2278
2296
  }): (client: LumiClient) => string;
2279
2297
 
2298
+ /**
2299
+ * SDK command for the decision model endpoint (`POST /api/v1/ai/decisions`):
2300
+ * typed `noul` / `choice` / `score` questions answered with probabilities by
2301
+ * TypeSafe Jev or the configured equivalent. Command factory
2302
+ * `(client) => Promise<T>`, matching the rest of the REST module.
2303
+ *
2304
+ * Provider keys never reach the SDK: the CMS holds them and the client only
2305
+ * sends its usual bearer + `X-Lumi-Site` headers.
2306
+ */
2307
+
2308
+ /** Free-form payload: plain text or structured data. */
2309
+ type DecisionPayload = string | Record<string, unknown> | unknown[];
2310
+ interface NoulQuestion {
2311
+ type: "noul";
2312
+ instructions: DecisionPayload;
2313
+ criteria: {
2314
+ true: DecisionPayload;
2315
+ false: DecisionPayload;
2316
+ };
2317
+ }
2318
+ interface ChoiceQuestion {
2319
+ type: "choice";
2320
+ instructions: DecisionPayload;
2321
+ /** Option key → description, or `null` when the key is self-explanatory. 2–255 options. */
2322
+ criteria: Record<string, DecisionPayload | null>;
2323
+ }
2324
+ interface ScoreQuestion {
2325
+ type: "score";
2326
+ instructions: DecisionPayload;
2327
+ /** Ordered rubric levels, lowest first. 2–10 levels. */
2328
+ criteria: DecisionPayload[];
2329
+ }
2330
+ type DecisionQuestion = NoulQuestion | ChoiceQuestion | ScoreQuestion;
2331
+ interface DecisionRequest {
2332
+ state: DecisionPayload;
2333
+ /** 1–32 questions keyed by `[A-Za-z0-9_-]{1,64}`. */
2334
+ questions: Record<string, DecisionQuestion>;
2335
+ }
2336
+ interface NoulAnswer {
2337
+ type: "noul";
2338
+ /** P(the `true` criterion holds), 0..1. */
2339
+ noul: number;
2340
+ }
2341
+ interface ChoiceAnswer {
2342
+ type: "choice";
2343
+ choice: string;
2344
+ probabilities: Record<string, number>;
2345
+ confidence: number;
2346
+ }
2347
+ interface ScoreAnswer {
2348
+ type: "score";
2349
+ score: number;
2350
+ legend: Record<string, unknown>;
2351
+ probabilities: Record<string, number>;
2352
+ confidence: number;
2353
+ }
2354
+ type DecisionAnswer = NoulAnswer | ChoiceAnswer | ScoreAnswer;
2355
+ interface DecisionResult {
2356
+ /** `typesafe`, `openrouter` or `llm`. */
2357
+ provider: string;
2358
+ model: string;
2359
+ /**
2360
+ * `false` when `DECISION_PROVIDER=llm`: probabilities are self-reported by
2361
+ * the LLM. `true` is the provider's claim, not a calibration on your data.
2362
+ */
2363
+ calibrated: boolean;
2364
+ answers: Record<string, DecisionAnswer>;
2365
+ /** `null` when the provider did not report the count (unknown, not zero). */
2366
+ usage: {
2367
+ inputTokens: number | null;
2368
+ outputTokens: number | null;
2369
+ };
2370
+ }
2371
+ /**
2372
+ * Every `errors[0].code` the decision and draft review endpoints return
2373
+ * (`POST /ai/decisions`, `/ai/review-profiles*`, `/ai/reviews*`), carried on
2374
+ * `LumiError.body`. Read it with {@link decisionErrorCode}.
2375
+ */
2376
+ declare const DECISION_ERROR_CODES: readonly ["VALIDATION", "FORBIDDEN", "DECISION_DISABLED", "DECISION_FIELD_NOT_ALLOWED", "DECISION_QUOTA_EXCEEDED", "DECISION_CONCURRENCY_LIMITED", "DECISION_QUOTA_UNAVAILABLE", "DECISION_NOT_CONFIGURED", "DECISION_AUTH", "DECISION_VALIDATION", "DECISION_RATE_LIMITED", "DECISION_UNAVAILABLE", "DECISION_UPSTREAM", "DECISION_PARSE_FAILED", "DECISION_TIMEOUT", "DECISION_CANCELLED", "DECISION_INPUT_TOO_LARGE", "REVIEW_PROFILE_NOT_FOUND", "REVIEW_PROFILE_EXISTS", "REVIEW_PROFILE_CONFLICT", "REVIEW_ITEM_NOT_FOUND", "REVIEW_RUN_NOT_FOUND", "REVIEW_FIELD_NOT_ALLOWED", "REVIEW_COLLECTION_MISMATCH", "REVIEW_NOT_COMPLETE", "REVIEW_STALE", "REVIEW_SESSION_MODE_MISMATCH", "REVIEW_SESSION_RUN_INVALID", "INTERNAL"];
2377
+ type DecisionErrorCode = (typeof DECISION_ERROR_CODES)[number];
2378
+ /**
2379
+ * The typed `errors[0].code` of a rejected decision or review call, or `null`
2380
+ * when `err` is not a `LumiError` with a known code (network failure, abort,
2381
+ * or a code this SDK version does not know — read `err.body` for those).
2382
+ */
2383
+ declare function decisionErrorCode(err: unknown): DecisionErrorCode | null;
2384
+ interface DecideOptions {
2385
+ /**
2386
+ * Aborts the HTTP request; the promise rejects with the fetch `AbortError`.
2387
+ * The CMS sees the disconnect, aborts its upstream call and does not retry.
2388
+ */
2389
+ signal?: AbortSignal;
2390
+ }
2391
+ /**
2392
+ * Ask the decision model typed questions about `state`. Read-only on the
2393
+ * server. Rejects with `LumiError` on non-2xx — e.g. 503 with
2394
+ * `DECISION_NOT_CONFIGURED` when the CMS has no `DECISION_PROVIDER`.
2395
+ *
2396
+ * Call it from a server with a secret API key or from Studio: a publishable
2397
+ * API key (`lbk_pub_…`) or a frontend session gets 403 `FORBIDDEN`, even when
2398
+ * its role grants `ai:decide`.
2399
+ *
2400
+ * The caller needs the `ai:decide` capability (403 `FORBIDDEN`), the site
2401
+ * must have opted in (403 `DECISION_DISABLED`), and each site has hourly,
2402
+ * concurrency and daily budgets (429 `DECISION_QUOTA_EXCEEDED` /
2403
+ * `DECISION_CONCURRENCY_LIMITED`, with `Retry-After`).
2404
+ */
2405
+ declare function decide(request: DecisionRequest, options?: DecideOptions): (client: LumiClient) => Promise<DecisionResult>;
2406
+
2407
+ /**
2408
+ * SDK commands for draft review (#512): read the site's versioned review
2409
+ * profiles, review a saved item or an unsaved draft, read a run with its
2410
+ * staleness, and record editor feedback. Command factories
2411
+ * `(client) => Promise<T>`, like {@link decide}.
2412
+ *
2413
+ * A review only suggests. None of these calls writes to an item; applying a
2414
+ * suggestion is the caller's own item update, under its own permissions.
2415
+ *
2416
+ * The SDK has no runtime dependencies, so these types mirror the CMS
2417
+ * contracts (`@lumibase/contracts` `decision-review.ts`). A type-equality test
2418
+ * (`__tests__/reviews.contract.test.ts`) fails the SDK typecheck when the two
2419
+ * drift. Provider keys stay on the CMS; the client only sends its usual
2420
+ * bearer and `X-Lumi-Site` headers.
2421
+ */
2422
+
2423
+ type ReviewPreset = "taxonomy" | "brand-voice" | "brief-alignment";
2424
+ type ReviewRunStatus = "running" | "success" | "abstained" | "error";
2425
+ type ReviewVerdict = "accept" | "edit" | "reject";
2426
+ /** `content_changed` / `revision_changed`: the item moved on; `item_unavailable`: it is gone or unreadable. */
2427
+ type ReviewStaleReason = "content_changed" | "revision_changed" | "item_unavailable";
2428
+ /** A versioned review profile. Rows are immutable; a new version archives the previous one. */
2429
+ interface ReviewProfile {
2430
+ id: string;
2431
+ key: string;
2432
+ version: number;
2433
+ status: "active" | "archived";
2434
+ /** Collection the profile applies to; `null` = any collection. */
2435
+ collection: string | null;
2436
+ preset: ReviewPreset | null;
2437
+ /** Top-level item fields the review reads. */
2438
+ fields: string[];
2439
+ questions: Record<string, DecisionQuestion>;
2440
+ sourceField: string | null;
2441
+ minConfidence: number | null;
2442
+ /** Caveat, e.g. "no source — not a fact-check". */
2443
+ note: string | null;
2444
+ createdBy: string | null;
2445
+ createdAt: string;
2446
+ }
2447
+ /** `POST /ai/reviews`. Give exactly one of `itemId` (saved item) or `snapshot` (unsaved draft). */
2448
+ interface ReviewRunRequest {
2449
+ /** Profile key. */
2450
+ profile: string;
2451
+ /** Defaults to the active version. */
2452
+ profileVersion?: number;
2453
+ collection: string;
2454
+ itemId?: string;
2455
+ /** Unsaved field values. Every key must be a profile field the caller may read and write. */
2456
+ snapshot?: Record<string, unknown>;
2457
+ /**
2458
+ * 8–128 chars. Same key from the same principal → the stored run, no second
2459
+ * provider call, whatever the content now is. The key must therefore change
2460
+ * when the content or profile version does: build it from
2461
+ * {@link reviewContentHash} and the profile version, never from a fixed id.
2462
+ */
2463
+ idempotencyKey?: string;
2464
+ }
2465
+ interface ReviewRun {
2466
+ /** uuidv7. */
2467
+ id: string;
2468
+ profileId: string;
2469
+ profileKey: string;
2470
+ profileVersion: number;
2471
+ collection: string;
2472
+ itemId: string | null;
2473
+ revisionId: string | null;
2474
+ /** `sha256:<hex>` of the canonical JSON of the reviewed fields. */
2475
+ contentHash: string;
2476
+ source: "item" | "snapshot";
2477
+ /** Profile fields the caller could not read; they were not sent. */
2478
+ omittedFields: string[];
2479
+ /** `abstained`: every choice was `other`/`unknown`, or a confidence fell below the profile minimum. */
2480
+ status: ReviewRunStatus;
2481
+ provider: string | null;
2482
+ model: string | null;
2483
+ /** `null` until the run completes; `false` when the CMS answers with `DECISION_PROVIDER=llm`. */
2484
+ calibrated: boolean | null;
2485
+ /** Keyed by question; `null` until the run completes or when it failed. */
2486
+ answers: Record<string, DecisionAnswer> | null;
2487
+ /** `null` until the run completes; a `null` count is unknown, not zero. */
2488
+ usage: {
2489
+ inputTokens: number | null;
2490
+ outputTokens: number | null;
2491
+ } | null;
2492
+ latencyMs: number | null;
2493
+ /** The decision error code when `status` is `error`. */
2494
+ errorCode: string | null;
2495
+ createdAt: string;
2496
+ completedAt: string | null;
2497
+ /** Item runs: the item changed since the run. Snapshot runs report `false` (checked on feedback). */
2498
+ stale: boolean;
2499
+ staleReason: ReviewStaleReason | null;
2500
+ note: string | null;
2501
+ }
2502
+ interface ReviewFeedbackEntry {
2503
+ questionKey: string;
2504
+ verdict: ReviewVerdict;
2505
+ /** Required for `edit`: the value the editor chose instead. */
2506
+ editedValue?: unknown;
2507
+ }
2508
+ /** `POST /ai/reviews/:id/feedback`. One entry per question. */
2509
+ interface ReviewFeedbackRequest {
2510
+ entries: ReviewFeedbackEntry[];
2511
+ /** Accept/edit on a stale run is refused (409 `REVIEW_STALE`) unless this is `true`. */
2512
+ acknowledgeStale?: boolean;
2513
+ /**
2514
+ * Snapshot runs: {@link reviewContentHash} of the draft the editor sees now.
2515
+ * A value other than `run.contentHash` makes accept/edit fail with 409
2516
+ * `REVIEW_STALE`. Without it (or with `run.contentHash` itself) a changed
2517
+ * draft is not detected, because the CMS cannot re-read an unsaved draft.
2518
+ */
2519
+ contentHash?: string;
2520
+ }
2521
+ /** Stored feedback. The first verdict per run, question and principal is final. */
2522
+ interface ReviewFeedback {
2523
+ id: string;
2524
+ runId: string;
2525
+ questionKey: string;
2526
+ verdict: ReviewVerdict;
2527
+ editedValue: unknown;
2528
+ principalType: string;
2529
+ principalId: string;
2530
+ createdAt: string;
2531
+ }
2532
+ interface ReviewRequestOptions {
2533
+ /** Aborts the HTTP request; the promise rejects with the fetch `AbortError`. */
2534
+ signal?: AbortSignal;
2535
+ }
2536
+ /**
2537
+ * `sha256:<64 hex>` of the canonical JSON (sorted keys, dates serialised,
2538
+ * `undefined` dropped) of `values`, computed exactly as the CMS computes
2539
+ * `ReviewRun.contentHash`. Uses WebCrypto (`crypto.subtle`), so it runs in
2540
+ * browsers, Node 18+ and Workers.
2541
+ *
2542
+ * Use it on the draft the editor sees now:
2543
+ * - pass it as `contentHash` to {@link submitReviewFeedback} on a snapshot run,
2544
+ * so the CMS answers 409 `REVIEW_STALE` when the draft changed after the
2545
+ * review. Sending the run's own `contentHash` back disables that check;
2546
+ * - build the `idempotencyKey` of {@link reviewDraft} from it, so a changed
2547
+ * draft gets a new run instead of a replay of the old one.
2548
+ *
2549
+ * For a snapshot run, hash the same fields you sent as `snapshot`.
2550
+ */
2551
+ declare function reviewContentHash(values: Record<string, unknown>): Promise<string>;
2552
+ /** Active profiles of the site; with `collection`, those bound to it or to any collection. Needs `ai:decide`. */
2553
+ declare function listReviewProfiles(params?: {
2554
+ collection?: string;
2555
+ }, options?: ReviewRequestOptions): (client: LumiClient) => Promise<ReviewProfile[]>;
2556
+ /** One profile: the active version, or `version`. 404 `REVIEW_PROFILE_NOT_FOUND`. */
2557
+ declare function getReviewProfile(key: string, params?: {
2558
+ version?: number;
2559
+ }, options?: ReviewRequestOptions): (client: LumiClient) => Promise<ReviewProfile>;
2560
+ /**
2561
+ * Review a saved item (`itemId`) or an unsaved draft (`snapshot`) with a
2562
+ * profile. Runs the governed decision path: rejects with `LumiError` carrying
2563
+ * the same codes as {@link decide} (403 `DECISION_DISABLED`, 429 with
2564
+ * `retryAfter`, 504 `DECISION_TIMEOUT`, …) plus 422 `REVIEW_FIELD_NOT_ALLOWED`
2565
+ * for a snapshot field outside the profile or the caller's permissions.
2566
+ * Resolves with the run — a replay of the same `idempotencyKey` returns the
2567
+ * stored run without a second provider call.
2568
+ */
2569
+ declare function reviewDraft(request: ReviewRunRequest, options?: ReviewRequestOptions): (client: LumiClient) => Promise<ReviewRun>;
2570
+ /** A run with its current staleness. 404 `REVIEW_RUN_NOT_FOUND` also when the caller cannot read what it reviewed. */
2571
+ declare function getReview(id: string, options?: ReviewRequestOptions): (client: LumiClient) => Promise<ReviewRun>;
2572
+ /** Runs of one item the caller may see, newest first (50 at most). */
2573
+ declare function listReviews(params: {
2574
+ collection: string;
2575
+ itemId: string;
2576
+ }, options?: ReviewRequestOptions): (client: LumiClient) => Promise<ReviewRun[]>;
2577
+ /**
2578
+ * Record accept / edit / reject on a run's answers. A retry returns the
2579
+ * stored rows and adds none. `accept`/`edit` on a stale run rejects with 409
2580
+ * `REVIEW_STALE` unless `acknowledgeStale: true`. Never changes the item.
2581
+ */
2582
+ declare function submitReviewFeedback(runId: string, request: ReviewFeedbackRequest, options?: ReviewRequestOptions): (client: LumiClient) => Promise<ReviewFeedback[]>;
2583
+
2280
2584
  /**
2281
2585
  * Full-text search via `GET /api/v1/search`. Omit `params.collection` for a
2282
2586
  * cross-collection (global) search that fans out over every collection of the
@@ -2446,4 +2750,5 @@ declare function toNextMetadata(item: unknown): Record<string, unknown>;
2446
2750
  */
2447
2751
  declare function jsonLdScript(item: unknown): string | undefined;
2448
2752
 
2449
- export { ACCESS_EXPORT_SCHEMA, type AIApproval, type AIApprovalStatus, type AIChatResponse, type AIChatStatus, type AIContentAssistResult, type AIConversation, type AIFieldSuggestion, type AIMessage, type AccessConflict, type AccessConflictCheckInput, type AccessConflictReport, type AccessExportApiKey, type AccessExportBindings, type AccessExportManifest, type AccessExportPermission, type AccessExportPolicy, type AccessExportRole, type AccessImportApplyResult, type AccessImportDiff, type AccessImportDiffEntry, type AccessImportDiffSection, type AccessImportDryRunResult, type AccessImportIssue, type AccessImportMode, type AccessImportOptions, type AccessImportSummary, type ActivityResource, type AgentApprovalResource, type AgentArtifactCreateInput, type AgentArtifactResource, type AgentArtifactType, type AgentEvaluationResource, type AgentGenerateAppInput, type AgentGenerateAppResult, type AgentGoalCreateInput, type AgentGoalResource, type AgentMemoryContext, type AgentMemoryResource, type AgentMemoryWriteInput, type AgentRiskLevel, type AgentRunResource, type AgentToolResource, type ApiKeyCreateInput, type ApiKeyPolicyAttachment, type ApiKeyResource, type ApiKeyRoleAttachment, type ApiKeyRotateInput, type ApiKeySecretResult, AudienceClient, type AudienceClientOptions, type AudienceEvent, type AudienceNotification, type Brand, type CdcActorType, type CdcConnectorType, type CdcDeliveryResource, type CdcDeployInput, type CdcDeploymentResult, type CdcDeploymentStatus, type CdcDeploymentStep, type CdcDeploymentTarget, type CdcEnvValidationResult, type CdcEventEnvelope, type CdcFeedPage, type CdcFeedReadParams, type CdcHealthCheckResult, type CdcHealthMetricEntry, type CdcOperation, type CdcPayloadMode, type CdcPipelineCreateInput, type CdcPipelineMetrics, type CdcPipelinePatchInput, type CdcPipelineResource, type CdcPipelineStatus, type CdcReplayInput, type CdcRollbackResult, type CdcSource, type CdcSubscriptionCreateInput, type CdcSubscriptionKind, type CdcSubscriptionPatchInput, type CdcSubscriptionResource, type CdcSubscriptionStatus, type CdcValidateEnvInput, type ChannelEventCallback, type CollectionInput, type CollectionResource, type CompiledPermission, type ConnectionStatus, type ContentVersion, type CreateSCIMTokenParams, DEFAULT_IMPORT_SOURCE, type DefaultSchema, type DeliverySeo, type DeploymentResource, type DeploymentTargetResource, type DomainCreateInput, type DomainResource, type DomainVerificationRecord, type ExtensionResource, type FieldDeleteOptions, type FieldInput, type FieldMutationOptions, type FieldRenameInput, type FieldResource, type FileResource, type FlowGraph, type FlowNode, type FlowResource, type FlowRun, type FlowRunResult, type FlowRunStatus, type FlowStatus, type FlowTriggerType, type FolderResource, type GenerateOptions, type GrantAction, type GraphQLExtension, type ID, type ItemFilter, type ItemFilterOp, type ItemRow, type ListItemsParams, type ListItemsResponse, type ListMarketplaceExtensionsParams, type Locale, type LumiClient, type LumiClientOptions, LumiError, type LumiErrorBody, type LumiResponse, type MarketplaceExtension, type MarketplaceListResponse, type MaterializeDataResponse, type MaterializeProjection, type MaterializeRefreshResult, type MaterializeRefreshStrategy, type MaterializedCollection, type MediaTransform, type NotificationCallback, type PermissionAction, type PermissionBundle, type PermissionCheckResult, type PermissionRow, type PolicyDetail, type PolicyResource, type PresenceCallback, type PresenceEntry, type PresetResource, type PresetScope, type PrimaryKeyType, type RealmAccessDescriptor, type RealmAccessGrant, type RealmAccessState, type RealmGrantInput, RealtimeClient, type RealtimeEvent, type RealtimeEventCallback, type RelationInput, type RelationResource, type RelationType, type RevisionRow, type RoleDetail, type RoleResource, type SCIMTokenCreated, type SCIMTokenMeta, type SCIMTokenRotated, type SchemaApplyInput, type SchemaApplyResult, type SchemaChangedEvent, type SchemaDiff, type SchemaDiffEntry, type SchemaDiffInput, type SchemaDiffRisk, type SchemaRuntimeImpact, type ScopedViewPreset, type SearchHit, type SearchHitMeta, type SearchParams, type SearchResponse, type SettingResource, type ShareCreateInput, type ShareResource, type ShareSecretResult, type SiteConfigUpdate, type SiteResource, type StatusCallback, type StorageMode, type TeamMemberResource, type TeamResource, type TmEntry, type TmSource, type TmSuggestion, type TranslationResource, type TypegenCollection, type TypegenField, type TypegenManifest, type TypegenRelation, type TypegenSchemaFilters, type UploadConfigResource, type UploadTypeCatalogueEntry, type UserPreferencesPayload, type UserResource, type VersionCompare, type VersionFieldChange, type ViewPreset, type WebSocketFactory, type WebSocketLike, type WebhookResource, ackCdcSubscription, checkCdcPipelineHealth, createAgentArtifact, createAgentGoal, createBookmark, createCdcPipeline, createCdcSubscription, createLumiClient, decideAgentApproval, deleteBookmark, deleteCdcPipeline, deleteCdcSubscription, deployCdc, dispatchCdcSubscription, dryRunAccessImport, evaluateAgentArtifact, exportAccessManifest, extractSeo, generateAgentApp, generateTypes, getEffectivePreset, graphql, importAccessManifest, jsonLdScript, legacyRest, listAgentApprovals, listAgentArtifacts, listAgentGoals, listAgentRuns, listAgentTools, listBookmarks, listCdcPipelines, listCdcSubscriptionDeliveries, listCdcSubscriptions, mediaUrl, publishAgentArtifact, readAgentMemoryContext, readCdcEvents, readCdcPipeline, readCdcPipelineMetricHistory, readCdcPipelineMetrics, readCdcSubscription, readItem, readItems, replayCdcSubscription, retryAgentRun, rollbackAgentArtifact, rollbackCdcDeployment, saveUserView, search, startCdcPipeline, stopCdcPipeline, toNextMetadata, updateBookmark, updateCdcPipeline, updateCdcSubscription, validateCdcDeploymentEnv, writeAgentMemory };
2753
+ export { ACCESS_EXPORT_SCHEMA, AudienceClient, DECISION_ERROR_CODES, DEFAULT_IMPORT_SOURCE, LumiError, RealtimeClient, ackCdcSubscription, checkCdcPipelineHealth, createAgentArtifact, createAgentGoal, createBookmark, createCdcPipeline, createCdcSubscription, createLumiClient, decide, decideAgentApproval, decisionErrorCode, deleteBookmark, deleteCdcPipeline, deleteCdcSubscription, deployCdc, dispatchCdcSubscription, dryRunAccessImport, evaluateAgentArtifact, exportAccessManifest, extractSeo, generateAgentApp, generateTypes, getEffectivePreset, getReview, getReviewProfile, graphql, importAccessManifest, jsonLdScript, legacyRest, listAgentApprovals, listAgentArtifacts, listAgentGoals, listAgentRuns, listAgentTools, listBookmarks, listCdcPipelines, listCdcSubscriptionDeliveries, listCdcSubscriptions, listReviewProfiles, listReviews, mediaUrl, publishAgentArtifact, readAgentMemoryContext, readCdcEvents, readCdcPipeline, readCdcPipelineMetricHistory, readCdcPipelineMetrics, readCdcSubscription, readItem, readItems, replayCdcSubscription, retryAgentRun, reviewContentHash, reviewDraft, rollbackAgentArtifact, rollbackCdcDeployment, saveUserView, search, startCdcPipeline, stopCdcPipeline, submitReviewFeedback, toNextMetadata, toWebSocketBase, updateBookmark, updateCdcPipeline, updateCdcSubscription, validateCdcDeploymentEnv, writeAgentMemory };
2754
+ export type { AIApproval, AIApprovalStatus, AIChatResponse, AIChatStatus, AIContentAssistResult, AIConversation, AIFieldSuggestion, AIMessage, AccessConflict, AccessConflictCheckInput, AccessConflictReport, AccessExportApiKey, AccessExportBindings, AccessExportManifest, AccessExportPermission, AccessExportPolicy, AccessExportRole, AccessImportApplyResult, AccessImportDiff, AccessImportDiffEntry, AccessImportDiffSection, AccessImportDryRunResult, AccessImportIssue, AccessImportMode, AccessImportOptions, AccessImportSummary, ActivityResource, AgentApprovalResource, AgentArtifactCreateInput, AgentArtifactResource, AgentArtifactType, AgentEvaluationResource, AgentGenerateAppInput, AgentGenerateAppResult, AgentGoalCreateInput, AgentGoalResource, AgentMemoryContext, AgentMemoryResource, AgentMemoryWriteInput, AgentRiskLevel, AgentRunResource, AgentToolResource, ApiKeyCreateInput, ApiKeyPolicyAttachment, ApiKeyResource, ApiKeyRoleAttachment, ApiKeyRotateInput, ApiKeySecretResult, AudienceClientOptions, AudienceEvent, AudienceNotification, Brand, CdcActorType, CdcConnectorType, CdcDeliveryResource, CdcDeployInput, CdcDeploymentResult, CdcDeploymentStatus, CdcDeploymentStep, CdcDeploymentTarget, CdcEnvValidationResult, CdcEventEnvelope, CdcFeedPage, CdcFeedReadParams, CdcHealthCheckResult, CdcHealthMetricEntry, CdcOperation, CdcPayloadMode, CdcPipelineCreateInput, CdcPipelineMetrics, CdcPipelinePatchInput, CdcPipelineResource, CdcPipelineStatus, CdcReplayInput, CdcRollbackResult, CdcSource, CdcSubscriptionCreateInput, CdcSubscriptionKind, CdcSubscriptionPatchInput, CdcSubscriptionResource, CdcSubscriptionStatus, CdcValidateEnvInput, ChannelEventCallback, ChoiceAnswer, ChoiceQuestion, CollectionInput, CollectionResource, CompiledPermission, ConnectionStatus, ContentVersion, CreateSCIMTokenParams, DecideOptions, DecisionAnswer, DecisionErrorCode, DecisionPayload, DecisionQuestion, DecisionRequest, DecisionResult, DefaultSchema, DeliverySeo, DeploymentResource, DeploymentTargetResource, DomainCreateInput, DomainResource, DomainVerificationRecord, ExtensionResource, FieldDeleteOptions, FieldInput, FieldMutationOptions, FieldRenameInput, FieldResource, FileResource, FlowGraph, FlowNode, FlowResource, FlowRun, FlowRunResult, FlowRunStatus, FlowStatus, FlowTriggerType, FolderResource, GenerateOptions, GrantAction, GraphQLExtension, ID, ItemFilter, ItemFilterOp, ItemRow, ListItemsParams, ListItemsResponse, ListMarketplaceExtensionsParams, Locale, LumiClient, LumiClientOptions, LumiErrorBody, LumiResponse, MarketplaceExtension, MarketplaceListResponse, MaterializeDataResponse, MaterializeProjection, MaterializeRefreshResult, MaterializeRefreshStrategy, MaterializedCollection, MediaTransform, NotificationCallback, NoulAnswer, NoulQuestion, PermissionAction, PermissionBundle, PermissionCheckResult, PermissionRow, PolicyDetail, PolicyResource, PresenceCallback, PresenceEntry, PresetResource, PresetScope, PrimaryKeyType, RealmAccessDescriptor, RealmAccessGrant, RealmAccessState, RealmGrantInput, RealtimeEvent, RealtimeEventCallback, RelationInput, RelationResource, RelationType, ReviewFeedback, ReviewFeedbackEntry, ReviewFeedbackRequest, ReviewPreset, ReviewProfile, ReviewRequestOptions, ReviewRun, ReviewRunRequest, ReviewRunStatus, ReviewStaleReason, ReviewVerdict, RevisionRow, RoleDetail, RoleResource, SCIMTokenCreated, SCIMTokenMeta, SCIMTokenRotated, SchemaApplyInput, SchemaApplyResult, SchemaChangedEvent, SchemaDiff, SchemaDiffEntry, SchemaDiffInput, SchemaDiffRisk, SchemaRuntimeImpact, ScopedViewPreset, ScoreAnswer, ScoreQuestion, SearchHit, SearchHitMeta, SearchParams, SearchResponse, SettingResource, ShareCreateInput, ShareResource, ShareSecretResult, SiteConfigUpdate, SiteResource, StatusCallback, StorageMode, TeamMemberResource, TeamResource, TmEntry, TmSource, TmSuggestion, TranslationResource, TypegenCollection, TypegenField, TypegenManifest, TypegenRelation, TypegenSchemaFilters, UploadConfigResource, UploadTypeCatalogueEntry, UserPreferencesPayload, UserResource, VersionCompare, VersionFieldChange, ViewPreset, WebSocketFactory, WebSocketLike, WebhookResource };
package/dist/index.js CHANGED
@@ -1,14 +1,28 @@
1
1
  // src/client.ts
2
2
  var LumiError = class extends Error {
3
- constructor(status, body) {
3
+ constructor(status, body, headers) {
4
4
  super(body?.errors?.[0]?.message ?? `LumiBase ${status}`);
5
5
  this.status = status;
6
6
  this.body = body;
7
7
  this.name = "LumiError";
8
+ this.retryAfter = parseRetryAfter(headers?.get("retry-after") ?? null);
8
9
  }
9
10
  status;
10
11
  body;
12
+ /**
13
+ * Seconds the server asked the caller to wait (`Retry-After`), or `null`
14
+ * when the response carried none — e.g. a 429 site budget or rate limit.
15
+ */
16
+ retryAfter;
11
17
  };
18
+ function parseRetryAfter(value) {
19
+ if (value === null) return null;
20
+ const trimmed = value.trim();
21
+ if (/^\d+$/.test(trimmed)) return Number(trimmed);
22
+ const at = Date.parse(trimmed);
23
+ if (Number.isNaN(at)) return null;
24
+ return Math.max(0, Math.ceil((at - Date.now()) / 1e3));
25
+ }
12
26
  function parseResponseBody(text) {
13
27
  if (!text) return null;
14
28
  try {
@@ -99,7 +113,7 @@ function createLumiClient(opts) {
99
113
  } catch {
100
114
  }
101
115
  }
102
- throw new LumiError(res.status, toErrorBody(res.status, body));
116
+ throw new LumiError(res.status, toErrorBody(res.status, body), res.headers);
103
117
  }
104
118
  return body;
105
119
  }
@@ -125,6 +139,24 @@ function createLumiClient(opts) {
125
139
  // src/types.ts
126
140
  var ACCESS_EXPORT_SCHEMA = "lumibase.access@v1";
127
141
 
142
+ // src/realtime/ws-url.ts
143
+ function toWebSocketBase(baseUrl) {
144
+ const trimmed = trimTrailingSlashes(baseUrl);
145
+ let absolute = trimmed;
146
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) {
147
+ const origin = globalThis.location?.origin;
148
+ if (origin && origin !== "null") {
149
+ absolute = trimTrailingSlashes(new URL(trimmed || "/", origin).toString());
150
+ }
151
+ }
152
+ return absolute.replace(/^http/i, "ws");
153
+ }
154
+ function trimTrailingSlashes(value) {
155
+ let end = value.length;
156
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
157
+ return end === value.length ? value : value.slice(0, end);
158
+ }
159
+
128
160
  // src/realtime/audience.ts
129
161
  var WS_OPEN = 1;
130
162
  var AudienceClient = class {
@@ -214,8 +246,7 @@ var AudienceClient = class {
214
246
  return;
215
247
  }
216
248
  if (this.stopped) return;
217
- const wsBase = this.opts.baseUrl.replace(/^http/, "ws");
218
- const url = `${wsBase}/api/v1/realtime?ticket=${encodeURIComponent(ticket)}`;
249
+ const url = `${toWebSocketBase(this.opts.baseUrl)}/api/v1/realtime?ticket=${encodeURIComponent(ticket)}`;
219
250
  const factory = this.opts.webSocketFactory ?? ((u) => new WebSocket(u));
220
251
  let ws;
221
252
  try {
@@ -398,8 +429,14 @@ var RealtimeClient = class {
398
429
  return;
399
430
  }
400
431
  if (this.stopped) return;
401
- const wsBase = baseUrl.replace(/^http/, "ws");
402
- const url = new URL(`${wsBase}/api/v1/realtime`);
432
+ let url;
433
+ try {
434
+ url = new URL(`${toWebSocketBase(baseUrl)}/api/v1/realtime`);
435
+ } catch (err) {
436
+ console.warn("[RealtimeClient] Cannot build the realtime URL from baseUrl", baseUrl, err);
437
+ this.stopped = true;
438
+ return;
439
+ }
403
440
  url.searchParams.set("ticket", ticket);
404
441
  url.searchParams.set("site", siteId);
405
442
  url.searchParams.set("siteId", siteId);
@@ -1210,6 +1247,139 @@ function mediaUrl(key, transform, opts) {
1210
1247
  };
1211
1248
  }
1212
1249
 
1250
+ // src/rest/decisions.ts
1251
+ var DECISION_ERROR_CODES = [
1252
+ "VALIDATION",
1253
+ "FORBIDDEN",
1254
+ // Governance (#511): checked before the provider is called.
1255
+ "DECISION_DISABLED",
1256
+ "DECISION_FIELD_NOT_ALLOWED",
1257
+ "DECISION_QUOTA_EXCEEDED",
1258
+ "DECISION_CONCURRENCY_LIMITED",
1259
+ "DECISION_QUOTA_UNAVAILABLE",
1260
+ // Provider and limits (#504, #509).
1261
+ "DECISION_NOT_CONFIGURED",
1262
+ "DECISION_AUTH",
1263
+ "DECISION_VALIDATION",
1264
+ "DECISION_RATE_LIMITED",
1265
+ "DECISION_UNAVAILABLE",
1266
+ "DECISION_UPSTREAM",
1267
+ "DECISION_PARSE_FAILED",
1268
+ "DECISION_TIMEOUT",
1269
+ "DECISION_CANCELLED",
1270
+ "DECISION_INPUT_TOO_LARGE",
1271
+ // Draft review (#512).
1272
+ "REVIEW_PROFILE_NOT_FOUND",
1273
+ "REVIEW_PROFILE_EXISTS",
1274
+ "REVIEW_PROFILE_CONFLICT",
1275
+ "REVIEW_ITEM_NOT_FOUND",
1276
+ "REVIEW_RUN_NOT_FOUND",
1277
+ "REVIEW_FIELD_NOT_ALLOWED",
1278
+ "REVIEW_COLLECTION_MISMATCH",
1279
+ "REVIEW_NOT_COMPLETE",
1280
+ "REVIEW_STALE",
1281
+ // Draft-review pilot sessions (#516).
1282
+ "REVIEW_SESSION_MODE_MISMATCH",
1283
+ "REVIEW_SESSION_RUN_INVALID",
1284
+ "INTERNAL"
1285
+ ];
1286
+ var KNOWN_CODES = new Set(DECISION_ERROR_CODES);
1287
+ function decisionErrorCode(err) {
1288
+ if (!(err instanceof LumiError)) return null;
1289
+ const code = err.body?.errors?.[0]?.code;
1290
+ return typeof code === "string" && KNOWN_CODES.has(code) ? code : null;
1291
+ }
1292
+ function decide(request, options = {}) {
1293
+ return async (client) => {
1294
+ const res = await client.rawRequest("/api/v1/ai/decisions", {
1295
+ method: "POST",
1296
+ body: JSON.stringify(request),
1297
+ signal: options.signal
1298
+ });
1299
+ return res.data;
1300
+ };
1301
+ }
1302
+
1303
+ // src/rest/reviews.ts
1304
+ function canonicalize(value) {
1305
+ if (Array.isArray(value)) return value.map(canonicalize);
1306
+ if (value && typeof value === "object") {
1307
+ const out = {};
1308
+ for (const key of Object.keys(value).sort()) out[key] = canonicalize(value[key]);
1309
+ return out;
1310
+ }
1311
+ return value;
1312
+ }
1313
+ async function reviewContentHash(values) {
1314
+ const canonical = JSON.stringify(canonicalize(JSON.parse(JSON.stringify(values ?? null))));
1315
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical)));
1316
+ return `sha256:${Array.from(digest, (b) => b.toString(16).padStart(2, "0")).join("")}`;
1317
+ }
1318
+ var BASE = "/api/v1/ai";
1319
+ function withQuery2(path, params) {
1320
+ const qs = new URLSearchParams();
1321
+ for (const [key, value] of Object.entries(params)) if (value !== void 0) qs.set(key, value);
1322
+ const s = qs.toString();
1323
+ return s ? `${path}?${s}` : path;
1324
+ }
1325
+ function listReviewProfiles(params = {}, options = {}) {
1326
+ return async (client) => {
1327
+ const res = await client.rawRequest(
1328
+ withQuery2(`${BASE}/review-profiles`, { collection: params.collection }),
1329
+ { signal: options.signal }
1330
+ );
1331
+ return res.data;
1332
+ };
1333
+ }
1334
+ function getReviewProfile(key, params = {}, options = {}) {
1335
+ return async (client) => {
1336
+ const res = await client.rawRequest(
1337
+ withQuery2(`${BASE}/review-profiles/${encodeURIComponent(key)}`, {
1338
+ version: params.version === void 0 ? void 0 : String(params.version)
1339
+ }),
1340
+ { signal: options.signal }
1341
+ );
1342
+ return res.data;
1343
+ };
1344
+ }
1345
+ function reviewDraft(request, options = {}) {
1346
+ return async (client) => {
1347
+ const res = await client.rawRequest(`${BASE}/reviews`, {
1348
+ method: "POST",
1349
+ body: JSON.stringify(request),
1350
+ signal: options.signal
1351
+ });
1352
+ return res.data;
1353
+ };
1354
+ }
1355
+ function getReview(id, options = {}) {
1356
+ return async (client) => {
1357
+ const res = await client.rawRequest(`${BASE}/reviews/${encodeURIComponent(id)}`, {
1358
+ signal: options.signal
1359
+ });
1360
+ return res.data;
1361
+ };
1362
+ }
1363
+ function listReviews(params, options = {}) {
1364
+ return async (client) => {
1365
+ const res = await client.rawRequest(
1366
+ withQuery2(`${BASE}/reviews`, { collection: params.collection, itemId: params.itemId }),
1367
+ { signal: options.signal }
1368
+ );
1369
+ return res.data;
1370
+ };
1371
+ }
1372
+ function submitReviewFeedback(runId, request, options = {}) {
1373
+ return async (client) => {
1374
+ const res = await client.rawRequest(`${BASE}/reviews/${encodeURIComponent(runId)}/feedback`, {
1375
+ method: "POST",
1376
+ body: JSON.stringify(request),
1377
+ signal: options.signal
1378
+ });
1379
+ return res.data;
1380
+ };
1381
+ }
1382
+
1213
1383
  // src/rest/index.ts
1214
1384
  function search(query, params) {
1215
1385
  return async (client) => {
@@ -1776,6 +1946,7 @@ function jsonLdScript(item) {
1776
1946
  export {
1777
1947
  ACCESS_EXPORT_SCHEMA,
1778
1948
  AudienceClient,
1949
+ DECISION_ERROR_CODES,
1779
1950
  DEFAULT_IMPORT_SOURCE,
1780
1951
  LumiError,
1781
1952
  RealtimeClient,
@@ -1787,7 +1958,9 @@ export {
1787
1958
  createCdcPipeline,
1788
1959
  createCdcSubscription,
1789
1960
  createLumiClient,
1961
+ decide,
1790
1962
  decideAgentApproval,
1963
+ decisionErrorCode,
1791
1964
  deleteBookmark,
1792
1965
  deleteCdcPipeline,
1793
1966
  deleteCdcSubscription,
@@ -1800,6 +1973,8 @@ export {
1800
1973
  generateAgentApp,
1801
1974
  generateTypes,
1802
1975
  getEffectivePreset,
1976
+ getReview,
1977
+ getReviewProfile,
1803
1978
  graphql,
1804
1979
  importAccessManifest,
1805
1980
  jsonLdScript,
@@ -1813,6 +1988,8 @@ export {
1813
1988
  listCdcPipelines,
1814
1989
  listCdcSubscriptionDeliveries,
1815
1990
  listCdcSubscriptions,
1991
+ listReviewProfiles,
1992
+ listReviews,
1816
1993
  mediaUrl,
1817
1994
  publishAgentArtifact,
1818
1995
  readAgentMemoryContext,
@@ -1825,13 +2002,17 @@ export {
1825
2002
  readItems,
1826
2003
  replayCdcSubscription,
1827
2004
  retryAgentRun,
2005
+ reviewContentHash,
2006
+ reviewDraft,
1828
2007
  rollbackAgentArtifact,
1829
2008
  rollbackCdcDeployment,
1830
2009
  saveUserView,
1831
2010
  search,
1832
2011
  startCdcPipeline,
1833
2012
  stopCdcPipeline,
2013
+ submitReviewFeedback,
1834
2014
  toNextMetadata,
2015
+ toWebSocketBase,
1835
2016
  updateBookmark,
1836
2017
  updateCdcPipeline,
1837
2018
  updateCdcSubscription,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lumibase/sdk",
3
- "version": "1.0.0-rc.4",
3
+ "version": "1.0.1",
4
4
  "description": "LumiBase JS SDK (REST + WebSocket) + typegen core. Isomorphic ESM.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -22,9 +22,10 @@
22
22
  "access": "public"
23
23
  },
24
24
  "devDependencies": {
25
- "tsup": "^8.5.1",
25
+ "tsup": "^9.0.0",
26
26
  "typescript": "^5.6.2",
27
- "vitest": "^5.0.1"
27
+ "vitest": "^5.0.5",
28
+ "@lumibase/contracts": "1.0.1"
28
29
  },
29
30
  "files": [
30
31
  "dist"
@@ -47,7 +48,8 @@
47
48
  "scripts": {
48
49
  "build": "tsup src/index.ts --format cjs,esm --dts --clean",
49
50
  "test": "vitest run",
50
- "typecheck": "tsc --noEmit",
51
+ "typecheck": "tsc --noEmit && pnpm run typecheck:examples",
52
+ "typecheck:examples": "tsc -p tsconfig.examples.json",
51
53
  "clean": "rm -rf .turbo dist"
52
54
  },
53
55
  "module": "./dist/index.js"