@genex-ai/embed-sdk 0.30.1 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -235,6 +235,38 @@ approval window passes, `pending` with `error: 'wait_timeout'` when the SDK
235
235
  stopped waiting (the sheet may still be open), and `failed` with a server code.
236
236
  The successful result carries `grantId` and the full server `grant` view.
237
237
 
238
+ **One live budget per player per game, and the newest approval wins.** Genex
239
+ never runs two budgets of one game for one player (per payment door). If you
240
+ ask while one is already running, the Genex sheet tells the player before they
241
+ approve that the new budget replaces the running one (and what it has used);
242
+ approving it stops the old budget and starts the new one in one step. Calls
243
+ the old budget already started still finish and are charged to it; a game
244
+ still holding the old id is refused `grant_stopped`, and `getSpendGrant(oldId)`
245
+ reads `stopped` with `stopReason: 'replaced'`. So don't ask every session —
246
+ reuse the running budget first (SDK **0.31.0+**):
247
+
248
+ ```ts
249
+ import { getActiveSpendGrant } from '@genex-ai/embed-sdk';
250
+
251
+ // On boot, or after `grant_stopped`: the player's live budget in THIS game.
252
+ const running = await getActiveSpendGrant(); // RuntimeGrantView | null
253
+ if (running) grantId = running.id;
254
+ else grantId = (await requestSpendGrant(budgetRequest)).grantId; // from a click
255
+ ```
256
+
257
+ `getActiveSpendGrant()` (SDK **0.31.0+**) returns the same view as
258
+ `getSpendGrant(id)`, or `null` when the player has no live budget in this game.
259
+ "Live" means it can run calls now or once its reason clears (`active`,
260
+ `suspended_insufficient_funds`, `waiting_for_plan`); a stopped, expired or
261
+ used-up budget is `null`, like one that never existed. It is scoped by the
262
+ player's token to this player and this game, so it never finds another game's
263
+ budget or another player's. A guest rejects with `no_player_session`, and any
264
+ other refusal rejects with the server's code, like `getSpendGrant()`. It is a
265
+ read: it never asks the player anything, so a game may call it on boot with no
266
+ click behind it — and, since only `requestSpendGrant()` needs a click, the one
267
+ prompt a returning player sees is the one their running budget does not cover. The development lane (`@genex-ai/embed-sdk/development`) has
268
+ no budgets, so there is no counterpart there.
269
+
238
270
  `generate({ grantId })` runs one call under that budget. It opens **no window,
239
271
  posts no parent message and needs no user gesture**, so it works from a game
240
272
  loop or a timer. Every other guard is unchanged: the published game (or its
@@ -257,8 +289,8 @@ those at 0). Poll it on the
257
289
  cadence your HUD needs — never derive the remaining budget from your own count
258
290
  of calls, and never show a figure the server did not send. Store `grantId` the
259
291
  way you store a `generationId`; `getSpendGrant()` recovers the budget after a
260
- reload, and a budget whose status is no longer live simply needs a new
261
- approval. `stopSpendGrant(id)` releases it when your feature ends. Stopping is
292
+ reload, `getActiveSpendGrant()` finds it when the id is lost, and a budget
293
+ whose status is no longer live simply needs a new approval. `stopSpendGrant(id)` releases it when your feature ends. Stopping is
262
294
  prospective: calls already started finish and are charged. The player has the
263
295
  same lever on Genex, on every page, and theirs always outranks the game's.
264
296
 
@@ -285,7 +317,7 @@ the game should have believable copy for each:
285
317
  `credits_unverified` (verify the email on Genex), `generation_paused` (Genex
286
318
  paused paid generation; retry later),
287
319
  `waiting_for_plan` (a personal plan's own rate limit; it resumes by itself),
288
- `grant_price_unreasonable`, `grant_already_active`, `external_grant_active` and
320
+ `grant_price_unreasonable`, `external_grant_active` and
289
321
  `invalid_grant_limit`. `generationErrorMessage(code)` returns a player-facing
290
322
  sentence for every one of these and for every one-time code as well; show it, or
291
323
  write your own in-fiction line keyed off the same code. Never show the raw code,
@@ -262,7 +262,11 @@ async function request(path, body) {
262
262
  ...body === void 0 ? {} : { body: JSON.stringify(body) }
263
263
  });
