@genex-ai/embed-sdk 0.24.3 → 0.26.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
@@ -211,6 +211,133 @@ and something that survives a reload. Validate `result.output` against the shape
211
211
  your game expects before using it, always. It is data, never authority for
212
212
  coins, rewards or items.
213
213
 
214
+ ## Streaming replies
215
+
216
+ SDK **0.26.0+**. `generateStream()` is `generate({ grantId })` answered as it is
217
+ written: the text arrives in pieces while the model writes it, instead of all at
218
+ once after the call. Use it for **dialogue and narration** a player watches
219
+ appear — an NPC's reply, a story beat. Keep `generate()` for answers the game
220
+ only acts on as a whole (a quest object, a list), and `judge()` for decisions.
221
+
222
+ ```ts
223
+ import { generateStream, generationErrorMessage } from '@genex-ai/embed-sdk';
224
+
225
+ const reply = await generateStream({
226
+ ...request, // the same options generate() takes
227
+ grantId, // required: only a standing budget streams
228
+ onDelta: (_piece, soFar) => bubble.setText(soFar),
229
+ });
230
+ if (reply.status === 'succeeded') applyGeneration(reply); // the answer
231
+ else showNotice(generationErrorMessage(reply.error));
232
+ ```
233
+
234
+ It resolves to **the same result `generate()` gives** — status, output, receipt
235
+ — and that result, not the pieces, is the answer. Pieces are provisional: a call
236
+ can still fail after text has arrived (the model broke off, or a JSON answer
237
+ did not match the schema), so let the resolved status decide what the game
238
+ keeps. The price is the same fixed price: a started attempt is charged whether
239
+ it succeeds, fails, or the player walks away mid-sentence.
240
+
241
+ For `outputFormat: 'json'`, `onPartialField(name, partialText)` reports the
242
+ **first top-level string property of `schema`** as far as the model has written
243
+ it — put the NPC's line first in the schema and it can appear word by word while
244
+ the rest of the object is still arriving. The object itself is parsed and
245
+ checked against the schema only once it is complete.
246
+
247
+ - **Grant-only.** Without `grantId` it resolves `failed` with
248
+ `stream_requires_grant` before the network: a one-time request waits on the
249
+ player's approval sheet, so there is nothing to stream. Every other guard is
250
+ a budget `generate()`'s — production play, a signed-in player, a trusted
251
+ parent, no popup and no user gesture — and so are the refusals
252
+ (`grant_concurrency`, `grant_limit_reached`, …). A stream holds one of the
253
+ budget's `maxConcurrent` slots until it has settled.
254
+ - **Sometimes it arrives whole.** A call the stand cannot start at once, a
255
+ retry of a call already running (the same `idempotencyKey`), or a budget on
256
+ the player's own plan is answered in one piece: the SDK waits for it the way
257
+ `generate()` does and calls `onDelta` once with the whole text.
258
+ - **`signal` stops the reading, not the call.** The model still finishes and the
259
+ call is charged; the result is `pending` with `stream_aborted` and the
260
+ `generationId` — `waitForGeneration(generationId)` recovers the answer. A
261
+ dropped connection is recovered the same way, automatically: Genex keeps
262
+ reading the model's reply after a client leaves and settles it either way.
263
+
264
+ The wire, for other clients: `POST /api/runtime/grants/:id/generations/stream`
265
+ with the embed token as a bearer answers `text/event-stream` — `start`
266
+ `{ generationId }`, `delta` `{ text }` (batched, at most every ~50 ms) and a
267
+ final `done` carrying the same view `GET /generations/:id` returns. EventSource
268
+ cannot send a POST or the token, so the SDK reads `fetch()`'s body.
269
+
270
+ ## Judge during play
271
+
272
+ SDK **0.25.0+**. `generate()` writes; `judge()` decides. A game that needs to
273
+ KNOW something about its own state — which mood the player is in, how
274
+ threatening a scene is on a scale, whether an NPC is lying — asks the budget's
275
+ classifier typed questions and gets calibrated probabilities back, typically in
276
+ about a third of a second. It writes no prose and invents no numbers, which is
277
+ exactly what makes it a steadier referee than a chat model asked to classify.
278
+
279
+ It is **grant-only** and **billed as used**: a call costs a small fraction of a
280
+ coin, so it is never charged a coin of its own. The budget holds a coin, calls
281
+ add up against it, and a whole coin is taken each time they reach one; when the
282
+ budget ends, a remainder is one coin and anything still held goes back. Ask for
283
+ it when you request the budget:
284
+
285
+ ```ts
286
+ import { requestSpendGrant, judge, generationErrorMessage } from '@genex-ai/embed-sdk';
287
+
288
+ const budget = await requestSpendGrant({
289
+ models: [model.id], // or [] for a judge-only budget
290
+ perCallMaxCoins: 8, perCallEstimateCoins: 5,
291
+ disclosure: { periodLabel: 'minute', estimatedCallsPerPeriod: 4, estimatedCoinsPerPeriod: 20 },
292
+ judge: { enabled: true, estimatedCallsPerPeriod: 30 }, // honest checks per period
293
+ });
294
+
295
+ const verdict = await judge({
296
+ grantId: budget.grantId!,
297
+ state: { npc: 'Mara', said: 'I never touched the key', evidence: ['key in her pocket'] },
298
+ questions: {
299
+ lying: { type: 'noul', instructions: 'Is the NPC lying about the key?' },
300
+ mood: { type: 'choice', instructions: 'What is the NPC\'s mood?',
301
+ criteria: { calm: 'Relaxed and cooperative', defensive: { what: 'Guarded, deflecting', not_for: 'Openly hostile' } } },
302
+ threat: { type: 'score', instructions: 'How dangerous is the NPC right now?', criteria: ['harmless', 'wary', 'dangerous'] },
303
+ },
304
+ });
305
+ if (verdict.status === 'succeeded') {
306
+ const lying = verdict.answers!.lying; // { type: 'noul', noul: 0.87 }
307
+ if (lying.type === 'noul' && lying.noul > 0.7) accuse();
308
+ } else showNotice(generationErrorMessage(verdict.error));
309
+ ```
310
+
311
+ The sheet tells the player the game also uses a fast classifier billed as used,
312
+ with Genex's own worst case for your declared calls per period beside your
313
+ estimate. Up to 64 questions per call: `choice` (2–255 named options, each a
314
+ description or `{ what, not_for?, examples? }`), `score` (2–10 levels, lowest
315
+ first) and `noul` (yes/no, `criteria: { true, false }` optional); every text
316
+ field is at most 2000 characters and `state` any JSON up to 96 KB. Each answer
317
+ has the type its question asked: `{ choice, probabilities }`,
318
+ `{ score, probabilities }` or `{ noul }` (a probability, not a boolean — pick
319
+ your own threshold).
320
+
321
+ `judge()` needs the budget and applies every guard a budget `generate()` does;
322
+ it opens no window. The answer arrives in the same response; reuse an
323
+ `idempotencyKey` to retry the same call without paying twice. A call that times
324
+ out (`timeoutMs`, 1000–20000) is `unknown` and billed at its maximum, because
325
+ the work may have run. The refusals to handle as game states:
326
+ `judge_requires_grant` (no budget), `judge_not_enabled` (the budget was approved
327
+ without the judge — request a new one), `judge_requires_coins`,
328
+ `judge_period_limit` (the checks reached the per-period ceiling the player was
329
+ shown — it rolls, so try again shortly), `judge_busy` and `judge_paused` (the
330
+ platform's, retry later), `request_too_large` (state and questions over the
331
+ byte bound), and every budget code above — `grant_concurrency` now also means
332
+ "fits once calls in flight land", never an ended budget. The receipt is on `verdict.billing` (`chargedCoins` is always
333
+ 0; `chargedUsdPicos` is what this call added); the budget's `spentCoins` and
334
+ `heldCoins` are the numbers to show.
335
+
336
+ Benchmark on your own coins with `developmentJudge()` from
337
+ `@genex-ai/embed-sdk/development` (same shape, `{ maxCoins, request }`). It is
338
+ billed one whole coin a call on your wallet — a player's budget, which meters,
339
+ spends far less for the same calls.
340
+
214
341
  ## Your subscription and the Genex player watcher
