@genex-ai/embed-sdk 0.35.0 → 0.37.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.
@@ -15,24 +15,29 @@ import {
15
15
  SAVE_MAX_BYTES,
16
16
  createBridgeId,
17
17
  encodeBridgeMessage,
18
+ foldRuntimeConversation,
18
19
  hasNativeMarker,
19
20
  isGenerationId,
20
21
  isGenerationTerminal,
22
+ isLoopbackHttpOrigin,
21
23
  isPlatformUrl,
22
24
  isSaveName,
23
25
  parseGenerationStreamEvent,
24
26
  parsePlatformRequest,
25
27
  parsePlatformResult,
28
+ practiceOrigin,
26
29
  readBridgeNativeCommand,
27
30
  readNativeEntry,
28
31
  readPlatformCaps,
32
+ readPracticeKey,
33
+ runtimeConversationError,
29
34
  sanitizeEntryHash,
30
35
  sanitizeEntryReferrer,
31
36
  sanitizePassthroughQuery,
32
37
  savableMime,
33
38
  stripNativeEntry,
34
39
  stripReturnMarker
35
- } from "./chunk-QBCWKMVQ.js";
40
+ } from "./chunk-WQJM5MJL.js";
36
41
 
37
42
  // src/platform.ts
38
43
  var ctx = null;
@@ -973,20 +978,43 @@ function partialStringField(text, name) {
973
978
  return void 0;
974
979
  }
975
980
 
981
+ // src/practice.ts
982
+ function _readPracticeTarget() {
983
+ if (typeof window === "undefined") return null;
984
+ try {
985
+ const location = window.location;
986
+ if (!location || !isLoopbackHttpOrigin(location.origin)) return null;
987
+ const key = readPracticeKey(location.search);
988
+ return key ? { origin: practiceOrigin(key.port), token: key.token } : null;
989
+ } catch {
990
+ return null;
991
+ }
992
+ }
993
+
976
994
  // src/generation.ts
977
995
  var config = null;
996
+ var practiceTarget = null;
978
997
  function _initGeneration(value) {
979
998
  config = value;
999
+ messagesFeature = void 0;
1000
+ practiceTarget = _readPracticeTarget();
980
1001
  }
981
1002
  function must2() {
982
1003
  if (!config) throw new Error("genex generation: call initEmbed() first");
983
1004
  return config;
984
1005
  }
