@openartifactsai/runtime 0.0.0-stage → 0.23.0-rc.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/src/sample.js ADDED
@@ -0,0 +1,570 @@
1
+ /**
2
+ * The editor runtime's `sample` capability: a built-in editor asks the person's model for text, as a page does with
3
+ * `openArtifacts.use("sample")`. The function a page gets and the one an editor gets behave alike (the shapes and the
4
+ * checks are `@openartifactsai/protocol/sample`'s): `sample(input, options)`, `sample.json(...)`, `sample.limits()`, and
5
+ * one plain `{code, message, text?}` object for every failure.
6
+ *
7
+ * Underneath, a call travels by a {@link SampleTransport}: straight to the type server (`_api/sample`, an NDJSON
8
+ * stream), or, inside the Shell, through its broker, which runs the same HTTP transport on the page's behalf. The
9
+ * transport resolves each call with its last event (`done` or `error`) instead of rejecting, so a code, and the text a
10
+ * failure keeps, cross the broker unchanged; the events before it (`wait`, `delta`, `tool`) come through `onEvent`.
11
+ *
12
+ * Editors send no images: a call that passes some is refused `images_unavailable`.
13
+ */
14
+ import { MODEL_TIERS, SAMPLE_ACKED_WAIT_MS, SAMPLE_ERROR_CODES, SAMPLE_MAX_PROMPT_BYTES, SAMPLE_MAX_TOOL_RESULT_BYTES, SAMPLE_REPLY_BUDGET_MS, SAMPLE_TOOL_EXECUTE_MS, normalizeSampleCache, parseSampleJson, sampleInputBytes, sampleInputProblem, sampleToolsProblem, } from '@openartifactsai/protocol/sample';
15
+ import { readLines } from '@openartifactsai/protocol/stream';
16
+ /** The transport methods, by the names the broker carries. */
17
+ export const SAMPLE_TRANSPORT_METHODS = ['start', 'toolResults', 'cancel', 'readLimits', 'readState'];
18
+ const OPTIONS = new Set(['onText', 'signal', 'tools', 'images', 'modelTier', 'model', 'effort', 'fast', 'cache']);
19
+ const TIERS = new Set([...MODEL_TIERS, 'inherit']);
20
+ const EFFORTS = new Set(['low', 'medium', 'high']);
21
+ const CODES = new Set(SAMPLE_ERROR_CODES);
22
+ const STATES = new Set(['granted', 'denied', 'none']);
23
+ const utf8 = new TextEncoder();
24
+ const noted = new Set();
25
+ const isRecord = (v) => typeof v === 'object' && v !== null;
26
+ const isPlain = (v) => {
27
+ if (!isRecord(v) || Array.isArray(v))
28
+ return false;
29
+ const proto = Object.getPrototypeOf(v);
30
+ return proto === null || proto === Object.prototype;
31
+ };
32
+ const isSignal = (v) => typeof AbortSignal !== 'undefined' && v instanceof AbortSignal;
33
+ const bytesOf = (text) => utf8.encode(text).length;
34
+ /** A console note, once per text. */
35
+ function note(text) {
36
+ if (noted.has(text))
37
+ return;
38
+ noted.add(text);
39
+ console.warn(`openartifacts sample: ${text}`);
40
+ }
41
+ /** The one failure shape: a plain object. */
42
+ export function sampleFailure(code, message, text) {
43
+ return text ? { code, message, text } : { code, message };
44
+ }
45
+ /** A failure as it arrived (a stream's `error` event, a broker's error): a known code, else `upstream_error`. */
46
+ function failureOf(error, fallbackText) {
47
+ const e = isRecord(error) ? error : {};
48
+ const code = (typeof e.code === 'string' && CODES.has(e.code) ? e.code : 'upstream_error');
49
+ const message = typeof e.message === 'string' && e.message ? e.message : code;
50
+ const text = code === 'refused' ? undefined : typeof e.text === 'string' ? e.text : fallbackText;
51
+ return sampleFailure(code, message, text || undefined);
52
+ }
53
+ /** Every check a call goes through before it leaves: the call, ready, or why it is refused. */
54
+ function prepare(input, given, json) {
55
+ if (given !== undefined && given !== null && !isPlain(given))
56
+ return sampleFailure('invalid_request', 'options: a plain object such as {onText, signal, modelTier}.');
57
+ const options = given ?? {};
58
+ const unknown = Object.keys(options).filter((k) => !OPTIONS.has(k));
59
+ if (unknown.length)
60
+ note(`${unknown.map((k) => `options.${k}`).join(', ')} ${unknown.length > 1 ? 'are not options' : 'is not an option'}; ignored.`);
61
+ let signal = null;
62
+ if (options.signal !== undefined) {
63
+ if (!isSignal(options.signal)) {
64
+ const controller = isRecord(options.signal) && isSignal(options.signal.signal);
65
+ return sampleFailure('invalid_request', controller ? 'options.signal: pass controller.signal, not the AbortController.' : 'options.signal: an AbortSignal.');
66
+ }
67
+ signal = options.signal;
68
+ if (signal.aborted)
69
+ return sampleFailure('cancelled', 'The signal was aborted before the call was sent.');
70
+ }
71
+ if (options.onText !== undefined && typeof options.onText !== 'function')
72
+ return sampleFailure('invalid_request', 'options.onText: a function.');
73
+ const modelTier = options.modelTier === undefined ? 'default' : options.modelTier;
74
+ if (typeof modelTier !== 'string' || !TIERS.has(modelTier))
75
+ return sampleFailure('invalid_request', 'options.modelTier: "default", "complex", "quick" or "inherit".');
76
+ const inputProblem = sampleInputProblem(input);
77
+ if (inputProblem)
78
+ return sampleFailure('invalid_request', inputProblem);
79
+ if (sampleInputBytes(input) > SAMPLE_MAX_PROMPT_BYTES)
80
+ return sampleFailure('prompt_too_large', `input: at most ${SAMPLE_MAX_PROMPT_BYTES} bytes of text.`);
81
+ const wire = {};
82
+ const tools = new Map();
83
+ if (options.tools !== undefined) {
84
+ const problem = sampleToolsProblem(options.tools);
85
+ if (problem)
86
+ return sampleFailure('invalid_request', problem);
87
+ const list = options.tools;
88
+ for (let i = 0; i < list.length; i++) {
89
+ const tool = list[i];
90
+ if (typeof tool.execute !== 'function')
91
+ return sampleFailure('invalid_request', `tools[${i}].execute: a function, run here when the model calls the tool.`);
92
+ const spec = { name: tool.name, description: tool.description };
93
+ if (tool.inputSchema !== undefined)
94
+ spec.inputSchema = JSON.parse(JSON.stringify(tool.inputSchema));
95
+ tools.set(spec.name, { spec, execute: tool.execute });
96
+ }
97
+ if (tools.size)
98
+ wire.tools = [...tools.values()].map((t) => t.spec);
99
+ }
100
+ const cache = normalizeSampleCache(options.cache, tools.size > 0);
101
+ if ('problem' in cache)
102
+ return sampleFailure('invalid_request', cache.problem);
103
+ wire.cache = cache.cache;
104
+ if (options.model !== undefined) {
105
+ if (modelTier === 'inherit')
106
+ note('options.model is ignored with modelTier "inherit".');
107
+ else if (typeof options.model === 'string' && options.model.trim())
108
+ wire.model = options.model.trim();
109
+ else
110
+ note('options.model: a model id string; ignored.');
111
+ }
112
+ if (options.effort !== undefined) {
113
+ if (typeof options.effort === 'string' && EFFORTS.has(options.effort))
114
+ wire.effort = options.effort;
115
+ else
116
+ note('options.effort: "low", "medium" or "high"; ignored.');
117
+ }
118
+ if (options.fast !== undefined && options.fast !== null) {
119
+ if (options.fast === 'auto' || options.fast === false)
120
+ wire.fast = options.fast;
121
+ else
122
+ note('options.fast: "auto" or false; ignored.');
123
+ }
124
+ if (json)
125
+ wire.format = 'json';
126
+ if (options.images !== undefined) {
127
+ const given = options.images;
128
+ const count = typeof Blob !== 'undefined' && given instanceof Blob ? 1 : Array.isArray(given) ? given.length : isRecord(given) && typeof given.length === 'number' ? given.length : -1;
129
+ if (count < 0)
130
+ return sampleFailure('invalid_request', 'options.images: a Blob or File, or a list of them.');
131
+ if (count > 0)
132
+ return sampleFailure('images_unavailable', 'An editor cannot send images with sample.');
133
+ }
134
+ return {
135
+ input: input,
136
+ modelTier: modelTier,
137
+ options: wire,
138
+ tools,
139
+ onText: typeof options.onText === 'function' ? options.onText : null,
140
+ signal,
141
+ };
142
+ }
143
+ /** A tool's return value as its result: a string, or JSON; never over the size limit. */
144
+ function encodeResult(name, value) {
145
+ const tooLarge = (bytes) => {
146
+ note(`tool ${name} returned ${bytes} bytes; at most ${SAMPLE_MAX_TOOL_RESULT_BYTES} go back to the model.`);
147
+ return { content: `Error: result too large (${bytes} bytes, at most ${SAMPLE_MAX_TOOL_RESULT_BYTES}); return less.`, isError: true };
148
+ };
149
+ if (typeof value === 'string') {
150
+ const bytes = bytesOf(value);
151
+ return bytes > SAMPLE_MAX_TOOL_RESULT_BYTES ? tooLarge(bytes) : { content: value };
152
+ }
153
+ if (value === undefined)
154
+ return { content: '(no return value)' };
155
+ let text;
156
+ try {
157
+ text = JSON.stringify(value);
158
+ }
159
+ catch (error) {
160
+ note(`tool ${name} returned a value that is not JSON (${error?.message ?? error}).`);
161
+ }
162
+ if (text === undefined)
163
+ return { content: 'Error: the result cannot be sent as JSON; return a string or plain data.', isError: true };
164
+ const bytes = bytesOf(text);
165
+ return bytes > SAMPLE_MAX_TOOL_RESULT_BYTES ? tooLarge(bytes) : { content: text };
166
+ }
167
+ /** A throw as its result: `Error: <message>`, within the size limit. */
168
+ function thrownResult(name, error) {
169
+ console.warn(`openartifacts sample: tool ${name} threw:`, error);
170
+ const message = isRecord(error) && typeof error.message === 'string' ? error.message : String(error);
171
+ let content = `Error: ${message}`;
172
+ while (bytesOf(content) > SAMPLE_MAX_TOOL_RESULT_BYTES)
173
+ content = content.slice(0, Math.floor(content.length * 0.9));
174
+ return { content, isError: true };
175
+ }
176
+ /** A per-load prefix plus a counter. */
177
+ function idMaker() {
178
+ const prefix = Math.random().toString(36).slice(2, 10);
179
+ let seq = 0;
180
+ return () => `e${prefix}${(++seq).toString(36)}`;
181
+ }
182
+ /** The editor's `sample` capability over `transport`. */
183
+ export function createSampleFunction(transport, settings = {}) {
184
+ const budget = settings.budgetMs ?? SAMPLE_REPLY_BUDGET_MS;
185
+ const waitMs = settings.waitMs ?? SAMPLE_ACKED_WAIT_MS;
186
+ const nextId = idMaker();
187
+ function call(input, options, json) {
188
+ return new Promise((resolve, reject) => {
189
+ const ready = prepare(input, options, json);
190
+ if ('code' in ready)
191
+ return reject(ready);
192
+ const { signal, onText, tools } = ready;
193
+ const id = nextId();
194
+ let sent = false;
195
+ let settled = false;
196
+ /** Everything streamed so far, and what `onText` last carried (the same once the text is not blank). */
197
+ let text = '';
198
+ let shown = '';
199
+ /** Where the text of the last round starts (after the last tool round): what `json` reads. */
200
+ let lastRound = 0;
201
+ let timer = null;
202
+ let off = null;
203
+ const toolControllers = new Set();
204
+ const stopTimer = () => {
205
+ if (timer)
206
+ clearTimeout(timer);
207
+ timer = null;
208
+ };
209
+ const settle = () => {
210
+ if (settled)
211
+ return false;
212
+ settled = true;
213
+ stopTimer();
214
+ off?.();
215
+ off = null;
216
+ signal?.removeEventListener('abort', onAbort);
217
+ for (const c of toolControllers)
218
+ c.abort(new Error('The sample call ended.'));
219
+ toolControllers.clear();
220
+ return true;
221
+ };
222
+ const fail = (error) => {
223
+ if (settle())
224
+ reject(error);
225
+ };
226
+ const end = (code, message) => {
227
+ if (settled)
228
+ return;
229
+ if (sent)
230
+ void transport.cancel(id).catch(() => undefined);
231
+ fail(sampleFailure(code, message, shown || undefined));
232
+ };
233
+ function onAbort() {
234
+ end('cancelled', 'The call was cancelled.');
235
+ }
236
+ signal?.addEventListener('abort', onAbort);
237
+ const arm = (ms) => {
238
+ stopTimer();
239
+ timer = setTimeout(() => end('upstream_error', 'sample did not answer in time.'), ms);
240
+ };
241
+ /** Calls `onText`, unless the call is over; its errors are the editor's own. */
242
+ const deliver = (update) => {
243
+ if (settled || !onText || signal?.aborted)
244
+ return;
245
+ try {
246
+ const out = onText(update);
247
+ if (isRecord(out) && typeof out.then === 'function')
248
+ out.then(undefined, (error) => console.error('openartifacts sample: onText rejected:', error));
249
+ }
250
+ catch (error) {
251
+ console.error('openartifacts sample: onText threw:', error);
252
+ }
253
+ };
254
+ const show = () => {
255
+ if (!text.trim() || text.length <= shown.length)
256
+ return;
257
+ const delta = text.slice(shown.length);
258
+ shown = text;
259
+ deliver({ text, delta });
260
+ };
261
+ const runTools = (calls) => {
262
+ const list = Array.isArray(calls) ? calls.filter((c) => isRecord(c) && typeof c.id === 'string' && typeof c.name === 'string') : [];
263
+ // The time a tool takes is not the host's: no timer until the results are sent.
264
+ stopTimer();
265
+ lastRound = text.length;
266
+ const runOne = (c) => new Promise((done) => {
267
+ const tool = tools.get(c.name);
268
+ if (!tool) {
269
+ note(`the model called ${c.name}, which is not in this call's tools.`);
270
+ const offered = [...tools.keys()].join(', ') || 'none';
271
+ done({ id: c.id, content: `Error: no tool named "${c.name.slice(0, 128)}"; this call offers: ${offered}.`, isError: true });
272
+ return;
273
+ }
274
+ const controller = new AbortController();
275
+ toolControllers.add(controller);
276
+ let over = false;
277
+ const finish = (result) => {
278
+ if (over)
279
+ return;
280
+ over = true;
281
+ clearTimeout(limit);
282
+ toolControllers.delete(controller);
283
+ done({ id: c.id, ...result });
284
+ };
285
+ const limit = setTimeout(() => {
286
+ controller.abort(new Error(`${c.name} took over ${SAMPLE_TOOL_EXECUTE_MS / 1000} s.`));
287
+ finish({ content: `Error: ${c.name} did not finish within ${SAMPLE_TOOL_EXECUTE_MS / 1000} s.`, isError: true });
288
+ }, SAMPLE_TOOL_EXECUTE_MS);
289
+ controller.signal.addEventListener('abort', () => clearTimeout(limit), { once: true });
290
+ let out;
291
+ try {
292
+ out = tool.execute(isRecord(c.input) && !Array.isArray(c.input) ? c.input : {}, { signal: controller.signal });
293
+ }
294
+ catch (error) {
295
+ finish(thrownResult(c.name, error));
296
+ return;
297
+ }
298
+ Promise.resolve(out).then((value) => finish(encodeResult(c.name, value)), (error) => finish(thrownResult(c.name, error)));
299
+ });
300
+ void Promise.all(list.map(runOne)).then(async (results) => {
301
+ if (settled)
302
+ return;
303
+ const taken = await transport.toolResults(id, results).catch(() => false);
304
+ if (settled)
305
+ return;
306
+ if (!taken)
307
+ return end('upstream_error', 'The tool results could not be sent.');
308
+ arm(budget);
309
+ });
310
+ };
311
+ const done = (result) => {
312
+ if (typeof result.text !== 'string')
313
+ return fail(sampleFailure('upstream_error', 'The answer was not one.', shown || undefined));
314
+ const final = result.text;
315
+ if (!final.trim())
316
+ return fail(sampleFailure('empty_completion', 'The model wrote no text.'));
317
+ if (!final.startsWith(shown))
318
+ return fail(sampleFailure('upstream_error', 'The answer does not continue what had streamed.', shown || undefined));
319
+ if (final.length > shown.length) {
320
+ text = final;
321
+ show();
322
+ if (settled)
323
+ return;
324
+ }
325
+ const truncated = result.truncated === true;
326
+ if (json) {
327
+ if (truncated)
328
+ return fail(sampleFailure('invalid_json', 'The reply was cut short before its JSON was complete.', final));
329
+ const parsed = parseSampleJson(lastRound > 0 && lastRound <= final.length ? final.slice(lastRound) : final);
330
+ if (!parsed.ok)
331
+ return fail(sampleFailure('invalid_json', 'The reply holds no JSON value.', final));
332
+ if (settle())
333
+ resolve(parsed.value);
334
+ return;
335
+ }
336
+ const tier = typeof result.modelTierApplied === 'string' && MODEL_TIERS.includes(result.modelTierApplied) ? result.modelTierApplied : 'default';
337
+ const out = { text: final, truncated, modelTierApplied: tier };
338
+ if (typeof result.modelApplied === 'string')
339
+ out.modelApplied = result.modelApplied;
340
+ if (settle())
341
+ resolve(out);
342
+ };
343
+ const onEvent = (event) => {
344
+ if (settled)
345
+ return;
346
+ if (event.t === 'wait' || event.t === 'ask')
347
+ return arm(waitMs);
348
+ if (event.t === 'delta') {
349
+ arm(budget);
350
+ if (typeof event.text !== 'string' || !event.text)
351
+ return;
352
+ text += event.text;
353
+ show();
354
+ }
355
+ else if (event.t === 'tool')
356
+ runTools(event.calls);
357
+ };
358
+ queueMicrotask(() => {
359
+ if (settled)
360
+ return;
361
+ if (signal?.aborted)
362
+ return fail(sampleFailure('cancelled', 'The call was cancelled before it was sent.'));
363
+ off = transport.onEvent((message) => {
364
+ if (message.call === id)
365
+ onEvent(message.event);
366
+ });
367
+ sent = true;
368
+ arm(budget);
369
+ transport.start(id, ready.input, ready.modelTier, ready.options).then((last) => {
370
+ if (settled)
371
+ return;
372
+ if (isRecord(last) && last.t === 'done')
373
+ done(last);
374
+ else
375
+ fail(failureOf(last, shown));
376
+ }, (error) => fail(failureOf(error, shown)));
377
+ });
378
+ });
379
+ }
380
+ const sample = ((input, options) => call(input, options, false));
381
+ sample.json = ((input, options) => call(input, options, true));
382
+ sample.limits = async () => {
383
+ let answer;
384
+ try {
385
+ answer = await transport.readLimits();
386
+ }
387
+ catch (error) {
388
+ throw failureOf(error);
389
+ }
390
+ if (!isRecord(answer) || 'error' in answer)
391
+ throw failureOf(isRecord(answer) ? answer.error : null);
392
+ // An editor sends no images.
393
+ const out = { ...answer };
394
+ delete out.images;
395
+ return out;
396
+ };
397
+ sample.state = async () => {
398
+ try {
399
+ const state = await transport.readState();
400
+ return STATES.has(state) ? state : 'none';
401
+ }
402
+ catch {
403
+ return 'none';
404
+ }
405
+ };
406
+ sample.request = async () => {
407
+ const asked = await settings.ask?.().catch(() => null);
408
+ return asked && STATES.has(asked) ? asked : sample.state();
409
+ };
410
+ return sample;
411
+ }
412
+ /** `sample` with its transport's methods on it (not enumerable), as the Shell's broker calls them. */
413
+ export function withTransport(sample, transport) {
414
+ for (const name of [...SAMPLE_TRANSPORT_METHODS, 'onEvent']) {
415
+ Object.defineProperty(sample, name, { value: transport[name].bind(transport), enumerable: false });
416
+ }
417
+ return sample;
418
+ }
419
+ /** The transport straight to the type server: `POST _api/sample` streams the call's events. */
420
+ export function createHttpSampleTransport(options) {
421
+ const { url, client, routes } = options;
422
+ const listeners = new Set();
423
+ const calls = new Map();
424
+ const emit = (call, event) => {
425
+ for (const listener of [...listeners]) {
426
+ try {
427
+ listener({ call, event });
428
+ }
429
+ catch (error) {
430
+ queueMicrotask(() => {
431
+ throw error;
432
+ });
433
+ }
434
+ }
435
+ };
436
+ const errorEvent = (code, message) => ({ t: 'error', code, message });
437
+ /** The failure a refused request means. */
438
+ const refusal = async (response) => {
439
+ const body = (await response.json().catch(() => null));
440
+ const message = typeof body?.message === 'string' ? body.message : `HTTP ${response.status}`;
441
+ // An older type server has no such route; a guest may not use the owner's models.
442
+ if (response.status === 404)
443
+ return errorEvent('capability_removed', message);
444
+ if (response.status === 401 || response.status === 403)
445
+ return errorEvent('capability_disabled', message);
446
+ return errorEvent('upstream_error', message);
447
+ };
448
+ return {
449
+ async start(call, input, modelTier, wire) {
450
+ const abort = new AbortController();
451
+ const entry = { abort };
452
+ calls.set(call, entry);
453
+ try {
454
+ let response;
455
+ try {
456
+ response = await fetch(url(routes.sample), {
457
+ method: 'POST',
458
+ headers: { 'content-type': 'application/json' },
459
+ body: JSON.stringify({ input, modelTier, options: wire, client }),
460
+ signal: abort.signal,
461
+ });
462
+ }
463
+ catch (error) {
464
+ if (abort.signal.aborted)
465
+ return errorEvent('cancelled', 'The call was cancelled.');
466
+ return errorEvent('upstream_error', `The call could not be sent (${error?.message ?? error}).`);
467
+ }
468
+ if (!response.ok)
469
+ return await refusal(response);
470
+ if (!response.body)
471
+ return errorEvent('upstream_error', 'The answer had no body.');
472
+ const take = (line) => {
473
+ let event;
474
+ try {
475
+ event = JSON.parse(line);
476
+ }
477
+ catch {
478
+ return null;
479
+ }
480
+ if (!isRecord(event) || typeof event.t !== 'string')
481
+ return null;
482
+ if (event.t === 'done' || event.t === 'error')
483
+ return event;
484
+ if (event.t === 'start') {
485
+ if (typeof event.sample === 'string')
486
+ entry.sample = event.sample;
487
+ return null;
488
+ }
489
+ if (event.t === 'tool') {
490
+ if (typeof event.sample === 'string')
491
+ entry.sample = event.sample;
492
+ if (typeof event.round === 'number')
493
+ entry.round = event.round;
494
+ }
495
+ if (event.t === 'wait' || event.t === 'ask' || event.t === 'delta' || event.t === 'tool')
496
+ emit(call, event);
497
+ return null;
498
+ };
499
+ try {
500
+ for await (const each of readLines(response.body)) {
501
+ const line = each.trim();
502
+ const last = line ? take(line) : null;
503
+ if (last)
504
+ return last;
505
+ }
506
+ return errorEvent('upstream_error', 'The model call ended without an answer.');
507
+ }
508
+ catch (error) {
509
+ if (abort.signal.aborted)
510
+ return errorEvent('cancelled', 'The call was cancelled.');
511
+ return errorEvent('upstream_error', `The answer broke off (${error?.message ?? error}).`);
512
+ }
513
+ }
514
+ finally {
515
+ calls.delete(call);
516
+ }
517
+ },
518
+ async toolResults(call, results) {
519
+ const entry = calls.get(call);
520
+ if (!entry?.sample || !entry.round)
521
+ return false;
522
+ try {
523
+ const response = await fetch(url(routes.sampleTool), {
524
+ method: 'POST',
525
+ headers: { 'content-type': 'application/json' },
526
+ body: JSON.stringify({ sample: entry.sample, round: entry.round, results }),
527
+ });
528
+ if (!response.ok)
529
+ return false;
530
+ const body = (await response.json().catch(() => null));
531
+ return body?.ok === true;
532
+ }
533
+ catch {
534
+ return false;
535
+ }
536
+ },
537
+ async cancel(call) {
538
+ calls.get(call)?.abort.abort();
539
+ },
540
+ async readLimits() {
541
+ try {
542
+ const response = await fetch(url(routes.sampleLimits, { client }), { cache: 'no-store' });
543
+ if (!response.ok) {
544
+ const last = await refusal(response);
545
+ return { error: sampleFailure(last.code, last.message) };
546
+ }
547
+ return (await response.json());
548
+ }
549
+ catch (error) {
550
+ return { error: sampleFailure('upstream_error', `The limits could not be read (${error?.message ?? error}).`) };
551
+ }
552
+ },
553
+ async readState() {
554
+ try {
555
+ const response = await fetch(url(routes.sampleState), { cache: 'no-store' });
556
+ if (!response.ok)
557
+ return 'none';
558
+ const body = (await response.json().catch(() => null));
559
+ return typeof body?.state === 'string' && STATES.has(body.state) ? body.state : 'none';
560
+ }
561
+ catch {
562
+ return 'none';
563
+ }
564
+ },
565
+ onEvent(listener) {
566
+ listeners.add(listener);
567
+ return () => void listeners.delete(listener);
568
+ },
569
+ };
570
+ }