215
342
 
216
343
  Both approval sheets can offer the player their own Claude or ChatGPT plan
@@ -6,9 +6,10 @@ import {
6
6
  hasNativeMarker,
7
7
  isGenerationId,
8
8
  isGenerationTerminal,
9
+ parseGenerationStreamEvent,
9
10
  readBridgeNativeCommand,
10
11
  readNativeEntry
11
- } from "./chunk-VPIQVRVS.js";
12
+ } from "./chunk-MJPLBT3T.js";
12
13
 
13
14
  // src/commerce.ts
14
15
  var cfg = null;
@@ -117,6 +118,129 @@ async function buy(opts) {
117
118
  return awaitOutcome(view.id, opts.timeoutMs ?? 18e4);
118
119
  }
119
120
 
121
+ // src/stream.ts
122
+ function createSseParser(onEvent) {
123
+ let buffer = "";
124
+ let data = [];
125
+ let name = "";
126
+ const line = (text) => {
127
+ if (text === "") {
128
+ if (data.length) onEvent({ event: name || "message", data: data.join("\n") });
129
+ data = [];
130
+ name = "";
131
+ return;
132
+ }
133
+ if (text.startsWith(":")) return;
134
+ const colon = text.indexOf(":");
135
+ const field = colon === -1 ? text : text.slice(0, colon);
136
+ let value = colon === -1 ? "" : text.slice(colon + 1);
137
+ if (value.startsWith(" ")) value = value.slice(1);
138
+ if (field === "data") data.push(value);
139
+ else if (field === "event") name = value;
140
+ };
141
+ const drain = (final) => {
142
+ for (; ; ) {
143
+ const match = /\r\n|\r|\n/.exec(buffer);
144
+ if (!match) break;
145
+ if (match[0] === "\r" && match.index === buffer.length - 1 && !final) break;
146
+ line(buffer.slice(0, match.index));
147
+ buffer = buffer.slice(match.index + match[0].length);
148
+ }
149
+ if (final) {
150
+ if (buffer) line(buffer);
151
+ buffer = "";
152
+ line("");
153
+ }
154
+ };
155
+ return {
156
+ push(text) {
157
+ buffer += text;
158
+ drain(false);
159
+ },
160
+ end() {
161
+ drain(true);
162
+ }
163
+ };
164
+ }
165
+ function firstStringProperty(schema) {
166
+ if (!schema || typeof schema !== "object") return void 0;
167
+ const properties = schema.properties;
168
+ if (schema.type !== "object" || !properties || typeof properties !== "object" || Array.isArray(properties)) return void 0;
169
+ for (const [name, child] of Object.entries(properties)) {
170
+ if (child && typeof child === "object" && child.type === "string") return name;
171
+ }
172
+ return void 0;
173
+ }
174
+ var ESCAPES = { '"': '"', "\\": "\\", "/": "/", b: "\b", f: "\f", n: "\n", r: "\r", t: " " };
175
+ function readString(text, start) {
176
+ let value = "";
177
+ let i = start + 1;
178
+ while (i < text.length) {
179
+ const c = text[i];
180
+ if (c === '"') return { value, end: i + 1, complete: true };
181
+ if (c !== "\\") {
182
+ value += c;
183
+ i++;
184
+ continue;
185
+ }
186
+ const next = text[i + 1];
187
+ if (next === void 0) break;
188
+ if (next === "u") {
189
+ const hex = text.slice(i + 2, i + 6);
190
+ if (hex.length < 4) break;
191
+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) return { value: withoutHalfPair(value), end: text.length, complete: false };
192
+ value += String.fromCharCode(parseInt(hex, 16));
193
+ i += 6;
194
+ continue;
195
+ }
196
+ value += ESCAPES[next] ?? next;
197
+ i += 2;
198
+ }
199
+ return { value: withoutHalfPair(value), end: text.length, complete: false };
200
+ }
201
+ function withoutHalfPair(value) {
202
+ return /[\uD800-\uDBFF]$/.test(value) ? value.slice(0, -1) : value;
203
+ }
204
+ function partialStringField(text, name) {
205
+ let i = 0;
206
+ const skip = () => {
207
+ while (i < text.length && /\s/.test(text[i])) i++;
208
+ };
209
+ skip();
210
+ if (text[i] !== "{") return void 0;
211
+ i++;
212
+ let depth = 1;
213
+ let expectKey = true;
214
+ while (i < text.length) {
215
+ const c = text[i];
216
+ if (c === '"') {
217
+ const read = readString(text, i);
218
+ if (depth === 1 && expectKey) {
219
+ if (!read.complete) return void 0;
220
+ i = read.end;
221
+ skip();
222
+ if (text[i] !== ":") return void 0;
223
+ i++;
224
+ skip();
225
+ expectKey = false;
226
+ if (read.value !== name) continue;
227
+ if (text[i] !== '"') return void 0;
228
+ return readString(text, i).value;
229
+ }
230
+ if (!read.complete) return void 0;
231
+ i = read.end;
232
+ continue;
233
+ }
234
+ if (c === "{" || c === "[") depth++;
235
+ else if (c === "}" || c === "]") {
236
+ depth--;
237
+ if (depth === 0) return void 0;
238
+ } else if (c === "," && depth === 1) expectKey = true;
239
+ i++;
240
+ }
241
+ return void 0;
242
+ }
243
+
120
244
  // src/generation.ts