985
- async function request(path, body) {
1006
+ function practice() {
986
1007
  const c = must2();
987
- const token = c.getToken();
1008
+ return c.isLocalTest() && !c.isEmbedded() && !c.isNative() ? practiceTarget : null;
1009
+ }
1010
+ function endpoint() {
1011
+ const target = practice();
1012
+ return target ? { base: target.origin, token: target.token } : { base: must2().apiUrl, token: must2().getToken() };
1013
+ }
1014
+ async function request(path, body) {
1015
+ const { base, token } = endpoint();
988
1016
  if (!token) throw new Error("no_player_session");
989
- const response = await fetch(`${c.apiUrl}/api/runtime${path}`, {
1017
+ const response = await fetch(`${base}/api/runtime${path}`, {
990
1018
  method: body === void 0 ? "GET" : "POST",
991
1019
  credentials: "omit",
992
1020
  cache: "no-store",
@@ -1019,6 +1047,37 @@ var GENERATION_WAIT_MS = 12e5;
1019
1047
  function getGenerationModels() {
1020
1048
  return request("/models");
1021
1049
  }
1050
+ var RICH_FIELDS = ["system", "messages", "temperature", "topP", "stop", "seed", "reasoningEffort", "cacheSystem"];
1051
+ var FEATURE_RECHECK_MS = 3e5;
1052
+ var messagesFeature;
1053
+ function standTakesMessages() {
1054
+ const known = messagesFeature;
1055
+ if (known && (known.yes || Date.now() - known.at < FEATURE_RECHECK_MS)) return known.answer;
1056
+ const asked = { at: Date.now(), yes: false, answer: Promise.resolve(false) };
1057
+ asked.answer = getGenerationModels().then(
1058
+ (models) => asked.yes = models.features?.messages === true,
1059
+ () => {
1060
+ if (messagesFeature === asked) messagesFeature = void 0;
1061
+ return false;
1062
+ }
1063
+ );
1064
+ messagesFeature = asked;
1065
+ return asked.answer;
1066
+ }
1067
+ function hasRichFields(body) {
1068
+ return RICH_FIELDS.some((key) => body[key] !== void 0);
1069
+ }
1070
+ function foldGenerationRequest(request2) {
1071
+ return foldRuntimeConversation(request2);
1072
+ }
1073
+ async function wireBody(body) {
1074
+ if (!hasRichFields(body) || await standTakesMessages()) return body;
1075
+ const { system, messages, temperature: _temperature, topP: _topP, stop: _stop, seed: _seed, reasoningEffort: _effort, cacheSystem: _cache, ...rest } = body;
1076
+ return { ...rest, prompt: foldRuntimeConversation({ system, messages, prompt: body.prompt }) };
1077
+ }
1078
+ function invalidConversation(options) {
1079
+ return hasRichFields(options) ? runtimeConversationError(options) : void 0;
1080
+ }
1022
1081
  function isWorkflowIdentifier(value) {
1023
1082
  return typeof value === "string" && /^[A-Za-z0-9_.:-]{1,120}$/.test(value) && value !== "." && value !== "..";
1024
1083
  }
@@ -1041,7 +1100,8 @@ function outcome(view) {
1041
1100
  source: view.source,
1042
1101
  ...view.modelProvenance ? { modelProvenance: view.modelProvenance } : {}
1043
1102
  } : {},
1044
- ...view.error ? { error: view.error } : {}
1103
+ ...view.error ? { error: view.error } : {},
1104
+ ...view.contentBlocked ? { contentBlocked: view.contentBlocked } : {}
1045
1105
  };
1046
1106
  }
1047
1107
  function billingReceipt(view) {
@@ -1095,6 +1155,8 @@ async function generate(options) {
1095
1155
  const ceiling = ceilingField(options);
1096
1156
  if ("error" in ceiling) return { status: "failed", error: ceiling.error };
1097
1157
  if (!validMaxOutputTokens(options.maxOutputTokens)) return { status: "failed", error: "invalid_max_output_tokens" };
1158
+ const malformed = invalidConversation(options);
1159
+ if (malformed) return { status: "failed", error: malformed };
1098
1160
  const { timeoutMs, idempotencyKey, grantId, maxCredits: _credits, estimateCoins: _coins, ...rest } = options;
1099
1161
  const input = { ...rest, ...ceiling.field };
1100
1162
  if (grantId !== void 0) return generateUnderGrant(grantId, input, idempotencyKey, timeoutMs ?? GENERATION_WAIT_MS);
@@ -1124,7 +1186,7 @@ async function resumeWorkflow(generationId, options = {}) {
1124
1186
  }
1125
1187
  function approvalGuards() {
1126
1188
  const c = must2();
1127
- if (c.isLocalTest()) return { status: "failed", error: "local_test_unsupported" };
1189
+ if (c.isLocalTest()) return practice() ? { parentOrigin: null, practice: true } : { status: "failed", error: "local_test_unsupported" };
1128
1190
  if (c.isNative()) return { status: "failed", error: "native_unsupported" };
1129
1191
  if (typeof window === "undefined") return { status: "failed", error: "no_window" };
1130
1192
  if (!c.getToken()) return { status: "failed", error: "no_player_session" };
@@ -1137,6 +1199,7 @@ function approvalGuards() {
1137
1199
  function reserveApprovalSurface(placeholder) {
1138
1200
  const guarded = approvalGuards();
1139
1201
  if ("status" in guarded) return guarded;
1202
+ if (guarded.practice) return { popup: null, parentOrigin: null };
1140
1203
  const c = must2();
1141
1204
  if (c.isEmbedded()) return { popup: null, parentOrigin: guarded.parentOrigin };
1142
1205
  let dashboard;
@@ -1159,7 +1222,7 @@ async function startGeneration(path, body, timeoutMs, readOutcome, workflow, res
1159
1222
  if ("status" in surface) return surface;
1160
1223
  const { popup, dashboard, parentOrigin: parentOrigin2 } = surface;
1161
1224
  try {
1162
- const view = resumeId ? await getGeneration(resumeId) : await request(path, { ...body, idempotencyKey: body.idempotencyKey ?? crypto.randomUUID() });
1225
+ const view = resumeId ? await getGeneration(resumeId) : await request(path, await wireBody({ ...body, idempotencyKey: body.idempotencyKey ?? crypto.randomUUID() }));
1163
1226
  if (resumeId && (view.id !== resumeId || view.kind !== "workflow")) throw new Error("invalid_generation_response");
1164
1227
  if (!isGenerationId(view.id) || workflow && (view.kind !== "workflow" || view.workflow?.id !== workflow.workflowId || view.workflow.offeringId !== workflow.offeringId)) {
1165
1228
  throw new Error("invalid_generation_response");
@@ -1204,6 +1267,7 @@ function invalidGrantOptions(options) {
1204
1267
  if (options.maxCallsPerMinute !== void 0 && !validCount(options.maxCallsPerMinute, 1, 120)) return "invalid_grant_terms";
1205
1268
  if (options.maxPendingExternal !== void 0 && !validCount(options.maxPendingExternal, 1, 8)) return "invalid_grant_terms";
1206
1269
  if (options.allowExternal !== void 0 && typeof options.allowExternal !== "boolean") return "invalid_grant_terms";
1270
+ if (options.shareWithRooms !== void 0 && typeof options.shareWithRooms !== "boolean") return "invalid_grant_terms";
1207
1271
  if (options.idempotencyKey !== void 0 && (typeof options.idempotencyKey !== "string" || options.idempotencyKey.length < 8 || options.idempotencyKey.length > 100)) return "invalid_idempotency_key";
1208
1272
  return void 0;
1209
1273
  }
@@ -1242,6 +1306,37 @@ function stopSpendGrant(grantId) {
1242
1306
  if (!isGrantId(grantId)) return Promise.reject(new Error("invalid_grant_id"));
1243
1307
  return request(`/grants/${encodeURIComponent(grantId)}/stop`, {});
1244
1308
  }
1309
+ async function roomCallsServed() {
1310
+ const models = await getGenerationModels();
1311
+ return models.features?.roomCalls === true;
1312
+ }
1313
+ function isRoomId(value) {
1314
+ return typeof value === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value);
1315
+ }
1316
+ function roomDoorError(error) {
1317
+ const status = error.status;
1318
+ const code = error instanceof Error ? error.message : "";
1319
+ if (status === 404 && (code === "generation_unavailable" || code === "not_found")) return new Error("room_calls_unavailable");
1320
+ return error instanceof Error ? error : new Error("generation_unavailable");
1321
+ }
1322
+ async function lendSpendGrantToRoom(grantId, roomId) {
1323
+ if (!isGrantId(grantId)) throw new Error("invalid_grant_id");
1324
+ if (!isRoomId(roomId)) throw new Error("invalid_room_id");
1325
+ try {
1326
+ return await request(`/grants/${encodeURIComponent(grantId)}/rooms`, { roomId });
1327
+ } catch (error) {
1328
+ throw roomDoorError(error);
1329
+ }
1330
+ }
1331
+ async function returnSpendGrantFromRoom(grantId, roomId) {
1332
+ if (!isGrantId(grantId)) throw new Error("invalid_grant_id");
1333
+ if (!isRoomId(roomId)) throw new Error("invalid_room_id");
1334
+ try {
1335
+ return await request(`/grants/${encodeURIComponent(grantId)}/rooms/${encodeURIComponent(roomId)}/end`, {});
1336
+ } catch (error) {
1337
+ throw roomDoorError(error);
1338
+ }
1339
+ }
1245
1340
  async function pollGrant(grantId, timeoutMs, popup) {
1246
1341
  const deadline = Date.now() + timeoutMs;
1247
1342
  while (Date.now() < deadline) {
@@ -1261,12 +1356,17 @@ async function pollGrant(grantId, timeoutMs, popup) {
1261
1356
  return { status: "pending", grantId, error: "wait_timeout" };
1262
1357
  }
1263
1358
  async function requestSpendGrant(options) {
1359
+ if (options.sponsored === true) return requestSponsoredGrant(options);
1264
1360
  const invalid = invalidGrantOptions(options);
1265
1361
  if (invalid) return { status: "failed", error: invalid };
1266
1362
  const surface = reserveApprovalSurface("/play/grant");
1267
1363
  if ("status" in surface) return surface;
1268
1364
  const { popup, dashboard, parentOrigin: parentOrigin2 } = surface;
1269
1365
  try {
1366
+ if (options.shareWithRooms === true && !await roomCallsServed()) {
1367
+ popup?.close();
1368
+ return { status: "failed", error: "room_calls_unavailable" };
1369
+ }
1270
1370
  const estimate = options.perCallEstimateCredits ?? options.perCallEstimateCoins;
1271
1371
  const view = await request("/grants", {
1272
1372
  idempotencyKey: options.idempotencyKey ?? crypto.randomUUID(),
@@ -1282,7 +1382,8 @@ async function requestSpendGrant(options) {
1282
1382
  ...options.maxCallsPerMinute !== void 0 ? { maxCallsPerMinute: options.maxCallsPerMinute } : {},
1283
1383
  ...options.maxPendingExternal !== void 0 ? { maxPendingExternal: options.maxPendingExternal } : {},
1284
1384
  ...options.allowExternal !== void 0 ? { allowExternal: options.allowExternal } : {},
1285
- ...options.judge !== void 0 ? { judge: { enabled: options.judge.enabled, estimatedCallsPerPeriod: options.judge.estimatedCallsPerPeriod } } : {}
1385
+ ...options.judge !== void 0 ? { judge: { enabled: options.judge.enabled, estimatedCallsPerPeriod: options.judge.estimatedCallsPerPeriod } } : {},
1386
+ ...options.shareWithRooms === true ? { shareWithRooms: true } : {}
1286
1387
  });
1287
1388
  if (!isGrantId(view.id)) throw new Error("invalid_grant_response");
1288
1389
  const settled2 = grantOutcome(view);
@@ -1302,6 +1403,56 @@ async function requestSpendGrant(options) {
1302
1403
  return { status: "failed", error: error instanceof Error ? error.message : "grant_unavailable" };
1303
1404
  }
1304
1405
  }
1406
+ var FEATURES_TTL_MS = 3e5;
1407
+ var knownFeatures;
1408
+ function runtimeFeatures() {
1409
+ const apiUrl = must2().apiUrl;
1410
+ if (!knownFeatures || knownFeatures.apiUrl !== apiUrl || Date.now() - knownFeatures.at > FEATURES_TTL_MS) {
1411
+ const value = getGenerationModels().then((models) => models.features ?? {}, () => null);
1412
+ const entry = { at: Date.now(), apiUrl, value };
1413
+ knownFeatures = entry;
1414
+ void value.then((read) => {
1415
+ if (read === null && knownFeatures === entry) knownFeatures = void 0;
1416
+ });
1417
+ }
1418
+ return knownFeatures.value;
1419
+ }
1420
+ function guestToken(token) {
1421
+ try {
1422
+ const payload = token.split(".")[1];
1423
+ if (!payload) return false;
1424
+ return JSON.parse(atob(payload.replace(/-/g, "+").replace(/_/g, "/"))).guest === true;
1425
+ } catch {
1426
+ return false;
1427
+ }
1428
+ }
1429
+ var unavailable = (error) => ({ status: "unavailable", error });
1430
+ async function requestSponsoredGrant(options) {
1431
+ const judge2 = options.judge;
1432
+ if (judge2 !== void 0 && (typeof judge2 !== "object" || judge2 === null || typeof judge2.enabled !== "boolean")) return { status: "failed", error: "invalid_judge_terms" };
1433
+ if (!Array.isArray(options.models) || options.models.length < (judge2?.enabled ? 0 : 1) || options.models.length > 8 || options.models.some((id) => typeof id !== "string" || !id || id.length > 150) || new Set(options.models).size !== options.models.length) return { status: "failed", error: "invalid_models" };
1434
+ const max = options.perCallMaxCredits ?? options.perCallMaxCoins;
1435
+ if (!validCount(max, 1, 1e6)) return { status: "failed", error: "invalid_declared_price" };
1436
+ if (options.maxCallsPerMinute !== void 0 && !validCount(options.maxCallsPerMinute, 1, 120)) return { status: "failed", error: "invalid_grant_terms" };
1437
+ const guarded = approvalGuards();
1438
+ if ("status" in guarded) return unavailable(guarded.error);
1439
+ const features = await runtimeFeatures();
1440
+ if (!features?.sponsor) return unavailable("sponsor_not_available");
1441
+ if (!features.sponsorGuests && guestToken(must2().getToken() ?? "")) return unavailable("sponsor_sign_in_required");
1442
+ try {
1443
+ const view = await request("/sponsor/grants", {
1444
+ models: options.models,
1445
+ perCallMaxCredits: max,
1446
+ ...judge2?.enabled ? { judge: true } : {},
1447
+ ...options.maxCallsPerMinute !== void 0 ? { maxCallsPerMinute: options.maxCallsPerMinute } : {}
1448
+ });
1449
+ if (!isGrantId(view.id) || view.sponsored !== true || !LIVE_GRANT_STATUSES.includes(view.status)) return unavailable("sponsor_not_available");
1450
+ return { status: "active", grantId: view.id, grant: view };
1451
+ } catch (error) {
1452
+ const code = error instanceof Error ? error.message : "";
1453
+ return unavailable(/^[a-z][a-z0-9_]{2,63}$/.test(code) && code !== "not_found" && code !== "generation_unavailable" ? code : "sponsor_not_available");
1454
+ }
1455
+ }
1305
1456
  async function generateUnderGrant(grantId, input, idempotencyKey, timeoutMs) {
1306
1457
  if (!isGrantId(grantId)) return { status: "failed", error: "invalid_grant_id" };
1307
1458
  const guarded = approvalGuards();
@@ -1310,7 +1461,7 @@ async function generateUnderGrant(grantId, input, idempotencyKey, timeoutMs) {
1310
1461
  try {
1311
1462
  const view = await request(
1312
1463
  `/grants/${encodeURIComponent(grantId)}/generations`,
1313
- { ...body, idempotencyKey: idempotencyKey ?? crypto.randomUUID() }
1464
+ await wireBody({ ...body, idempotencyKey: idempotencyKey ?? crypto.randomUUID() })
1314
1465
  );
1315
1466
  if (!isGenerationId(view.id) || view.grantId !== grantId) throw new Error("invalid_generation_response");
1316
1467
  const result = outcome(view);
@@ -1324,13 +1475,14 @@ async function generateStream(options) {
1324
1475
  const ceiling = ceilingField(options);
1325
1476
  if ("error" in ceiling) return { status: "failed", error: ceiling.error };
1326
1477
  if (!validMaxOutputTokens(options.maxOutputTokens)) return { status: "failed", error: "invalid_max_output_tokens" };
1478
+ const malformed = invalidConversation(options);
1479
+ if (malformed) return { status: "failed", error: malformed };
1327
1480
  const { timeoutMs, idempotencyKey, grantId, onDelta, onPartialField, signal, allowExternal: _unused, maxCredits: _credits, estimateCoins: _coins, ...rest } = options;
1328
1481
  const body = { ...rest, ...ceiling.field };
1329
1482
  if (grantId === void 0 || grantId === null) return { status: "failed", error: "stream_requires_grant" };
1330
1483
  if (!isGrantId(grantId)) return { status: "failed", error: "invalid_grant_id" };
1331
1484
  const guarded = approvalGuards();
1332
1485
  if ("status" in guarded) return guarded;
1333
- const c = must2();
1334
1486
  const field = body.outputFormat === "json" && onPartialField ? firstStringProperty(body.schema) : void 0;
1335
1487
  let generationId;
1336
1488
  let soFar = "";
@@ -1364,14 +1516,14 @@ async function generateStream(options) {
1364
1516
  };
1365
1517
  const aborted = () => ({ status: "pending", ...generationId ? { generationId } : {}, error: "stream_aborted" });
1366
1518
  try {
1367
- const token = c.getToken();
1519
+ const { base, token } = endpoint();
1368
1520
  if (!token) return { status: "failed", error: "no_player_session" };
1369
- const response = await fetch(`${c.apiUrl}/api/runtime/grants/${encodeURIComponent(grantId)}/generations/stream`, {
1521
+ const response = await fetch(`${base}/api/runtime/grants/${encodeURIComponent(grantId)}/generations/stream`, {
1370
1522
  method: "POST",
1371
1523
  credentials: "omit",
1372
1524
  cache: "no-store",
1373
1525
  headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "text/event-stream" },
1374
- body: JSON.stringify({ ...body, idempotencyKey: idempotencyKey ?? crypto.randomUUID() }),
1526
+ body: JSON.stringify(await wireBody({ ...body, idempotencyKey: idempotencyKey ?? crypto.randomUUID() })),
1375
1527
  ...signal ? { signal } : {}
1376
1528
  });
1377
1529
  if (!response.ok) {
@@ -1465,7 +1617,8 @@ async function judge(options) {
1465
1617
  generationId: view.generationId,
1466
1618
  billing: view.billing,
1467
1619
  ...view.answers ? { answers: view.answers } : {},
1468
- ...view.error ? { error: view.error } : {}
1620
+ ...view.error ? { error: view.error } : {},
1621
+ ...view.source ? { source: view.source } : {}
1469
1622
  };
1470
1623
  } catch (error) {
1471
1624
  return { status: "failed", error: error instanceof Error ? error.message : "judge_unavailable" };
@@ -1511,10 +1664,38 @@ function generationErrorMessage(code) {
1511
1664
  return "Requests are coming too quickly for this budget. Wait a moment and try again.";
1512
1665
  case "grant_already_active":
1513
1666
  return "A budget is already running here. Stop it on Genex before setting up another.";
1667
+ // --- lending a budget to a multiplayer room -------------------------------
1668
+ case "room_calls_unavailable":
1669
+ return "Shared AI in multiplayer rooms isn\u2019t available here yet.";
1670
+ case "grant_not_shareable":
1671
+ return "This budget wasn\u2019t approved for the game\u2019s multiplayer server. Set up a new one that says so.";
1672
+ case "room_not_found":
1673
+ return "That multiplayer room isn\u2019t running any more.";
1674
+ case "room_funding_unsupported":
1675
+ return "A budget on your own Claude or ChatGPT plan can\u2019t be used by the game\u2019s multiplayer server. Use one paid from Genex credits.";
1676
+ case "lend_not_found":
1677
+ return "This budget isn\u2019t lent to that room.";
1514
1678
  case "external_grant_active":
1515
1679
  return "A budget on your own plan is already running. Stop it on Genex before setting up another.";
1516
1680
  case "invalid_grant_limit":
1517
1681
  return "That limit is outside the range Genex offers. Choose one on the slider.";
1682
+ // --- a budget the game's creator pays for --------------------------------
1683
+ case "sponsor_not_available":
1684
+ case "sponsor_terms_mismatch":
1685
+ return "This game isn\u2019t covering model use right now.";
1686
+ case "sponsor_exhausted":
1687
+ case "sponsor_stopped":
1688
+ case "sponsor_expired":
1689
+ return "What this game\u2019s creator set aside for model use has run out or ended. Nothing was charged to you.";
1690
+ case "sponsor_player_limit_reached":
1691
+ case "sponsor_address_limit_reached":
1692
+ return "You\u2019ve used what this game\u2019s creator covers for today. It starts again tomorrow.";
1693
+ case "sponsor_rate_limited":
1694
+ return "Requests are coming too quickly right now. Wait a moment and try again.";
1695
+ case "sponsor_sign_in_required":
1696
+ return "Sign in to Genex to use what this game\u2019s creator covers.";
1697
+ case "sponsor_email_unverified":
1698
+ return "Verify your email on Genex to use what this game\u2019s creator covers.";
1518
1699
  // --- the judge ------------------------------------------------------------
1519
1700
  case "judge_requires_grant":
1520
1701
  return "This game\u2019s quick checks run under a budget you approve. Set one up to keep going.";
@@ -1619,6 +1800,8 @@ function generationErrorMessage(code) {
1619
1800
  case "invalid_request":
1620
1801
  case "invalid_schema":
1621
1802
  case "invalid_max_output_tokens":
1803
+ case "invalid_messages":
1804
+ case "unsupported_parameter":
1622
1805
  return "This request wasn\u2019t something Genex could accept.";
1623
1806
  case "generation_limit":
1624
1807
  return "As many requests are running as Genex allows at once. Wait for one to finish.";
@@ -1632,6 +1815,11 @@ function generationErrorMessage(code) {
1632
1815
  case "validation_failed":
1633
1816
  case "invalid_provider_response":
1634
1817
  return "The answer didn\u2019t match what this game asked for.";
1818
+ // One sentence for both sides (`contentBlocked` says which): a request
1819
+ // refused before the model ran is not charged, a withheld answer is, and
1820
+ // the Genex receipt is what says so — never this line.
1821
+ case "content_blocked":
1822
+ return "That isn\u2019t allowed here, so nothing was shown. Try saying it another way.";
1635
1823
  // TWO DIFFERENT ENDINGS, and the difference is money. A budget that was
1636
1824
  // stopped, expired or revoked cancels what it admitted but never
1637
1825
  // dispatched, at zero cost — that is the one case where "before it ran" is
@@ -1668,7 +1856,7 @@ var LOCAL_AUTH_FLAG = "genex:embed:local-auth";
1668
1856
  var ENTRY_REFERRER_MEMO = "genex:embed:entry-referrer";
1669
1857
  var ENTRY_REFERRER_NONE = "none";
1670
1858
  var PLAYER_ID_KEY = "genex:player";
1671
- var SDK_VERSION = "0.35.0";
1859
+ var SDK_VERSION = "0.37.0";
1672
1860
  var config2 = null;
1673
1861
  var state = "pending";
1674
1862
  var user = null;
@@ -1682,6 +1870,7 @@ var embedToken;
1682
1870
  var colyseusUrls;
1683
1871
  var authorityUrls;
1684
1872
  var authorityRegions;
1873
+ var authorityHome;
1685
1874
  var localAuthority = false;
1686
1875
  var parentOrigin = null;
1687
1876
  var shellCaps = [];
@@ -1911,6 +2100,11 @@ function getAuthorityUrls() {
1911
2100
  function getAuthorityRegions() {
1912
2101
  return regionList(authorityRegions);
1913
2102
  }
2103
+ function getAuthorityHome() {
2104
+ if (typeof authorityHome !== "string" || authorityHome.length === 0) return void 0;
2105
+ const home = authorityHome;
2106
+ return regionList(authorityRegions).some((r) => r.region === home) ? home : void 0;
2107
+ }
1914
2108
  function waitForAuth() {
1915
2109
  if (state === "authenticated" && user) return Promise.resolve({ user });
1916
2110
  if (state === "blocked") return Promise.reject(new Error("genex embed auth: blocked"));
@@ -2705,6 +2899,7 @@ function adoptColyseus(block) {
2705
2899
  colyseusUrls = block?.urls;
2706
2900
  authorityUrls = block?.authorityUrls;
2707
2901
  authorityRegions = block?.authorityRegions;
2902
+ authorityHome = block?.authorityHome;
2708
2903
  }
2709
2904
  function urlList(value) {
2710
2905
  if (!Array.isArray(value)) return void 0;
@@ -3257,6 +3452,7 @@ export {
3257
3452
  getPayments,
3258
3453
  requestPayment,
3259
3454
  getGenerationModels,
3455
+ foldGenerationRequest,
3260
3456
  getWorkflowOfferings,
3261
3457
  getGeneration,
3262
3458
  waitForGeneration,
@@ -3266,6 +3462,8 @@ export {
3266
3462
  getSpendGrant,
3267
3463
  getActiveSpendGrant,
3268
3464
  stopSpendGrant,
3465
+ lendSpendGrantToRoom,
3466
+ returnSpendGrantFromRoom,
3269
3467
  requestSpendGrant,
3270
3468
  generateStream,
3271
3469
  judge,
@@ -3282,6 +3480,7 @@ export {
3282
3480
  getColyseusUrls,
3283
3481
  getAuthorityUrls,
3284
3482
  getAuthorityRegions,
3483
+ getAuthorityHome,
3285
3484
  waitForAuth,
3286
3485
  waitForPlayer,
3287
3486
  on,
@@ -468,6 +468,35 @@ function parsePlatformResult(value) {
468
468
  function isGenerationId(value) {
469
469
  return typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(value);
470
470
  }
471
+ var RUNTIME_TURN_LABEL = { user: "User", assistant: "Assistant" };
472
+ function runtimeTurns(request) {
473
+ return [...request.messages ?? [], ...request.prompt ? [{ role: "user", content: request.prompt }] : []];
474
+ }
475
+ function runtimeConversationError(request) {
476
+ if (request.system !== void 0 && (typeof request.system !== "string" || !request.system.trim())) return "invalid_request";
477
+ if (request.prompt !== void 0 && typeof request.prompt !== "string") return "invalid_request";
478
+ if (request.messages !== void 0 && (!Array.isArray(request.messages) || request.messages.length === 0 || request.messages.some((turn) => !turn || typeof turn !== "object" || turn.role !== "user" && turn.role !== "assistant" || typeof turn.content !== "string" || !turn.content.trim() || Object.keys(turn).length !== 2))) return "invalid_messages";
479
+ const prompt = typeof request.prompt === "string" ? request.prompt.trim() : "";
480
+ const turns = runtimeTurns({ messages: request.messages, prompt });
481
+ if (turns.length === 0) return "invalid_request";
482
+ const ordered = turns[0].role === "user" && turns[turns.length - 1].role === "user" && turns.every((turn, index) => index === 0 || turn.role !== turns[index - 1].role);
483
+ return ordered ? void 0 : "invalid_messages";
484
+ }
485
+ function foldRuntimeConversation(request) {
486
+ const turns = runtimeTurns(request);
487
+ if (!request.system && turns.length <= 1) return turns[0]?.content ?? "";
488
+ const parts = [];
489
+ if (request.system) parts.push(`Instructions:
490
+ ${request.system}`);
491
+ if (turns.length === 1) parts.push(`Request:
492
+ ${turns[0].content}`);
493
+ else if (turns.length > 1) {
494
+ parts.push(`Conversation:
495
+ ${turns.map((turn) => `${RUNTIME_TURN_LABEL[turn.role]}: ${turn.content}`).join("\n\n")}`);
496
+ parts.push("Answer the last User message as the Assistant.");
497
+ }
498
+ return parts.join("\n\n");
499
+ }
471
500
  function parseGenerationStreamEvent(event, data) {
472
501
  let value;
473
502
  try {
@@ -497,6 +526,40 @@ function createBridgeId(random = Math.random) {
497
526
  return out;
498
527
  }
499
528
 
529
+ // ../embed-protocol/src/runtime-practice.ts
530
+ var PRACTICE_PARAM = "genex_llm_practice";
531
+ var PRACTICE_HOST = "127.0.0.1";
532
+ var PRACTICE_TOKEN_RE = /^[0-9a-f]{32}$/;
533
+ var PRACTICE_PORT_RE = /^[1-9][0-9]{3,4}$/;
534
+ var LOOPBACK_ORIGIN_RE = /^http:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::[0-9]{1,5})?$/;
535
+ function isPracticeToken(value) {
536
+ return typeof value === "string" && PRACTICE_TOKEN_RE.test(value);
537
+ }
538
+ function isPracticePort(value) {
539
+ return Number.isInteger(value) && value >= 1024 && value <= 65535;
540
+ }
541
+ function isLoopbackHttpOrigin(origin) {
542
+ return typeof origin === "string" && LOOPBACK_ORIGIN_RE.test(origin);
543
+ }
544
+ function readPracticeKey(search) {
545
+ if (typeof search !== "string") return null;
546
+ const query = search.charAt(0) === "?" ? search.slice(1) : search;
547
+ for (const pair of query.split("&")) {
548
+ const eq = pair.indexOf("=");
549
+ if (eq === -1 || pair.slice(0, eq) !== PRACTICE_PARAM) continue;
550
+ const value = pair.slice(eq + 1);
551
+ const dot = value.indexOf(".");
552
+ const port = value.slice(0, dot === -1 ? 0 : dot);
553
+ const token = value.slice(dot + 1);
554
+ if (!PRACTICE_PORT_RE.test(port) || !isPracticePort(Number(port)) || !isPracticeToken(token)) return null;
555
+ return { port: Number(port), token };
556
+ }
557
+ return null;
558
+ }
559
+ function practiceOrigin(port) {
560
+ return `http://${PRACTICE_HOST}:${port}`;
561
+ }
562
+
500
563
  export {
501
564
  NATIVE_CHANNEL,
502
565
  NATIVE_PROTOCOL_VERSION,
@@ -529,6 +592,11 @@ export {
529
592
  parsePlatformRequest,
530
593
  parsePlatformResult,
531
594
  isGenerationId,
595
+ runtimeConversationError,
596
+ foldRuntimeConversation,
532
597
  parseGenerationStreamEvent,
533
- isGenerationTerminal
598
+ isGenerationTerminal,
599
+ isLoopbackHttpOrigin,
600
+ readPracticeKey,
601
+ practiceOrigin
534
602
  };
@@ -1,4 +1,4 @@
1
- import { R as RuntimeJudgeQuestion, a as RuntimeWorkflowInput, b as RuntimeGenerationView } from './runtime-generation-B3oFDmCp.js';
1
+ import { R as RuntimeConversationFields, a as RuntimeControlFields, b as RuntimeJudgeQuestion, c as RuntimeWorkflowInput, d as RuntimeGenerationView } from './runtime-generation-D4RMgsvn.js';
2
2
 
3
3
  /**
4
4
  * Server-only benchmarks spend the authenticated creator's OWN CREDITS
@@ -21,16 +21,23 @@ interface DevelopmentCap {
21
21
  maxCoins?: number;
22
22
  }
23
23
  interface DevelopmentGenerationOptions extends DevelopmentGenerationConfig, DevelopmentCap {
24
+ /**
25
+ * The call to measure, exactly as the game will make it — its `system`,
26
+ * `messages` and controls included, because they change what it costs. They
27
+ * are sent as given: a stand that does not accept them answers
28
+ * `invalid_request` (a benchmark of a different request would price nothing).
29
+ */
24
30
  request: {
25
31
  modelId: string;
26
- prompt: string;
32
+ /** Required unless `messages` ends with the user's turn. */
33
+ prompt?: string;
27
34
  outputFormat: 'text' | 'json';
28
35
  schema?: Record<string, unknown>;
29
36
  /** The most output tokens the benchmarked call may write, exactly as the
30
37
  * game will ask (`generate({ maxOutputTokens })`); omit for the stand's default. */
31
38
  maxOutputTokens?: number;
32
39
  idempotencyKey?: string;
33
- };
40
+ } & RuntimeConversationFields & RuntimeControlFields;
34
41
  /** Waiting time only; timeout returns the last server view without canceling.
35
42
  * Defaults to 20 minutes, longer than the lane's longest dispatch. */
36
43
  timeoutMs?: number;
@@ -1,10 +1,11 @@
1
1
  import {
2
2
  isGenerationId,
3
3
  isGenerationTerminal
4
- } from "./chunk-QBCWKMVQ.js";
4
+ } from "./chunk-WQJM5MJL.js";
5
5
 
6
6
  // src/development.ts
7
7
  var DEVELOPMENT_WAIT_MS = 12e5;
8
+ var CONVERSATION_FIELDS = ["system", "messages", "temperature", "topP", "stop", "seed", "reasoningEffort", "cacheSystem"];
8
9
  function assertIdentifier(value) {
9
10
  if (!/^[A-Za-z0-9_.:-]{1,120}$/.test(value) || value === "." || value === "..") throw new Error("invalid_development_identifier");
10
11
  }
@@ -52,8 +53,9 @@ async function developmentGenerate(options) {
52
53
  if (input.maxOutputTokens !== void 0 && (!Number.isSafeInteger(input.maxOutputTokens) || input.maxOutputTokens < 1)) throw new Error("invalid_max_output_tokens");
53
54
  const view = await request(options, "/generations", { ...cap, request: {
54
55
  modelId: input.modelId,
55
- prompt: input.prompt,
56
+ ...input.prompt === void 0 ? {} : { prompt: input.prompt },
56
57
  outputFormat: input.outputFormat,
58
+ ...Object.fromEntries(CONVERSATION_FIELDS.filter((key) => input[key] !== void 0).map((key) => [key, input[key]])),
57
59
  ...input.schema === void 0 ? {} : { schema: input.schema },
58
60
  ...input.maxOutputTokens === void 0 ? {} : { maxOutputTokens: input.maxOutputTokens },
59
61
  idempotencyKey: input.idempotencyKey ?? crypto.randomUUID()