264
264
  const result = await response.json().catch(() => ({}));
265
- if (!response.ok) throw new Error(typeof result.error === "string" ? result.error : "generation_unavailable");
265
+ if (!response.ok) {
266
+ const error = new Error(typeof result.error === "string" ? result.error : "generation_unavailable");
267
+ error.status = response.status;
268
+ throw error;
269
+ }
266
270
  return result;
267
271
  }
268
272
  function validEstimateCoins(value) {
@@ -473,7 +477,8 @@ function invalidGrantOptions(options) {
473
477
  function grantOutcome(view) {
474
478
  if (LIVE_GRANT_STATUSES.includes(view.status)) return { status: "active", grantId: view.id, grant: view };
475
479
  switch (view.status) {
476
- // The player closing the sheet, or stopping later, is a normal outcome.
480
+ // The player closing the sheet, or stopping later, is a normal outcome —
481
+ // whatever reason the server recorded for the stop.
477
482
  case "stopped":
478
483
  return { status: "canceled", grantId: view.id, grant: view };
479
484
  case "expired":
@@ -490,6 +495,16 @@ function getSpendGrant(grantId) {
490
495
  if (!isGrantId(grantId)) return Promise.reject(new Error("invalid_grant_id"));
491
496
  return request(`/grants/${encodeURIComponent(grantId)}`);
492
497
  }
498
+ async function getActiveSpendGrant() {
499
+ try {
500
+ const view = await request("/grants/current");
501
+ if (!isGrantId(view.id)) throw new Error("invalid_grant_response");
502
+ return view;
503
+ } catch (error) {
504
+ if (error.status === 404) return null;
505
+ throw error;
506
+ }
507
+ }
493
508
  function stopSpendGrant(grantId) {
494
509
  if (!isGrantId(grantId)) return Promise.reject(new Error("invalid_grant_id"));
495
510
  return request(`/grants/${encodeURIComponent(grantId)}/stop`, {});
@@ -917,7 +932,7 @@ var RETRY_FLAG = "genex:embed:retry";
917
932
  var POPOVER_DISMISSED_FLAG = "genex:guest:popover-dismissed";
918
933
  var LOCAL_AUTH_FLAG = "genex:embed:local-auth";
919
934
  var PLAYER_ID_KEY = "genex:player";
920
- var SDK_VERSION = "0.30.1";
935
+ var SDK_VERSION = "0.31.0";
921
936
  var config2 = null;
922
937
  var state = "pending";
923
938
  var user = null;
@@ -935,6 +950,7 @@ var redeeming = false;
935
950
  var requestingGuest = false;
936
951
  var identityEpoch = 0;
937
952
  var handshakeTimeoutMs = 1e4;
953
+ var standaloneWatchdogGraceMs = 2e3;
938
954
  var refreshDelayMs = 10 * 6e4;
939
955
  var refreshRetryMs = 6e4;
940
956
  var overlayTextDelayMs = 500;
@@ -1609,7 +1625,7 @@ function armStandaloneWatchdog() {
1609
1625
  handshakeTimer = setTimeout(() => {
1610
1626
  handshakeTimer = void 0;
1611
1627
  if (state === "pending") enterBlocked("no-identity");
1612
- }, handshakeTimeoutMs);
1628
+ }, handshakeTimeoutMs + standaloneWatchdogGraceMs);
1613
1629
  }
1614
1630
  var stashedTicketHash = null;
1615
1631
  function _stashTicketFromUrl() {
@@ -2269,6 +2285,7 @@ function __resetForTests(overrides) {
2269
2285
  hasPendingPlayerSave = false;
2270
2286
  pendingScores.clear();
2271
2287
  handshakeTimeoutMs = overrides?.handshakeTimeoutMs ?? 1e4;
2288
+ standaloneWatchdogGraceMs = overrides?.standaloneWatchdogGraceMs ?? 2e3;
2272
2289
  refreshDelayMs = overrides?.refreshDelayMs ?? 10 * 6e4;
2273
2290
  refreshRetryMs = overrides?.refreshRetryMs ?? 6e4;
2274
2291
  overlayTextDelayMs = overrides?.overlayTextDelayMs ?? 500;
@@ -2289,6 +2306,7 @@ export {
2289
2306
  requestWorkflow,
2290
2307
  resumeWorkflow,
2291
2308
  getSpendGrant,
2309
+ getActiveSpendGrant,
2292
2310
  stopSpendGrant,
2293
2311
  requestSpendGrant,
2294
2312
  generateStream,
@@ -1,4 +1,4 @@
1
- import { R as RuntimeJudgeQuestion, a as RuntimeWorkflowInput, b as RuntimeGenerationView } from './runtime-generation-sXuSFc3c.js';
1
+ import { R as RuntimeJudgeQuestion, a as RuntimeWorkflowInput, b as RuntimeGenerationView } from './runtime-generation-B3oFDmCp.js';
2
2
 
3
3
  /**
4
4
  * Server-only benchmarks spend the authenticated creator's OWN CREDITS
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { R as RuntimeJudgeQuestion, c as RuntimeJudgeAnswer, d as RuntimeJudgmentView, a as RuntimeWorkflowInput, e as RuntimeGenerationBilling, f as RuntimeGenerationFunding, g as RuntimeGrantView, b as RuntimeGenerationView, h as RuntimeGenerationModels, i as RuntimeWorkflowOfferings } from './runtime-generation-sXuSFc3c.js';
2
- export { j as RuntimeBillingPolicy, k as RuntimeCurrency, l as RuntimeExternalProvider, m as RuntimeGenerationStatus, n as RuntimeGenerationStreamEvent, o as RuntimeGrantJudgeTerms, p as RuntimeGrantStatus, q as RuntimeGrantTerms, r as RuntimeJudgeCriterion } from './runtime-generation-sXuSFc3c.js';
1
+ import { R as RuntimeJudgeQuestion, c as RuntimeJudgeAnswer, d as RuntimeJudgmentView, a as RuntimeWorkflowInput, e as RuntimeGenerationBilling, f as RuntimeGenerationFunding, g as RuntimeGrantView, b as RuntimeGenerationView, h as RuntimeGenerationModels, i as RuntimeWorkflowOfferings } from './runtime-generation-B3oFDmCp.js';
2
+ export { j as RuntimeBillingPolicy, k as RuntimeCurrency, l as RuntimeExternalProvider, m as RuntimeGenerationStatus, n as RuntimeGenerationStreamEvent, o as RuntimeGrantJudgeTerms, p as RuntimeGrantStatus, q as RuntimeGrantTerms, r as RuntimeJudgeCriterion } from './runtime-generation-B3oFDmCp.js';
3
3
 
4
4
  /** A thing the game sells. Resolved server-side; the game never sets a price. */
5
5
  interface ShopItem {
@@ -290,10 +290,25 @@ interface SpendGrantResult {
290
290
  grantId?: string;
291
291
  /** The authoritative server view: limit, spend, counts and the frozen terms. */
292
292
  grant?: RuntimeGrantView;
293
+ /** Why a `failed` result failed, as a code for generationErrorMessage(). */
293
294
  error?: string;
294
295
  }
295
296
  /** Read a budget: limit, spend, calls and status. Scoped to this player AND this game. */
296
297
  declare function getSpendGrant(grantId: string): Promise<RuntimeGrantView>;
298
+ /**
299
+ * This player's live budget in this game, or `null` when there is none (0.31.0).
300
+ *
301
+ * Genex keeps ONE live budget per player per game, and a newer approval
302
+ * replaces it — so a game that already has one running (after a reload, in a
303
+ * new session, or after losing the id requestSpendGrant() gave it) reuses it
304
+ * here instead of asking the player to approve another. "Live" means it can
305
+ * run calls now or once its reason clears (an empty wallet, the player's own
306
+ * plan asking to wait); a stopped, expired or used-up budget is not returned.
307
+ * Scoped by the player's token to this player AND this game. Rejects like the
308
+ * other budget helpers (`no_player_session` for a guest, the server's code
309
+ * otherwise); only "none" is `null`.
310
+ */
311
+ declare function getActiveSpendGrant(): Promise<RuntimeGrantView | null>;
297
312
  /**
298
313
  * Release a budget when the feature that needed it ends. Stopping is
299
314
  * PROSPECTIVE: calls already started finish and are charged. The player has the
@@ -309,6 +324,11 @@ declare function stopSpendGrant(grantId: string): Promise<RuntimeGrantView>;
309
324
  * Resolves `active` once the budget can serve calls; pass its `grantId` to
310
325
  * generate() from then on. A player who closes the sheet resolves `canceled`.
311
326
  * Store the id: getSpendGrant(id) recovers the budget after a reload.
327
+ *
328
+ * Genex keeps one live budget per player per game, and the newest approval
329
+ * REPLACES the running one (the sheet tells the player so before they
330
+ * approve). So ask getActiveSpendGrant() first: a game that reuses the running
331
+ * budget does not ask the player again every session.
312
332
  */
313
333
  declare function requestSpendGrant(options: SpendGrantOptions): Promise<SpendGrantResult>;
314
334
  interface GenerateStreamOptions extends GenerateOptions {
@@ -779,6 +799,7 @@ declare function listEvents<T = unknown>(stream: string, opts?: {
779
799
  declare function _stashTicketFromUrl(): void;
780
800
  declare function __resetForTests(overrides?: {
781
801
  handshakeTimeoutMs?: number;
802
+ standaloneWatchdogGraceMs?: number;
782
803
  refreshDelayMs?: number;
783
804
  refreshRetryMs?: number;
784
805
  overlayTextDelayMs?: number;
@@ -786,4 +807,4 @@ declare function __resetForTests(overrides?: {
786
807
  heartbeatIntervalMs?: number;
787
808
  }): void;
788
809
 
789
- export { type AppendEventResult, type AuthState, type DeleteSharedResult, type EmbedConfig, type EmbedEvent, type EmbedUser, type Entitlement, type GenerateOptions, type GenerateStreamOptions, type JudgeOptions, type JudgeResult, type Leaderboard, type LeaderboardEntry, type PlayerStateResult, type PurchaseResult, type PurchaseStatus, type PutSharedResult, type RequestWorkflowOptions, RuntimeGenerationBilling, RuntimeGenerationFunding, RuntimeGenerationModels, type RuntimeGenerationResult, RuntimeGenerationView, RuntimeGrantView, RuntimeJudgeAnswer, RuntimeJudgeQuestion, RuntimeJudgmentView, type RuntimeWorkflowAuthorization, RuntimeWorkflowInput, RuntimeWorkflowOfferings, type SaveStateResult, type SharedEventPage, type SharedEventRecord, type SharedObject, type SharedObjectInfo, type SharedPage, type ShopItem, type SpendGrantDisclosure, type SpendGrantOptions, type SpendGrantResult, type SubmitScoreResult, type WorldStateResult, __resetForTests, _stashTicketFromUrl, appendEvent, buy, consumeEntitlement, deleteShared, generate, generateStream, generationErrorMessage, getAuthState, getColyseusAuth, getColyseusUrls, getEmbedToken, getEntitlements, getGeneration, getGenerationModels, getLeaderboard, getShared, getShop, getSpendGrant, getUser, getWorkflowOfferings, initEmbed, isEmbedded, judge, listEvents, listShared, loadPlayerState, loadWorldState, on, putShared, requestSpendGrant, requestWorkflow, resumeWorkflow, savePlayerState, saveWorldState, stopSpendGrant, submitScore, waitForAuth, waitForGeneration, waitForPlayer };
810
+ export { type AppendEventResult, type AuthState, type DeleteSharedResult, type EmbedConfig, type EmbedEvent, type EmbedUser, type Entitlement, type GenerateOptions, type GenerateStreamOptions, type JudgeOptions, type JudgeResult, type Leaderboard, type LeaderboardEntry, type PlayerStateResult, type PurchaseResult, type PurchaseStatus, type PutSharedResult, type RequestWorkflowOptions, RuntimeGenerationBilling, RuntimeGenerationFunding, RuntimeGenerationModels, type RuntimeGenerationResult, RuntimeGenerationView, RuntimeGrantView, RuntimeJudgeAnswer, RuntimeJudgeQuestion, RuntimeJudgmentView, type RuntimeWorkflowAuthorization, RuntimeWorkflowInput, RuntimeWorkflowOfferings, type SaveStateResult, type SharedEventPage, type SharedEventRecord, type SharedObject, type SharedObjectInfo, type SharedPage, type ShopItem, type SpendGrantDisclosure, type SpendGrantOptions, type SpendGrantResult, type SubmitScoreResult, type WorldStateResult, __resetForTests, _stashTicketFromUrl, appendEvent, buy, consumeEntitlement, deleteShared, generate, generateStream, generationErrorMessage, getActiveSpendGrant, getAuthState, getColyseusAuth, getColyseusUrls, getEmbedToken, getEntitlements, getGeneration, getGenerationModels, getLeaderboard, getShared, getShop, getSpendGrant, getUser, getWorkflowOfferings, initEmbed, isEmbedded, judge, listEvents, listShared, loadPlayerState, loadWorldState, on, putShared, requestSpendGrant, requestWorkflow, resumeWorkflow, savePlayerState, saveWorldState, stopSpendGrant, submitScore, waitForAuth, waitForGeneration, waitForPlayer };
package/dist/index.js CHANGED
@@ -8,6 +8,7 @@ import {
8
8
  generate,
9
9
  generateStream,
10
10
  generationErrorMessage,
11
+ getActiveSpendGrant,
11
12
  getAuthState,
12
13
  getColyseusAuth,
13
14
  getColyseusUrls,
@@ -40,7 +41,7 @@ import {
40
41
  waitForAuth,
41
42
  waitForGeneration,
42
43
  waitForPlayer
43
- } from "./chunk-FBJN7DGJ.js";
44
+ } from "./chunk-QNZZIJGP.js";
44
45
  import "./chunk-MJPLBT3T.js";
45
46
  export {
46
47
  __resetForTests,
@@ -52,6 +53,7 @@ export {
52
53
  generate,
53
54
  generateStream,
54
55
  generationErrorMessage,
56
+ getActiveSpendGrant,
55
57
  getAuthState,
56
58
  getColyseusAuth,
57
59
  getColyseusUrls,
@@ -414,6 +414,10 @@ interface RuntimeGrantView {
414
414
  expiresAt: string;
415
415
  lastCallAt?: string;
416
416
  stopRequestedAt?: string;
417
+ /** Why it stopped: `player_stopped`, `game_stopped`, `operator_stopped`,
418
+ * `session_revoked`, … — and `replaced` when the player approved a newer
419
+ * budget for the same game and funding, which the game finds with
420
+ * `getActiveSpendGrant()`. */
417
421
  stopReason?: string;
418
422
  createdAt: string;
419
423
  /** When a `waiting_for_plan` budget may admit again. The player's OWN plan
@@ -421,6 +425,10 @@ interface RuntimeGrantView {
421
425
  * only while the status is `waiting_for_plan`. */
422
426
  resumeAt?: string;
423
427
  watcherOnline?: boolean;
428
+ /** Only on the PLAYER's own Genex read of a request still waiting on them:
429
+ * the live budgets of this game that approving it would replace, one per
430
+ * funding door at most. Never sent to a game. */
431
+ replaces?: RuntimeGrantView[];
424
432
  }
425
433
  interface RuntimeGenerationModels {
426
434
  enabled: true;
package/dist/sentry.js CHANGED
@@ -2,7 +2,7 @@ import {
2
2
  _stashTicketFromUrl,
3
3
  getUser,
4
4
  on
5
- } from "./chunk-FBJN7DGJ.js";
5
+ } from "./chunk-QNZZIJGP.js";
6
6
  import "./chunk-MJPLBT3T.js";
7
7
 
8
8
  // src/sentry.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@genex-ai/embed-sdk",
3
- "version": "0.30.1",
3
+ "version": "0.31.0",
4
4
  "description": "Player identity + durable game state for genex games \u2014 signed-in or guest play, per-player save slots, shared world state, soft-trust leaderboards, and shared collections and event streams.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",