121
245
  var config = null;
122
246
  function _initGeneration(value) {
@@ -310,7 +434,9 @@ function validCount(value, min, max) {
310
434
  return Number.isSafeInteger(value) && value >= min && value <= max;
311
435
  }
312
436
  function invalidGrantOptions(options) {
313
- if (!Array.isArray(options.models) || options.models.length < 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 "invalid_models";
437
+ const judge2 = options.judge;
438
+ if (judge2 !== void 0 && (typeof judge2 !== "object" || judge2 === null || typeof judge2.enabled !== "boolean" || !validCount(judge2.estimatedCallsPerPeriod, 1, 1e5))) return "invalid_judge_terms";
439
+ 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 "invalid_models";
314
440
  if (!validCount(options.perCallMaxCoins, 1, 1e6) || !validCount(options.perCallEstimateCoins, 1, 1e6) || options.perCallEstimateCoins > options.perCallMaxCoins) return "invalid_declared_price";
315
441
  const d = options.disclosure;
316
442
  if (!d || typeof d !== "object" || !["minute", "hour", "session"].includes(d.periodLabel) || !validCount(d.estimatedCallsPerPeriod, 1, 1e4) || !validCount(d.estimatedCoinsPerPeriod, 0, 1e6)) return "invalid_disclosure";
@@ -383,7 +509,8 @@ async function requestSpendGrant(options) {
383
509
  ...options.maxConcurrent !== void 0 ? { maxConcurrent: options.maxConcurrent } : {},
384
510
  ...options.maxCallsPerMinute !== void 0 ? { maxCallsPerMinute: options.maxCallsPerMinute } : {},
385
511
  ...options.maxPendingExternal !== void 0 ? { maxPendingExternal: options.maxPendingExternal } : {},
386
- ...options.allowExternal !== void 0 ? { allowExternal: options.allowExternal } : {}
512
+ ...options.allowExternal !== void 0 ? { allowExternal: options.allowExternal } : {},
513
+ ...options.judge !== void 0 ? { judge: { enabled: options.judge.enabled, estimatedCallsPerPeriod: options.judge.estimatedCallsPerPeriod } } : {}
387
514
  });
388
515
  if (!isGrantId(view.id)) throw new Error("invalid_grant_response");
389
516
  const settled = grantOutcome(view);
@@ -420,6 +547,154 @@ async function generateUnderGrant(grantId, input, idempotencyKey, timeoutMs) {
420
547
  return { status: "failed", error: error instanceof Error ? error.message : "generation_unavailable" };
421
548
  }
422
549
  }
550
+ async function generateStream(options) {
551
+ if (!validEstimateCoins(options.estimateCoins)) return { status: "failed", error: "invalid_estimate_coins" };
552
+ const { timeoutMs, idempotencyKey, grantId, onDelta, onPartialField, signal, allowExternal: _unused, ...body } = options;
553
+ if (grantId === void 0 || grantId === null) return { status: "failed", error: "stream_requires_grant" };
554
+ if (!isGrantId(grantId)) return { status: "failed", error: "invalid_grant_id" };
555
+ const guarded = approvalGuards();
556
+ if ("status" in guarded) return guarded;
557
+ const c = must2();
558
+ const field = body.outputFormat === "json" && onPartialField ? firstStringProperty(body.schema) : void 0;
559
+ let generationId;
560
+ let soFar = "";
561
+ let shown;
562
+ const showField = (value) => {
563
+ if (!field || value === shown) return;
564
+ shown = value;
565
+ try {
566
+ onPartialField(field, value);
567
+ } catch {
568
+ }
569
+ };
570
+ const deliver = (text) => {
571
+ soFar += text;
572
+ try {
573
+ onDelta?.(text, soFar);
574
+ } catch {
575
+ }
576
+ if (field) {
577
+ const partial = partialStringField(soFar, field);
578
+ if (partial !== void 0) showField(partial);
579
+ }
580
+ };
581
+ const finish = (result) => {
582
+ if (result.status === "succeeded") {
583
+ const output = result.output;
584
+ if (typeof output === "string" && output.startsWith(soFar) && output.length > soFar.length) deliver(output.slice(soFar.length));
585
+ else if (field && output && typeof output === "object" && typeof output[field] === "string") showField(output[field]);
586
+ }
587
+ return result;
588
+ };
589
+ const aborted = () => ({ status: "pending", ...generationId ? { generationId } : {}, error: "stream_aborted" });
590
+ try {
591
+ const token = c.getToken();
592
+ if (!token) return { status: "failed", error: "no_player_session" };
593
+ const response = await fetch(`${c.apiUrl}/api/runtime/grants/${encodeURIComponent(grantId)}/generations/stream`, {
594
+ method: "POST",
595
+ credentials: "omit",
596
+ cache: "no-store",
597
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "text/event-stream" },
598
+ body: JSON.stringify({ ...body, idempotencyKey: idempotencyKey ?? crypto.randomUUID() }),
599
+ ...signal ? { signal } : {}
600
+ });
601
+ if (!response.ok) {
602
+ const refusal = await response.json().catch(() => ({}));
603
+ return { status: "failed", error: typeof refusal.error === "string" ? refusal.error : "generation_unavailable" };
604
+ }
605
+ if (!response.body || !(response.headers.get("content-type") ?? "").includes("text/event-stream")) throw new Error("invalid_generation_response");
606
+ let done;
607
+ const parser = createSseParser(({ event, data }) => {
608
+ const parsed = parseGenerationStreamEvent(event, data);
609
+ if (!parsed || done) return;
610
+ if (parsed.event === "start") generationId ??= parsed.data.generationId;
611
+ else if (parsed.event === "delta") deliver(parsed.data.text);
612
+ else done = parsed.data;
613
+ });
614
+ const reader = response.body.getReader();
615
+ const decoder = new TextDecoder();
616
+ try {
617
+ for (; ; ) {
618
+ const { value, done: ended } = await reader.read();
619
+ if (ended) break;
620
+ parser.push(decoder.decode(value, { stream: true }));
621
+ if (done) {
622
+ reader.cancel().catch(() => {
623
+ });
624
+ break;
625
+ }
626
+ }
627
+ if (!done) {
628
+ parser.push(decoder.decode());
629
+ parser.end();
630
+ }
631
+ } catch {
632
+ if (signal?.aborted) return aborted();
633
+ }
634
+ if (signal?.aborted) return aborted();
635
+ if (done) {
636
+ const view = done;
637
+ if (!isGenerationId(view.id) || view.grantId !== grantId || generationId !== void 0 && view.id !== generationId) throw new Error("invalid_generation_response");
638
+ return finish(outcome(view) ?? await poll(view.id, timeoutMs ?? 6e5, outcome));
639
+ }
640
+ if (generationId) return finish(await poll(generationId, timeoutMs ?? 6e5, outcome));
641
+ return { status: "failed", error: "generation_unavailable" };
642
+ } catch (error) {
643
+ if (signal?.aborted) return aborted();
644
+ return { status: "failed", error: error instanceof Error ? error.message : "generation_unavailable" };
645
+ }
646
+ }
647
+ var JUDGE_QUESTION_NAME = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
648
+ function invalidJudgeOptions(options) {
649
+ if (options.grantId === void 0 || options.grantId === null) return "judge_requires_grant";
650
+ if (!isGrantId(options.grantId)) return "invalid_grant_id";
651
+ if (options.state === void 0) return "invalid_request";
652
+ const questions = options.questions;
653
+ if (!questions || typeof questions !== "object" || Array.isArray(questions)) return "invalid_request";
654
+ const names = Object.keys(questions);
655
+ if (names.length < 1 || names.length > 64 || names.some((name) => !JUDGE_QUESTION_NAME.test(name))) return "invalid_request";
656
+ if (names.some((name) => !["choice", "score", "noul"].includes(questions[name]?.type))) return "invalid_request";
657
+ if (options.timeoutMs !== void 0 && !validCount(options.timeoutMs, 1e3, 2e4)) return "invalid_timeout";
658
+ if (options.idempotencyKey !== void 0 && (typeof options.idempotencyKey !== "string" || options.idempotencyKey.length < 8 || options.idempotencyKey.length > 100)) return "invalid_idempotency_key";
659
+ return void 0;
660
+ }
661
+ function judgeOutcome(view) {
662
+ if (!isGenerationTerminal(view.status)) return void 0;
663
+ return {
664
+ status: view.status === "expired" ? "failed" : view.status,
665
+ generationId: view.id,
666
+ ...view.status === "succeeded" ? { answers: view.output } : {},
667
+ ...view.error ? { error: view.error } : {}
668
+ };
669
+ }
670
+ async function judge(options) {
671
+ const invalid = invalidJudgeOptions(options);
672
+ if (invalid) return { status: "failed", error: invalid };
673
+ const guarded = approvalGuards();
674
+ if ("status" in guarded) return guarded;
675
+ try {
676
+ const view = await request(`/grants/${encodeURIComponent(options.grantId)}/judgments`, {
677
+ idempotencyKey: options.idempotencyKey ?? crypto.randomUUID(),
678
+ state: options.state,
679
+ questions: options.questions,
680
+ ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {}
681
+ });
682
+ if (!isGenerationId(view.generationId) || view.grantId !== options.grantId) throw new Error("invalid_judgment_response");
683
+ if (view.status === "dispatching") {
684
+ const settled = await poll(view.generationId, (options.timeoutMs ?? 2e4) + 1e4, judgeOutcome);
685
+ return settled.status === "pending" ? { ...settled, billing: view.billing } : settled;
686
+ }
687
+ return {
688
+ status: view.status,
689
+ generationId: view.generationId,
690
+ billing: view.billing,
691
+ ...view.answers ? { answers: view.answers } : {},
692
+ ...view.error ? { error: view.error } : {}
693
+ };
694
+ } catch (error) {
695
+ return { status: "failed", error: error instanceof Error ? error.message : "judge_unavailable" };
696
+ }
697
+ }
423
698
  function generationErrorMessage(code) {
424
699
  switch (code) {
425
700
  // --- the outcome is not known yet. Never a failure sentence. ------------
@@ -456,6 +731,26 @@ function generationErrorMessage(code) {
456
731
  return "A budget on your own plan is already running. Stop it on Genex before setting up another.";
457
732
  case "invalid_grant_limit":
458
733
  return "That limit is outside the range Genex offers. Choose one on the slider.";
734
+ // --- the judge ------------------------------------------------------------
735
+ case "judge_requires_grant":
736
+ return "This game\u2019s quick checks run under a budget you approve. Set one up to keep going.";
737
+ case "judge_not_enabled":
738
+ return "This budget doesn\u2019t cover the game\u2019s quick checks. Set up a new one to keep going.";
739
+ case "judge_requires_coins":
740
+ return "The game\u2019s quick checks are paid from your Genex wallet, not your own plan.";
741
+ case "invalid_judge_terms":
742
+ return "This budget request isn\u2019t valid, so nothing was requested.";
743
+ case "judge_period_limit":
744
+ return "The game\u2019s quick checks have reached the most your budget allows for now. They pick up again shortly.";
745
+ case "judge_busy":
746
+ return "The game\u2019s quick checks are busy right now. Try again in a moment.";
747
+ case "judge_paused":
748
+ return "The game\u2019s quick checks are paused for now. Try again later.";
749
+ // --- streamed replies -----------------------------------------------------
750
+ case "stream_requires_grant":
751
+ return "Live replies run under a budget you approve. Set one up to keep going.";
752
+ case "stream_aborted":
753
+ return "This reply stopped showing, but it is still finishing and is charged as usual. Check back in a moment.";
459
754
  case "waiting_for_plan":
460
755
  return "Your own plan is at its rate limit right now. This resumes on its own once the limit resets.";
461
756
  // --- personal plans and the player watcher ------------------------------
@@ -577,7 +872,7 @@ var RETRY_FLAG = "genex:embed:retry";
577
872
  var POPOVER_DISMISSED_FLAG = "genex:guest:popover-dismissed";
578
873
  var LOCAL_AUTH_FLAG = "genex:embed:local-auth";
579
874
  var PLAYER_ID_KEY = "genex:player";
580
- var SDK_VERSION = "0.24.3";
875
+ var SDK_VERSION = "0.26.0";
581
876
  var config2 = null;
582
877
  var state = "pending";
583
878
  var user = null;
@@ -1831,6 +2126,8 @@ export {
1831
2126
  getSpendGrant,
1832
2127
  stopSpendGrant,
1833
2128
  requestSpendGrant,
2129
+ generateStream,
2130
+ judge,
1834
2131
  generationErrorMessage,
1835
2132
  initEmbed,
1836
2133
  isEmbedded,
@@ -232,6 +232,20 @@ function readNativeEntry(search) {
232
232
  function isGenerationId(value) {
233
233
  return typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(value);
234
234
  }
235
+ function parseGenerationStreamEvent(event, data) {
236
+ let value;
237
+ try {
238
+ value = JSON.parse(data);
239
+ } catch {
240
+ return void 0;
241
+ }
242
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
243
+ const fields = value;
244
+ if (event === "start") return isGenerationId(fields.generationId) ? { event, data: { generationId: fields.generationId } } : void 0;
245
+ if (event === "delta") return typeof fields.text === "string" ? { event, data: { text: fields.text } } : void 0;
246
+ if (event === "done") return isGenerationId(fields.id) && typeof fields.status === "string" ? { event, data: value } : void 0;
247
+ return void 0;
248
+ }
235
249
  function isGenerationTerminal(status) {
236
250
  return ["succeeded", "failed", "unknown", "canceled", "expired"].includes(status);
237
251
  }
@@ -245,5 +259,6 @@ export {
245
259
  hasNativeMarker,
246
260
  readNativeEntry,
247
261
  isGenerationId,
262
+ parseGenerationStreamEvent,
248
263
  isGenerationTerminal
249
264
  };
@@ -1,4 +1,4 @@
1
- import { RuntimeWorkflowInput, RuntimeGenerationView } from '@genex/embed-protocol';
1
+ import { RuntimeJudgeQuestion, RuntimeWorkflowInput, RuntimeGenerationView } from '@genex/embed-protocol';
2
2
 
3
3
  /** Server-only benchmarks spend the authenticated creator's own coin wallet. */
4
4
 
@@ -32,6 +32,25 @@ interface DevelopmentWorkflowOptions extends DevelopmentGenerationConfig {
32
32
  }
33
33
  /** Create a generic benchmark and wait for execution and its actual-usage receipt. */
34
34
  declare function developmentGenerate(options: DevelopmentGenerationOptions): Promise<RuntimeGenerationView>;
35
+ interface DevelopmentJudgeOptions extends DevelopmentGenerationConfig {
36
+ /** Explicit maximum reservation in your own coins. Each call is charged at the
37
+ * lane's one-coin minimum (`consumed-v1`), a refusal before any work at zero. */
38
+ maxCoins: number;
39
+ request: {
40
+ state: unknown;
41
+ questions: Record<string, RuntimeJudgeQuestion>;
42
+ idempotencyKey?: string;
43
+ /** How long the server waits for the classifier, 1000–20000 ms. */
44
+ timeoutMs?: number;
45
+ };
46
+ }
47
+ /**
48
+ * The judge on the creator's OWN wallet, answered in the same response. Unlike
49
+ * a player's budget — which meters judge calls and moves whole coins only as
50
+ * they add up — a development call is billed at the one-coin minimum, so a
51
+ * bench here overstates what a budget would spend on the same calls.
52
+ */
53
+ declare function developmentJudge(options: DevelopmentJudgeOptions): Promise<RuntimeGenerationView>;
35
54
  /** Returns the accepted workflow so its trusted executor can enqueue before waiting. */
36
55
  declare function developmentRequestWorkflow(options: DevelopmentWorkflowOptions): Promise<RuntimeGenerationView>;
37
56
  /** Recover a benchmark with the same creator and project; no play token is used. */
@@ -41,4 +60,4 @@ declare function cancelDevelopmentGeneration(config: DevelopmentGenerationConfig
41
60
  /** Wait for execution and final billing; timeout preserves the latest pending receipt. */
42
61
  declare function waitForDevelopmentGeneration(config: DevelopmentGenerationConfig, generationId: string, timeoutMs?: number): Promise<RuntimeGenerationView>;
43
62
 
44
- export { type DevelopmentGenerationConfig, type DevelopmentGenerationOptions, type DevelopmentWorkflowOptions, cancelDevelopmentGeneration, developmentGenerate, developmentRequestWorkflow, getDevelopmentGeneration, waitForDevelopmentGeneration };
63
+ export { type DevelopmentGenerationConfig, type DevelopmentGenerationOptions, type DevelopmentJudgeOptions, type DevelopmentWorkflowOptions, cancelDevelopmentGeneration, developmentGenerate, developmentJudge, developmentRequestWorkflow, getDevelopmentGeneration, waitForDevelopmentGeneration };
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  isGenerationId,
3
3
  isGenerationTerminal
4
- } from "./chunk-VPIQVRVS.js";
4
+ } from "./chunk-MJPLBT3T.js";
5
5
 
6
6
  // src/development.ts
7
7
  function assertIdentifier(value) {
@@ -48,6 +48,19 @@ async function developmentGenerate(options) {
48
48
  } });
49
49
  return wait(options, view, options.timeoutMs ?? 6e5);
50
50
  }
51
+ async function developmentJudge(options) {
52
+ validateMaximum(options.maxCoins);
53
+ const input = options.request;
54
+ if (!input || input.state === void 0 || !input.questions || typeof input.questions !== "object") throw new Error("invalid_request");
55
+ const view = await request(options, "/judgments", { maxCoins: options.maxCoins, request: {
56
+ state: input.state,
57
+ questions: input.questions,
58
+ ...input.timeoutMs === void 0 ? {} : { timeoutMs: input.timeoutMs },
59
+ idempotencyKey: input.idempotencyKey ?? crypto.randomUUID()
60
+ } });
61
+ if (view.outputFormat !== "judge") throw new Error("invalid_development_response");
62
+ return view;
63
+ }
51
64
  async function developmentRequestWorkflow(options) {
52
65
  validateMaximum(options.maxCoins);
53
66
  assertIdentifier(options.workflowId);
@@ -93,6 +106,7 @@ async function waitForDevelopmentGeneration(config, generationId, timeoutMs = 6e
93
106
  export {
94
107
  cancelDevelopmentGeneration,
95
108
  developmentGenerate,
109
+ developmentJudge,
96
110
  developmentRequestWorkflow,
97
111
  getDevelopmentGeneration,
98
112
  waitForDevelopmentGeneration
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { RuntimeWorkflowInput, RuntimeGenerationBilling, RuntimeGenerationFunding, RuntimeGrantView, RuntimeGenerationView, RuntimeGenerationModels, RuntimeWorkflowOfferings } from '@genex/embed-protocol';
2
- export { RuntimeBillingPolicy, RuntimeExternalProvider, RuntimeGenerationBilling, RuntimeGenerationFunding, RuntimeGenerationModels, RuntimeGenerationStatus, RuntimeGenerationView, RuntimeGrantStatus, RuntimeGrantTerms, RuntimeGrantView, RuntimeWorkflowInput, RuntimeWorkflowOfferings } from '@genex/embed-protocol';
1
+ import { RuntimeJudgeQuestion, RuntimeJudgeAnswer, RuntimeJudgmentView, RuntimeWorkflowInput, RuntimeGenerationBilling, RuntimeGenerationFunding, RuntimeGrantView, RuntimeGenerationView, RuntimeGenerationModels, RuntimeWorkflowOfferings } from '@genex/embed-protocol';
2
+ export { RuntimeBillingPolicy, RuntimeExternalProvider, RuntimeGenerationBilling, RuntimeGenerationFunding, RuntimeGenerationModels, RuntimeGenerationStatus, RuntimeGenerationStreamEvent, RuntimeGenerationView, RuntimeGrantJudgeTerms, RuntimeGrantStatus, RuntimeGrantTerms, RuntimeGrantView, RuntimeJudgeAnswer, RuntimeJudgeCriterion, RuntimeJudgeQuestion, RuntimeJudgmentView, RuntimeWorkflowInput, RuntimeWorkflowOfferings } from '@genex/embed-protocol';
3
3
 
4
4
  /** A thing the game sells. Resolved server-side; the game never sets a price. */
5
5
  interface ShopItem {
@@ -146,8 +146,9 @@ interface RuntimeGenerationResult extends RuntimeGenerationBilling {
146
146
  status: 'succeeded' | 'failed' | 'unknown' | 'canceled' | 'expired' | 'pending';
147
147
  generationId?: string;
148
148
  output?: unknown;
149
- /** External output is user-supplied; never use it as authority for rewards or money. */
150
- source?: 'openrouter' | 'external';
149
+ /** External output is user-supplied; never use it as authority for rewards or money.
150
+ * `typesafe` appears only on a judge call read back through getGeneration(). */
151
+ source?: 'openrouter' | 'external' | 'typesafe';
151
152
  modelProvenance?: 'unverified';
152
153
  error?: string;
153
154
  }
@@ -223,6 +224,17 @@ interface SpendGrantOptions {
223
224
  maxPendingExternal?: number;
224
225
  /** Offer the player's own Claude/ChatGPT plan beside coins. Defaults off. */
225
226
  allowExternal?: boolean;
227
+ /**
228
+ * The game also calls judge() — a fast classifier billed as used rather than
229
+ * per request. The sheet tells the player so, beside the server's own worst
230
+ * case for `estimatedCallsPerPeriod` calls per `disclosure.periodLabel`. A
231
+ * budget with the judge is coin-funded: `allowExternal` offers nothing on it.
232
+ * With `enabled: true`, `models` may be empty for a judge-only budget.
233
+ */
234
+ judge?: {
235
+ enabled: boolean;
236
+ estimatedCallsPerPeriod: number;
237
+ };
226
238
  /** Reuse for the same budget request across retries and reloads. */
227
239
  idempotencyKey?: string;
228
240
  /** Approval waiting time only. A timeout neither cancels nor charges. */
@@ -255,6 +267,67 @@ declare function stopSpendGrant(grantId: string): Promise<RuntimeGrantView>;
255
267
  * Store the id: getSpendGrant(id) recovers the budget after a reload.
256
268
  */
257
269
  declare function requestSpendGrant(options: SpendGrantOptions): Promise<SpendGrantResult>;
270
+ interface GenerateStreamOptions extends GenerateOptions {
271
+ /** A standing budget from requestSpendGrant(). Required: only a budget streams. */
272
+ grantId: string;
273
+ /**
274
+ * Each piece of the answer as it arrives, and all of it so far. PROVISIONAL:
275
+ * a call can still fail after text has arrived (the model broke off, the
276
+ * JSON did not match the schema) — only the resolved result is the answer.
277
+ */
278
+ onDelta?: (text: string, soFar: string) => void;
279
+ /**
280
+ * `outputFormat: 'json'` only: the FIRST top-level string property of
281
+ * `schema` (say, an NPC's `line`), as far as the model has written it, read
282
+ * leniently from the growing JSON — so dialogue can appear while the rest of
283
+ * the object is still arriving. Called only when the value grows.
284
+ */
285
+ onPartialField?: (name: string, partialText: string) => void;
286
+ /**
287
+ * Stops READING the reply, not the call: the model still finishes and the
288
+ * call is charged as usual. Resolves `pending` with `stream_aborted`;
289
+ * waitForGeneration(generationId) recovers the answer.
290
+ */
291
+ signal?: AbortSignal;
292
+ }
293
+ /**
294
+ * One call under a standing budget, streamed. No popup and no user gesture —
295
+ * the same guards as generate({ grantId }). A call the stand cannot start at
296
+ * once, a replay of a call already running, or a budget on the player's own
297
+ * plan is answered whole: the SDK polls it, and `onDelta` receives the text in
298
+ * one piece at the end. A dropped connection is polled too, because the server
299
+ * keeps reading the model's reply and settles it either way.
300
+ */
301
+ declare function generateStream(options: GenerateStreamOptions): Promise<RuntimeGenerationResult>;
302
+ interface JudgeOptions {
303
+ /** A standing budget from requestSpendGrant({ judge: { enabled: true, … } }). Required. */
304
+ grantId: string;
305
+ /** Whatever the questions are about: any JSON value, at most 96 KB serialized. */
306
+ state: unknown;
307
+ /** One to 64 named questions (a name starts with a letter; letters, digits, `_`). */
308
+ questions: Record<string, RuntimeJudgeQuestion>;
309
+ /** Reuse for retries of the same call: a replay is answered, never billed twice. */
310
+ idempotencyKey?: string;
311
+ /** How long the server waits for the classifier, 1000–20000 ms. A call that
312
+ * times out is `unknown` and billed at its maximum — it may have run. */
313
+ timeoutMs?: number;
314
+ }
315
+ interface JudgeResult {
316
+ status: 'succeeded' | 'failed' | 'unknown' | 'canceled' | 'pending';
317
+ generationId?: string;
318
+ /** One typed answer per question; present only on `succeeded`. */
319
+ answers?: Record<string, RuntimeJudgeAnswer>;
320
+ error?: string;
321
+ /** Where the call's money went: never a coin of its own, always the budget's meter. */
322
+ billing?: RuntimeJudgmentView['billing'];
323
+ }
324
+ /**
325
+ * Ask the budget's classifier. No popup, no user gesture — the player approved
326
+ * the budget once — and every other guard generate({ grantId }) applies. The
327
+ * answer arrives in the same response; a replay of a call still running waits
328
+ * for it.
329
+ */
330
+ declare function judge(options: JudgeOptions): Promise<JudgeResult>;
258
331
  /**
259
332
  * A player-facing sentence for any code this lane can put in `result.error`.
260
333
  *
@@ -526,4 +599,4 @@ declare function __resetForTests(overrides?: {
526
599
  heartbeatIntervalMs?: number;
527
600
  }): void;
528
601
 
529
- export { type AuthState, type EmbedConfig, type EmbedEvent, type EmbedUser, type Entitlement, type GenerateOptions, type Leaderboard, type LeaderboardEntry, type PlayerStateResult, type PurchaseResult, type PurchaseStatus, type RequestWorkflowOptions, type RuntimeGenerationResult, type RuntimeWorkflowAuthorization, type SaveStateResult, type ShopItem, type SpendGrantDisclosure, type SpendGrantOptions, type SpendGrantResult, type SubmitScoreResult, type WorldStateResult, __resetForTests, _stashTicketFromUrl, buy, consumeEntitlement, generate, generationErrorMessage, getAuthState, getColyseusAuth, getColyseusUrls, getEmbedToken, getEntitlements, getGeneration, getGenerationModels, getLeaderboard, getShop, getSpendGrant, getUser, getWorkflowOfferings, initEmbed, isEmbedded, loadPlayerState, loadWorldState, on, requestSpendGrant, requestWorkflow, resumeWorkflow, savePlayerState, saveWorldState, stopSpendGrant, submitScore, waitForAuth, waitForGeneration, waitForPlayer };
602
+ export { type AuthState, 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 RequestWorkflowOptions, type RuntimeGenerationResult, type RuntimeWorkflowAuthorization, type SaveStateResult, type ShopItem, type SpendGrantDisclosure, type SpendGrantOptions, type SpendGrantResult, type SubmitScoreResult, type WorldStateResult, __resetForTests, _stashTicketFromUrl, buy, consumeEntitlement, generate, generateStream, generationErrorMessage, getAuthState, getColyseusAuth, getColyseusUrls, getEmbedToken, getEntitlements, getGeneration, getGenerationModels, getLeaderboard, getShop, getSpendGrant, getUser, getWorkflowOfferings, initEmbed, isEmbedded, judge, loadPlayerState, loadWorldState, on, requestSpendGrant, requestWorkflow, resumeWorkflow, savePlayerState, saveWorldState, stopSpendGrant, submitScore, waitForAuth, waitForGeneration, waitForPlayer };
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@ import {
4
4
  buy,
5
5
  consumeEntitlement,
6
6
  generate,
7
+ generateStream,
7
8
  generationErrorMessage,
8
9
  getAuthState,
9
10
  getColyseusAuth,
@@ -19,6 +20,7 @@ import {
19
20
  getWorkflowOfferings,
20
21
  initEmbed,
21
22
  isEmbedded,
23
+ judge,
22
24
  loadPlayerState,
23
25
  loadWorldState,
24
26
  on,
@@ -32,14 +34,15 @@ import {
32
34
  waitForAuth,
33
35
  waitForGeneration,
34
36
  waitForPlayer
35
- } from "./chunk-EM5TVVSD.js";
36
- import "./chunk-VPIQVRVS.js";
37
+ } from "./chunk-KEPAMDTE.js";
38
+ import "./chunk-MJPLBT3T.js";
37
39
  export {
38
40
  __resetForTests,
39
41
  _stashTicketFromUrl,
40
42
  buy,
41
43
  consumeEntitlement,
42
44
  generate,
45
+ generateStream,
43
46
  generationErrorMessage,
44
47
  getAuthState,
45
48
  getColyseusAuth,
@@ -55,6 +58,7 @@ export {
55
58
  getWorkflowOfferings,
56
59
  initEmbed,
57
60
  isEmbedded,
61
+ judge,
58
62
  loadPlayerState,
59
63
  loadWorldState,
60
64
  on,
package/dist/sentry.js CHANGED
@@ -2,8 +2,8 @@ import {
2
2
  _stashTicketFromUrl,
3
3
  getUser,
4
4
  on
5
- } from "./chunk-EM5TVVSD.js";
6
- import "./chunk-VPIQVRVS.js";
5
+ } from "./chunk-KEPAMDTE.js";
6
+ import "./chunk-MJPLBT3T.js";
7
7
 
8
8
  // src/sentry.ts
9
9
  import * as Sentry from "@sentry/browser";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@genex-ai/embed-sdk",
3
- "version": "0.24.3",
3
+ "version": "0.26.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, and soft-trust leaderboards.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",