@smoothbuilder/smoothagent-agent-server 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3402 @@
1
+ import {
2
+ KNOWN_ERROR_CODES,
3
+ newMessageId,
4
+ serverEnv,
5
+ systemClock,
6
+ untilStored,
7
+ uuidv7
8
+ } from "./chunk-T5FJM7CV.js";
9
+ import {
10
+ __export
11
+ } from "./chunk-PZ5AY32C.js";
12
+
13
+ // ../core-live/src/auth.ts
14
+ var SmoothAgentAuthError = class extends Error {
15
+ constructor(reason, message = `unauthorized (${reason})`) {
16
+ super(message);
17
+ this.reason = reason;
18
+ this.name = "SmoothAgentAuthError";
19
+ }
20
+ };
21
+ function jwtExpiresAt(token) {
22
+ const part = token.split(".")[1];
23
+ if (!part) return null;
24
+ try {
25
+ const json = JSON.parse(decodeBase64Url(part));
26
+ return typeof json.exp === "number" ? json.exp * 1e3 : null;
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+ function decodeBase64Url(s) {
32
+ const b64 = s.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((s.length + 3) % 4);
33
+ if (typeof atob === "function") {
34
+ const bin = atob(b64);
35
+ const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));
36
+ return new TextDecoder().decode(bytes);
37
+ }
38
+ return Buffer.from(b64, "base64").toString("utf8");
39
+ }
40
+ var TokenSource = class {
41
+ constructor(o) {
42
+ this.o = o;
43
+ if (!o.token && !o.getToken) throw new Error("SmoothAgent: passe `token` ou `getToken`");
44
+ this.current = o.token ?? null;
45
+ this.skewMs = o.skewMs ?? 6e4;
46
+ }
47
+ current;
48
+ inflight = null;
49
+ stale = false;
50
+ revoked = false;
51
+ listeners = /* @__PURE__ */ new Set();
52
+ skewMs;
53
+ /** Token válido agora (renova se precisar). Rejeita com SmoothAgentAuthError('revoked') depois de revogado. */
54
+ async get() {
55
+ if (this.revoked) throw new SmoothAgentAuthError("revoked");
56
+ if (this.current && !this.stale && !this.nearExpiry(this.current)) return this.current;
57
+ if (!this.o.getToken) {
58
+ if (this.current && !this.stale) return this.current;
59
+ throw new SmoothAgentAuthError("expired");
60
+ }
61
+ return this.refresh();
62
+ }
63
+ /** O servidor disse `expired`: a próxima `get()` renova. */
64
+ invalidate() {
65
+ this.stale = true;
66
+ }
67
+ /** O servidor disse `revoked`: nada de renovar. */
68
+ markRevoked() {
69
+ this.revoked = true;
70
+ }
71
+ get isRevoked() {
72
+ return this.revoked;
73
+ }
74
+ onRenew(cb) {
75
+ this.listeners.add(cb);
76
+ return () => this.listeners.delete(cb);
77
+ }
78
+ nearExpiry(token) {
79
+ const exp = jwtExpiresAt(token);
80
+ return exp !== null && exp - this.o.clock.now() < this.skewMs;
81
+ }
82
+ refresh() {
83
+ if (this.inflight) return this.inflight;
84
+ const prev = this.current;
85
+ this.inflight = this.o.getToken().then((t) => {
86
+ this.current = t;
87
+ this.stale = false;
88
+ if (t !== prev) for (const l of this.listeners) l(t);
89
+ return t;
90
+ }).finally(() => {
91
+ this.inflight = null;
92
+ });
93
+ return this.inflight;
94
+ }
95
+ };
96
+ function authedFetch(source, base = fetch) {
97
+ return async (input, init) => {
98
+ const call = async (token) => {
99
+ const headers = new Headers(init?.headers);
100
+ headers.set("Authorization", `Bearer ${token}`);
101
+ return base(input, { ...init, headers });
102
+ };
103
+ let res = await call(await source.get());
104
+ if (res.status !== 401) return res;
105
+ const reason = await reasonOf(res);
106
+ if (reason === "revoked") {
107
+ source.markRevoked();
108
+ return res;
109
+ }
110
+ if (reason !== "expired") return res;
111
+ source.invalidate();
112
+ res = await call(await source.get());
113
+ if (res.status === 401 && await reasonOf(res) === "revoked") source.markRevoked();
114
+ return res;
115
+ };
116
+ }
117
+ async function reasonOf(res) {
118
+ try {
119
+ const body = await res.clone().json();
120
+ return body.error?.details?.reason;
121
+ } catch {
122
+ return void 0;
123
+ }
124
+ }
125
+
126
+ // ../core-live/src/wasm/live.js
127
+ var live_exports = {};
128
+ __export(live_exports, {
129
+ LiveFeed: () => LiveFeed,
130
+ LiveSession: () => LiveSession,
131
+ LiveWatch: () => LiveWatch,
132
+ Reducer: () => Reducer,
133
+ default: () => live_default,
134
+ error_code: () => error_code,
135
+ error_codes: () => error_codes,
136
+ initSync: () => initSync,
137
+ needs_provider: () => needs_provider,
138
+ to_ms: () => to_ms
139
+ });
140
+ var wasm;
141
+ var cachedTextDecoder = typeof TextDecoder !== "undefined" ? new TextDecoder("utf-8", { ignoreBOM: true, fatal: true }) : { decode: () => {
142
+ throw Error("TextDecoder not available");
143
+ } };
144
+ if (typeof TextDecoder !== "undefined") {
145
+ cachedTextDecoder.decode();
146
+ }
147
+ var cachedUint8ArrayMemory0 = null;
148
+ function getUint8ArrayMemory0() {
149
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
150
+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
151
+ }
152
+ return cachedUint8ArrayMemory0;
153
+ }
154
+ function getStringFromWasm0(ptr, len) {
155
+ ptr = ptr >>> 0;
156
+ return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
157
+ }
158
+ var heap = new Array(128).fill(void 0);
159
+ heap.push(void 0, null, true, false);
160
+ var heap_next = heap.length;
161
+ function addHeapObject(obj) {
162
+ if (heap_next === heap.length) heap.push(heap.length + 1);
163
+ const idx = heap_next;
164
+ heap_next = heap[idx];
165
+ heap[idx] = obj;
166
+ return idx;
167
+ }
168
+ function to_ms(epoch, now) {
169
+ const ret = wasm.to_ms(epoch, now);
170
+ return ret;
171
+ }
172
+ var WASM_VECTOR_LEN = 0;
173
+ var cachedTextEncoder = typeof TextEncoder !== "undefined" ? new TextEncoder("utf-8") : { encode: () => {
174
+ throw Error("TextEncoder not available");
175
+ } };
176
+ var encodeString = typeof cachedTextEncoder.encodeInto === "function" ? function(arg, view) {
177
+ return cachedTextEncoder.encodeInto(arg, view);
178
+ } : function(arg, view) {
179
+ const buf = cachedTextEncoder.encode(arg);
180
+ view.set(buf);
181
+ return {
182
+ read: arg.length,
183
+ written: buf.length
184
+ };
185
+ };
186
+ function passStringToWasm0(arg, malloc, realloc) {
187
+ if (realloc === void 0) {
188
+ const buf = cachedTextEncoder.encode(arg);
189
+ const ptr2 = malloc(buf.length, 1) >>> 0;
190
+ getUint8ArrayMemory0().subarray(ptr2, ptr2 + buf.length).set(buf);
191
+ WASM_VECTOR_LEN = buf.length;
192
+ return ptr2;
193
+ }
194
+ let len = arg.length;
195
+ let ptr = malloc(len, 1) >>> 0;
196
+ const mem = getUint8ArrayMemory0();
197
+ let offset = 0;
198
+ for (; offset < len; offset++) {
199
+ const code = arg.charCodeAt(offset);
200
+ if (code > 127) break;
201
+ mem[ptr + offset] = code;
202
+ }
203
+ if (offset !== len) {
204
+ if (offset !== 0) {
205
+ arg = arg.slice(offset);
206
+ }
207
+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
208
+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
209
+ const ret = encodeString(arg, view);
210
+ offset += ret.written;
211
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
212
+ }
213
+ WASM_VECTOR_LEN = offset;
214
+ return ptr;
215
+ }
216
+ var cachedDataViewMemory0 = null;
217
+ function getDataViewMemory0() {
218
+ if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || cachedDataViewMemory0.buffer.detached === void 0 && cachedDataViewMemory0.buffer !== wasm.memory.buffer) {
219
+ cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
220
+ }
221
+ return cachedDataViewMemory0;
222
+ }
223
+ function error_code(c) {
224
+ let deferred2_0;
225
+ let deferred2_1;
226
+ try {
227
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
228
+ const ptr0 = passStringToWasm0(c, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
229
+ const len0 = WASM_VECTOR_LEN;
230
+ wasm.error_code(retptr, ptr0, len0);
231
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
232
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
233
+ deferred2_0 = r0;
234
+ deferred2_1 = r1;
235
+ return getStringFromWasm0(r0, r1);
236
+ } finally {
237
+ wasm.__wbindgen_add_to_stack_pointer(16);
238
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
239
+ }
240
+ }
241
+ function error_codes() {
242
+ let deferred1_0;
243
+ let deferred1_1;
244
+ try {
245
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
246
+ wasm.error_codes(retptr);
247
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
248
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
249
+ deferred1_0 = r0;
250
+ deferred1_1 = r1;
251
+ return getStringFromWasm0(r0, r1);
252
+ } finally {
253
+ wasm.__wbindgen_add_to_stack_pointer(16);
254
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
255
+ }
256
+ }
257
+ function getObject(idx) {
258
+ return heap[idx];
259
+ }
260
+ function dropObject(idx) {
261
+ if (idx < 132) return;
262
+ heap[idx] = heap_next;
263
+ heap_next = idx;
264
+ }
265
+ function takeObject(idx) {
266
+ const ret = getObject(idx);
267
+ dropObject(idx);
268
+ return ret;
269
+ }
270
+ function needs_provider(timeline_json, queue_json, refusal_json) {
271
+ let deferred5_0;
272
+ let deferred5_1;
273
+ try {
274
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
275
+ const ptr0 = passStringToWasm0(timeline_json, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
276
+ const len0 = WASM_VECTOR_LEN;
277
+ const ptr1 = passStringToWasm0(queue_json, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
278
+ const len1 = WASM_VECTOR_LEN;
279
+ const ptr2 = passStringToWasm0(refusal_json, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
280
+ const len2 = WASM_VECTOR_LEN;
281
+ wasm.needs_provider(retptr, ptr0, len0, ptr1, len1, ptr2, len2);
282
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
283
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
284
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
285
+ var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
286
+ var ptr4 = r0;
287
+ var len4 = r1;
288
+ if (r3) {
289
+ ptr4 = 0;
290
+ len4 = 0;
291
+ throw takeObject(r2);
292
+ }
293
+ deferred5_0 = ptr4;
294
+ deferred5_1 = len4;
295
+ return getStringFromWasm0(ptr4, len4);
296
+ } finally {
297
+ wasm.__wbindgen_add_to_stack_pointer(16);
298
+ wasm.__wbindgen_export_2(deferred5_0, deferred5_1, 1);
299
+ }
300
+ }
301
+ var LiveFeedFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
302
+ }, unregister: () => {
303
+ } } : new FinalizationRegistry((ptr) => wasm.__wbg_livefeed_free(ptr >>> 0, 1));
304
+ var LiveFeed = class {
305
+ __destroy_into_raw() {
306
+ const ptr = this.__wbg_ptr;
307
+ this.__wbg_ptr = 0;
308
+ LiveFeedFinalization.unregister(this);
309
+ return ptr;
310
+ }
311
+ free() {
312
+ const ptr = this.__destroy_into_raw();
313
+ wasm.__wbg_livefeed_free(ptr, 0);
314
+ }
315
+ /**
316
+ * @param {number} now
317
+ * @param {boolean} online
318
+ * @param {boolean} visible
319
+ * @param {number} rand
320
+ * @param {number} conn
321
+ * @param {string} text
322
+ * @returns {string}
323
+ */
324
+ on_message(now, online, visible, rand, conn, text) {
325
+ let deferred2_0;
326
+ let deferred2_1;
327
+ try {
328
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
329
+ const ptr0 = passStringToWasm0(text, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
330
+ const len0 = WASM_VECTOR_LEN;
331
+ wasm.livefeed_on_message(retptr, this.__wbg_ptr, now, online, visible, rand, conn, ptr0, len0);
332
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
333
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
334
+ deferred2_0 = r0;
335
+ deferred2_1 = r1;
336
+ return getStringFromWasm0(r0, r1);
337
+ } finally {
338
+ wasm.__wbindgen_add_to_stack_pointer(16);
339
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
340
+ }
341
+ }
342
+ /**
343
+ * @param {number} _n
344
+ * @param {boolean} _o
345
+ * @param {boolean} _v
346
+ * @param {number} _r
347
+ * @param {number} _req
348
+ * @param {boolean} _ok
349
+ * @param {string} _s
350
+ * @returns {string}
351
+ */
352
+ on_snapshot(_n, _o, _v, _r, _req, _ok, _s) {
353
+ let deferred2_0;
354
+ let deferred2_1;
355
+ try {
356
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
357
+ const ptr0 = passStringToWasm0(_s, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
358
+ const len0 = WASM_VECTOR_LEN;
359
+ wasm.livefeed_on_probe(retptr, this.__wbg_ptr, _n, _o, _v, _r, _req, _ok, ptr0, len0);
360
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
361
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
362
+ deferred2_0 = r0;
363
+ deferred2_1 = r1;
364
+ return getStringFromWasm0(r0, r1);
365
+ } finally {
366
+ wasm.__wbindgen_add_to_stack_pointer(16);
367
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
368
+ }
369
+ }
370
+ /**
371
+ * @returns {number}
372
+ */
373
+ next_deadline() {
374
+ const ret = wasm.livefeed_next_deadline(this.__wbg_ptr);
375
+ return ret;
376
+ }
377
+ /**
378
+ * @param {number} now
379
+ * @param {boolean} online
380
+ * @param {boolean} visible
381
+ * @param {number} rand
382
+ * @param {number} conn
383
+ * @returns {string}
384
+ */
385
+ on_open_failed(now, online, visible, rand, conn) {
386
+ let deferred1_0;
387
+ let deferred1_1;
388
+ try {
389
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
390
+ wasm.livefeed_on_open_failed(retptr, this.__wbg_ptr, now, online, visible, rand, conn);
391
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
392
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
393
+ deferred1_0 = r0;
394
+ deferred1_1 = r1;
395
+ return getStringFromWasm0(r0, r1);
396
+ } finally {
397
+ wasm.__wbindgen_add_to_stack_pointer(16);
398
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
399
+ }
400
+ }
401
+ /**
402
+ * `config_json`: { url, agentId?, backoff? }
403
+ * @param {string} config_json
404
+ */
405
+ constructor(config_json) {
406
+ try {
407
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
408
+ const ptr0 = passStringToWasm0(config_json, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
409
+ const len0 = WASM_VECTOR_LEN;
410
+ wasm.livefeed_new(retptr, ptr0, len0);
411
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
412
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
413
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
414
+ if (r2) {
415
+ throw takeObject(r1);
416
+ }
417
+ this.__wbg_ptr = r0 >>> 0;
418
+ LiveFeedFinalization.register(this, this.__wbg_ptr, this);
419
+ return this;
420
+ } finally {
421
+ wasm.__wbindgen_add_to_stack_pointer(16);
422
+ }
423
+ }
424
+ /**
425
+ * @param {number} now
426
+ * @param {boolean} online
427
+ * @param {boolean} visible
428
+ * @param {number} rand
429
+ * @returns {string}
430
+ */
431
+ tick(now, online, visible, rand) {
432
+ let deferred1_0;
433
+ let deferred1_1;
434
+ try {
435
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
436
+ wasm.livefeed_tick(retptr, this.__wbg_ptr, now, online, visible, rand);
437
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
438
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
439
+ deferred1_0 = r0;
440
+ deferred1_1 = r1;
441
+ return getStringFromWasm0(r0, r1);
442
+ } finally {
443
+ wasm.__wbindgen_add_to_stack_pointer(16);
444
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
445
+ }
446
+ }
447
+ /**
448
+ * @param {number} now
449
+ * @param {boolean} online
450
+ * @param {boolean} visible
451
+ * @param {number} rand
452
+ * @param {string} _why
453
+ * @param {number} _away_ms
454
+ * @returns {string}
455
+ */
456
+ wake(now, online, visible, rand, _why, _away_ms) {
457
+ let deferred2_0;
458
+ let deferred2_1;
459
+ try {
460
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
461
+ const ptr0 = passStringToWasm0(_why, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
462
+ const len0 = WASM_VECTOR_LEN;
463
+ wasm.livefeed_wake(retptr, this.__wbg_ptr, now, online, visible, rand, ptr0, len0, _away_ms);
464
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
465
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
466
+ deferred2_0 = r0;
467
+ deferred2_1 = r1;
468
+ return getStringFromWasm0(r0, r1);
469
+ } finally {
470
+ wasm.__wbindgen_add_to_stack_pointer(16);
471
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
472
+ }
473
+ }
474
+ /**
475
+ * @param {number} now
476
+ * @param {boolean} online
477
+ * @param {boolean} visible
478
+ * @param {number} rand
479
+ * @returns {string}
480
+ */
481
+ close(now, online, visible, rand) {
482
+ let deferred1_0;
483
+ let deferred1_1;
484
+ try {
485
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
486
+ wasm.livefeed_close(retptr, this.__wbg_ptr, now, online, visible, rand);
487
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
488
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
489
+ deferred1_0 = r0;
490
+ deferred1_1 = r1;
491
+ return getStringFromWasm0(r0, r1);
492
+ } finally {
493
+ wasm.__wbindgen_add_to_stack_pointer(16);
494
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
495
+ }
496
+ }
497
+ /**
498
+ * @param {number} now
499
+ * @param {boolean} online
500
+ * @param {boolean} visible
501
+ * @param {number} rand
502
+ * @returns {string}
503
+ */
504
+ start(now, online, visible, rand) {
505
+ let deferred1_0;
506
+ let deferred1_1;
507
+ try {
508
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
509
+ wasm.livefeed_start(retptr, this.__wbg_ptr, now, online, visible, rand);
510
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
511
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
512
+ deferred1_0 = r0;
513
+ deferred1_1 = r1;
514
+ return getStringFromWasm0(r0, r1);
515
+ } finally {
516
+ wasm.__wbindgen_add_to_stack_pointer(16);
517
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
518
+ }
519
+ }
520
+ /**
521
+ * @returns {string}
522
+ */
523
+ status() {
524
+ let deferred1_0;
525
+ let deferred1_1;
526
+ try {
527
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
528
+ wasm.livefeed_status(retptr, this.__wbg_ptr);
529
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
530
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
531
+ deferred1_0 = r0;
532
+ deferred1_1 = r1;
533
+ return getStringFromWasm0(r0, r1);
534
+ } finally {
535
+ wasm.__wbindgen_add_to_stack_pointer(16);
536
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
537
+ }
538
+ }
539
+ /**
540
+ * @param {number} now
541
+ * @param {boolean} online
542
+ * @param {boolean} visible
543
+ * @param {number} rand
544
+ * @param {number} conn
545
+ * @returns {string}
546
+ */
547
+ on_open(now, online, visible, rand, conn) {
548
+ let deferred1_0;
549
+ let deferred1_1;
550
+ try {
551
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
552
+ wasm.livefeed_on_open(retptr, this.__wbg_ptr, now, online, visible, rand, conn);
553
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
554
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
555
+ deferred1_0 = r0;
556
+ deferred1_1 = r1;
557
+ return getStringFromWasm0(r0, r1);
558
+ } finally {
559
+ wasm.__wbindgen_add_to_stack_pointer(16);
560
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
561
+ }
562
+ }
563
+ /**
564
+ * @param {number} now
565
+ * @param {boolean} online
566
+ * @param {boolean} visible
567
+ * @param {number} rand
568
+ * @param {number} conn
569
+ * @param {number} code
570
+ * @param {string} reason
571
+ * @returns {string}
572
+ */
573
+ on_close(now, online, visible, rand, conn, code, reason) {
574
+ let deferred2_0;
575
+ let deferred2_1;
576
+ try {
577
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
578
+ const ptr0 = passStringToWasm0(reason, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
579
+ const len0 = WASM_VECTOR_LEN;
580
+ wasm.livefeed_on_close(retptr, this.__wbg_ptr, now, online, visible, rand, conn, code, ptr0, len0);
581
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
582
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
583
+ deferred2_0 = r0;
584
+ deferred2_1 = r1;
585
+ return getStringFromWasm0(r0, r1);
586
+ } finally {
587
+ wasm.__wbindgen_add_to_stack_pointer(16);
588
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
589
+ }
590
+ }
591
+ /**
592
+ * @param {number} _now
593
+ * @param {boolean} _online
594
+ * @param {boolean} _visible
595
+ * @param {number} _rand
596
+ * @param {number} _conn
597
+ * @returns {string}
598
+ */
599
+ on_error(_now, _online, _visible, _rand, _conn) {
600
+ let deferred1_0;
601
+ let deferred1_1;
602
+ try {
603
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
604
+ wasm.livefeed_on_error(retptr, this.__wbg_ptr, _now, _online, _visible, _rand, _conn);
605
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
606
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
607
+ deferred1_0 = r0;
608
+ deferred1_1 = r1;
609
+ return getStringFromWasm0(r0, r1);
610
+ } finally {
611
+ wasm.__wbindgen_add_to_stack_pointer(16);
612
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
613
+ }
614
+ }
615
+ /**
616
+ * @param {number} _n
617
+ * @param {boolean} _o
618
+ * @param {boolean} _v
619
+ * @param {number} _r
620
+ * @param {number} _req
621
+ * @param {boolean} _ok
622
+ * @param {string} _a
623
+ * @returns {string}
624
+ */
625
+ on_probe(_n, _o, _v, _r, _req, _ok, _a) {
626
+ let deferred2_0;
627
+ let deferred2_1;
628
+ try {
629
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
630
+ const ptr0 = passStringToWasm0(_a, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
631
+ const len0 = WASM_VECTOR_LEN;
632
+ wasm.livefeed_on_probe(retptr, this.__wbg_ptr, _n, _o, _v, _r, _req, _ok, ptr0, len0);
633
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
634
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
635
+ deferred2_0 = r0;
636
+ deferred2_1 = r1;
637
+ return getStringFromWasm0(r0, r1);
638
+ } finally {
639
+ wasm.__wbindgen_add_to_stack_pointer(16);
640
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
641
+ }
642
+ }
643
+ /**
644
+ * @param {number} _n
645
+ * @param {boolean} _o
646
+ * @param {boolean} _v
647
+ * @param {number} _r
648
+ * @param {number} _req
649
+ * @param {boolean} _ok
650
+ * @param {string} _e
651
+ * @param {number} _f
652
+ * @param {number} _t
653
+ * @returns {string}
654
+ */
655
+ on_range(_n, _o, _v, _r, _req, _ok, _e, _f, _t) {
656
+ let deferred2_0;
657
+ let deferred2_1;
658
+ try {
659
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
660
+ const ptr0 = passStringToWasm0(_e, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
661
+ const len0 = WASM_VECTOR_LEN;
662
+ wasm.livefeed_on_range(retptr, this.__wbg_ptr, _n, _o, _v, _r, _req, _ok, ptr0, len0, _f, _t);
663
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
664
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
665
+ deferred2_0 = r0;
666
+ deferred2_1 = r1;
667
+ return getStringFromWasm0(r0, r1);
668
+ } finally {
669
+ wasm.__wbindgen_add_to_stack_pointer(16);
670
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
671
+ }
672
+ }
673
+ /**
674
+ * @param {number} now
675
+ * @param {boolean} online
676
+ * @param {boolean} visible
677
+ * @param {number} rand
678
+ * @param {number} req
679
+ * @param {boolean} ok
680
+ * @param {string} token
681
+ * @returns {string}
682
+ */
683
+ on_token(now, online, visible, rand, req, ok, token) {
684
+ let deferred2_0;
685
+ let deferred2_1;
686
+ try {
687
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
688
+ const ptr0 = passStringToWasm0(token, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
689
+ const len0 = WASM_VECTOR_LEN;
690
+ wasm.livefeed_on_token(retptr, this.__wbg_ptr, now, online, visible, rand, req, ok, ptr0, len0);
691
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
692
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
693
+ deferred2_0 = r0;
694
+ deferred2_1 = r1;
695
+ return getStringFromWasm0(r0, r1);
696
+ } finally {
697
+ wasm.__wbindgen_add_to_stack_pointer(16);
698
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
699
+ }
700
+ }
701
+ };
702
+ var LiveSessionFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
703
+ }, unregister: () => {
704
+ } } : new FinalizationRegistry((ptr) => wasm.__wbg_livesession_free(ptr >>> 0, 1));
705
+ var LiveSession = class {
706
+ __destroy_into_raw() {
707
+ const ptr = this.__wbg_ptr;
708
+ this.__wbg_ptr = 0;
709
+ LiveSessionFinalization.unregister(this);
710
+ return ptr;
711
+ }
712
+ free() {
713
+ const ptr = this.__destroy_into_raw();
714
+ wasm.__wbg_livesession_free(ptr, 0);
715
+ }
716
+ /**
717
+ * @param {number} now
718
+ * @param {boolean} online
719
+ * @param {boolean} visible
720
+ * @param {number} rand
721
+ * @param {number} conn
722
+ * @param {string} text
723
+ * @returns {string}
724
+ */
725
+ on_message(now, online, visible, rand, conn, text) {
726
+ let deferred2_0;
727
+ let deferred2_1;
728
+ try {
729
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
730
+ const ptr0 = passStringToWasm0(text, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
731
+ const len0 = WASM_VECTOR_LEN;
732
+ wasm.livesession_on_message(retptr, this.__wbg_ptr, now, online, visible, rand, conn, ptr0, len0);
733
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
734
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
735
+ deferred2_0 = r0;
736
+ deferred2_1 = r1;
737
+ return getStringFromWasm0(r0, r1);
738
+ } finally {
739
+ wasm.__wbindgen_add_to_stack_pointer(16);
740
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
741
+ }
742
+ }
743
+ /**
744
+ * @param {number} now
745
+ * @param {boolean} online
746
+ * @param {boolean} visible
747
+ * @param {number} rand
748
+ * @param {number} req
749
+ * @param {boolean} ok
750
+ * @param {string} snapshot_json
751
+ * @returns {string}
752
+ */
753
+ on_snapshot(now, online, visible, rand, req, ok, snapshot_json) {
754
+ let deferred2_0;
755
+ let deferred2_1;
756
+ try {
757
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
758
+ const ptr0 = passStringToWasm0(snapshot_json, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
759
+ const len0 = WASM_VECTOR_LEN;
760
+ wasm.livesession_on_snapshot(retptr, this.__wbg_ptr, now, online, visible, rand, req, ok, ptr0, len0);
761
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
762
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
763
+ deferred2_0 = r0;
764
+ deferred2_1 = r1;
765
+ return getStringFromWasm0(r0, r1);
766
+ } finally {
767
+ wasm.__wbindgen_add_to_stack_pointer(16);
768
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
769
+ }
770
+ }
771
+ /**
772
+ * JSON da presença da box ou "".
773
+ * @returns {string}
774
+ */
775
+ box_presence() {
776
+ let deferred1_0;
777
+ let deferred1_1;
778
+ try {
779
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
780
+ wasm.livesession_box_presence(retptr, this.__wbg_ptr);
781
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
782
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
783
+ deferred1_0 = r0;
784
+ deferred1_1 = r1;
785
+ return getStringFromWasm0(r0, r1);
786
+ } finally {
787
+ wasm.__wbindgen_add_to_stack_pointer(16);
788
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
789
+ }
790
+ }
791
+ /**
792
+ * Próximo prazo (ms) ou -1.
793
+ * @returns {number}
794
+ */
795
+ next_deadline() {
796
+ const ret = wasm.livesession_next_deadline(this.__wbg_ptr);
797
+ return ret;
798
+ }
799
+ /**
800
+ * @param {number} now
801
+ * @param {boolean} online
802
+ * @param {boolean} visible
803
+ * @param {number} rand
804
+ * @param {string} token
805
+ * @returns {string}
806
+ */
807
+ token_renewed(now, online, visible, rand, token) {
808
+ let deferred2_0;
809
+ let deferred2_1;
810
+ try {
811
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
812
+ const ptr0 = passStringToWasm0(token, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
813
+ const len0 = WASM_VECTOR_LEN;
814
+ wasm.livesession_token_renewed(retptr, this.__wbg_ptr, now, online, visible, rand, ptr0, len0);
815
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
816
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
817
+ deferred2_0 = r0;
818
+ deferred2_1 = r1;
819
+ return getStringFromWasm0(r0, r1);
820
+ } finally {
821
+ wasm.__wbindgen_add_to_stack_pointer(16);
822
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
823
+ }
824
+ }
825
+ /**
826
+ * @param {number} now
827
+ * @param {boolean} online
828
+ * @param {boolean} visible
829
+ * @param {number} rand
830
+ * @param {number} conn
831
+ * @returns {string}
832
+ */
833
+ on_open_failed(now, online, visible, rand, conn) {
834
+ let deferred1_0;
835
+ let deferred1_1;
836
+ try {
837
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
838
+ wasm.livesession_on_open_failed(retptr, this.__wbg_ptr, now, online, visible, rand, conn);
839
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
840
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
841
+ deferred1_0 = r0;
842
+ deferred1_1 = r1;
843
+ return getStringFromWasm0(r0, r1);
844
+ } finally {
845
+ wasm.__wbindgen_add_to_stack_pointer(16);
846
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
847
+ }
848
+ }
849
+ /**
850
+ * `config_json`: { chatId, connectorUrl, resumeCursor?, resumeInboxVersion?, includeRaw?, strict?,
851
+ * pingEveryMs?, pongTimeoutMs?, switchGraceMs?, syncTimeoutMs?, gapTimeoutMs?,
852
+ * longAwayMs?, backoff?{…}, has:{probeAccess,eventsRange,snapshot} }
853
+ * @param {string} config_json
854
+ */
855
+ constructor(config_json) {
856
+ try {
857
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
858
+ const ptr0 = passStringToWasm0(config_json, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
859
+ const len0 = WASM_VECTOR_LEN;
860
+ wasm.livesession_new(retptr, ptr0, len0);
861
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
862
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
863
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
864
+ if (r2) {
865
+ throw takeObject(r1);
866
+ }
867
+ this.__wbg_ptr = r0 >>> 0;
868
+ LiveSessionFinalization.register(this, this.__wbg_ptr, this);
869
+ return this;
870
+ } finally {
871
+ wasm.__wbindgen_add_to_stack_pointer(16);
872
+ }
873
+ }
874
+ /**
875
+ * "connector" | "box" | "" (nenhum)
876
+ * @returns {string}
877
+ */
878
+ via() {
879
+ let deferred1_0;
880
+ let deferred1_1;
881
+ try {
882
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
883
+ wasm.livesession_via(retptr, this.__wbg_ptr);
884
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
885
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
886
+ deferred1_0 = r0;
887
+ deferred1_1 = r1;
888
+ return getStringFromWasm0(r0, r1);
889
+ } finally {
890
+ wasm.__wbindgen_add_to_stack_pointer(16);
891
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
892
+ }
893
+ }
894
+ /**
895
+ * @param {number} now
896
+ * @param {boolean} online
897
+ * @param {boolean} visible
898
+ * @param {number} rand
899
+ * @returns {string}
900
+ */
901
+ tick(now, online, visible, rand) {
902
+ let deferred1_0;
903
+ let deferred1_1;
904
+ try {
905
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
906
+ wasm.livesession_tick(retptr, this.__wbg_ptr, now, online, visible, rand);
907
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
908
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
909
+ deferred1_0 = r0;
910
+ deferred1_1 = r1;
911
+ return getStringFromWasm0(r0, r1);
912
+ } finally {
913
+ wasm.__wbindgen_add_to_stack_pointer(16);
914
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
915
+ }
916
+ }
917
+ /**
918
+ * @param {number} now
919
+ * @param {boolean} online
920
+ * @param {boolean} visible
921
+ * @param {number} rand
922
+ * @param {string} why
923
+ * @param {number} away_ms
924
+ * @returns {string}
925
+ */
926
+ wake(now, online, visible, rand, why, away_ms) {
927
+ let deferred2_0;
928
+ let deferred2_1;
929
+ try {
930
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
931
+ const ptr0 = passStringToWasm0(why, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
932
+ const len0 = WASM_VECTOR_LEN;
933
+ wasm.livesession_wake(retptr, this.__wbg_ptr, now, online, visible, rand, ptr0, len0, away_ms);
934
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
935
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
936
+ deferred2_0 = r0;
937
+ deferred2_1 = r1;
938
+ return getStringFromWasm0(r0, r1);
939
+ } finally {
940
+ wasm.__wbindgen_add_to_stack_pointer(16);
941
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
942
+ }
943
+ }
944
+ /**
945
+ * @param {number} now
946
+ * @param {boolean} online
947
+ * @param {boolean} visible
948
+ * @param {number} rand
949
+ * @returns {string}
950
+ */
951
+ close(now, online, visible, rand) {
952
+ let deferred1_0;
953
+ let deferred1_1;
954
+ try {
955
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
956
+ wasm.livesession_close(retptr, this.__wbg_ptr, now, online, visible, rand);
957
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
958
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
959
+ deferred1_0 = r0;
960
+ deferred1_1 = r1;
961
+ return getStringFromWasm0(r0, r1);
962
+ } finally {
963
+ wasm.__wbindgen_add_to_stack_pointer(16);
964
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
965
+ }
966
+ }
967
+ /**
968
+ * @param {number} now
969
+ * @param {boolean} online
970
+ * @param {boolean} visible
971
+ * @param {number} rand
972
+ * @returns {string}
973
+ */
974
+ start(now, online, visible, rand) {
975
+ let deferred1_0;
976
+ let deferred1_1;
977
+ try {
978
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
979
+ wasm.livesession_start(retptr, this.__wbg_ptr, now, online, visible, rand);
980
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
981
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
982
+ deferred1_0 = r0;
983
+ deferred1_1 = r1;
984
+ return getStringFromWasm0(r0, r1);
985
+ } finally {
986
+ wasm.__wbindgen_add_to_stack_pointer(16);
987
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
988
+ }
989
+ }
990
+ /**
991
+ * @returns {number}
992
+ */
993
+ cursor() {
994
+ const ret = wasm.livesession_cursor(this.__wbg_ptr);
995
+ return ret;
996
+ }
997
+ /**
998
+ * @returns {string}
999
+ */
1000
+ status() {
1001
+ let deferred1_0;
1002
+ let deferred1_1;
1003
+ try {
1004
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1005
+ wasm.livesession_status(retptr, this.__wbg_ptr);
1006
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1007
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1008
+ deferred1_0 = r0;
1009
+ deferred1_1 = r1;
1010
+ return getStringFromWasm0(r0, r1);
1011
+ } finally {
1012
+ wasm.__wbindgen_add_to_stack_pointer(16);
1013
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
1014
+ }
1015
+ }
1016
+ /**
1017
+ * @param {number} now
1018
+ * @param {boolean} online
1019
+ * @param {boolean} visible
1020
+ * @param {number} rand
1021
+ * @param {string} frame_json
1022
+ * @returns {string}
1023
+ */
1024
+ command(now, online, visible, rand, frame_json) {
1025
+ let deferred3_0;
1026
+ let deferred3_1;
1027
+ try {
1028
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1029
+ const ptr0 = passStringToWasm0(frame_json, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1030
+ const len0 = WASM_VECTOR_LEN;
1031
+ wasm.livesession_command(retptr, this.__wbg_ptr, now, online, visible, rand, ptr0, len0);
1032
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1033
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1034
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
1035
+ var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
1036
+ var ptr2 = r0;
1037
+ var len2 = r1;
1038
+ if (r3) {
1039
+ ptr2 = 0;
1040
+ len2 = 0;
1041
+ throw takeObject(r2);
1042
+ }
1043
+ deferred3_0 = ptr2;
1044
+ deferred3_1 = len2;
1045
+ return getStringFromWasm0(ptr2, len2);
1046
+ } finally {
1047
+ wasm.__wbindgen_add_to_stack_pointer(16);
1048
+ wasm.__wbindgen_export_2(deferred3_0, deferred3_1, 1);
1049
+ }
1050
+ }
1051
+ /**
1052
+ * @param {number} now
1053
+ * @param {boolean} online
1054
+ * @param {boolean} visible
1055
+ * @param {number} rand
1056
+ * @param {number} conn
1057
+ * @returns {string}
1058
+ */
1059
+ on_open(now, online, visible, rand, conn) {
1060
+ let deferred1_0;
1061
+ let deferred1_1;
1062
+ try {
1063
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1064
+ wasm.livesession_on_open(retptr, this.__wbg_ptr, now, online, visible, rand, conn);
1065
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1066
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1067
+ deferred1_0 = r0;
1068
+ deferred1_1 = r1;
1069
+ return getStringFromWasm0(r0, r1);
1070
+ } finally {
1071
+ wasm.__wbindgen_add_to_stack_pointer(16);
1072
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
1073
+ }
1074
+ }
1075
+ /**
1076
+ * @param {number} now
1077
+ * @param {boolean} online
1078
+ * @param {boolean} visible
1079
+ * @param {number} rand
1080
+ * @param {number} conn
1081
+ * @param {number} code
1082
+ * @param {string} reason
1083
+ * @returns {string}
1084
+ */
1085
+ on_close(now, online, visible, rand, conn, code, reason) {
1086
+ let deferred2_0;
1087
+ let deferred2_1;
1088
+ try {
1089
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1090
+ const ptr0 = passStringToWasm0(reason, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1091
+ const len0 = WASM_VECTOR_LEN;
1092
+ wasm.livesession_on_close(retptr, this.__wbg_ptr, now, online, visible, rand, conn, code, ptr0, len0);
1093
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1094
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1095
+ deferred2_0 = r0;
1096
+ deferred2_1 = r1;
1097
+ return getStringFromWasm0(r0, r1);
1098
+ } finally {
1099
+ wasm.__wbindgen_add_to_stack_pointer(16);
1100
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
1101
+ }
1102
+ }
1103
+ /**
1104
+ * @param {number} now
1105
+ * @param {boolean} online
1106
+ * @param {boolean} visible
1107
+ * @param {number} rand
1108
+ * @param {number} conn
1109
+ * @returns {string}
1110
+ */
1111
+ on_error(now, online, visible, rand, conn) {
1112
+ let deferred1_0;
1113
+ let deferred1_1;
1114
+ try {
1115
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1116
+ wasm.livesession_on_error(retptr, this.__wbg_ptr, now, online, visible, rand, conn);
1117
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1118
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1119
+ deferred1_0 = r0;
1120
+ deferred1_1 = r1;
1121
+ return getStringFromWasm0(r0, r1);
1122
+ } finally {
1123
+ wasm.__wbindgen_add_to_stack_pointer(16);
1124
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
1125
+ }
1126
+ }
1127
+ /**
1128
+ * @param {number} now
1129
+ * @param {boolean} online
1130
+ * @param {boolean} visible
1131
+ * @param {number} rand
1132
+ * @param {number} req
1133
+ * @param {boolean} ok
1134
+ * @param {string} access
1135
+ * @returns {string}
1136
+ */
1137
+ on_probe(now, online, visible, rand, req, ok, access) {
1138
+ let deferred2_0;
1139
+ let deferred2_1;
1140
+ try {
1141
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1142
+ const ptr0 = passStringToWasm0(access, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1143
+ const len0 = WASM_VECTOR_LEN;
1144
+ wasm.livesession_on_probe(retptr, this.__wbg_ptr, now, online, visible, rand, req, ok, ptr0, len0);
1145
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1146
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1147
+ deferred2_0 = r0;
1148
+ deferred2_1 = r1;
1149
+ return getStringFromWasm0(r0, r1);
1150
+ } finally {
1151
+ wasm.__wbindgen_add_to_stack_pointer(16);
1152
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
1153
+ }
1154
+ }
1155
+ /**
1156
+ * `events_json` = array de envelopes.
1157
+ * @param {number} now
1158
+ * @param {boolean} online
1159
+ * @param {boolean} visible
1160
+ * @param {number} rand
1161
+ * @param {number} req
1162
+ * @param {boolean} ok
1163
+ * @param {string} events_json
1164
+ * @param {number} from
1165
+ * @param {number} to
1166
+ * @returns {string}
1167
+ */
1168
+ on_range(now, online, visible, rand, req, ok, events_json, from, to) {
1169
+ let deferred2_0;
1170
+ let deferred2_1;
1171
+ try {
1172
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1173
+ const ptr0 = passStringToWasm0(events_json, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1174
+ const len0 = WASM_VECTOR_LEN;
1175
+ wasm.livesession_on_range(retptr, this.__wbg_ptr, now, online, visible, rand, req, ok, ptr0, len0, from, to);
1176
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1177
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1178
+ deferred2_0 = r0;
1179
+ deferred2_1 = r1;
1180
+ return getStringFromWasm0(r0, r1);
1181
+ } finally {
1182
+ wasm.__wbindgen_add_to_stack_pointer(16);
1183
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
1184
+ }
1185
+ }
1186
+ /**
1187
+ * `ok=false` = o getToken falhou.
1188
+ * @param {number} now
1189
+ * @param {boolean} online
1190
+ * @param {boolean} visible
1191
+ * @param {number} rand
1192
+ * @param {number} req
1193
+ * @param {boolean} ok
1194
+ * @param {string} token
1195
+ * @returns {string}
1196
+ */
1197
+ on_token(now, online, visible, rand, req, ok, token) {
1198
+ let deferred2_0;
1199
+ let deferred2_1;
1200
+ try {
1201
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1202
+ const ptr0 = passStringToWasm0(token, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1203
+ const len0 = WASM_VECTOR_LEN;
1204
+ wasm.livesession_on_token(retptr, this.__wbg_ptr, now, online, visible, rand, req, ok, ptr0, len0);
1205
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1206
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1207
+ deferred2_0 = r0;
1208
+ deferred2_1 = r1;
1209
+ return getStringFromWasm0(r0, r1);
1210
+ } finally {
1211
+ wasm.__wbindgen_add_to_stack_pointer(16);
1212
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
1213
+ }
1214
+ }
1215
+ };
1216
+ var LiveWatchFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
1217
+ }, unregister: () => {
1218
+ } } : new FinalizationRegistry((ptr) => wasm.__wbg_livewatch_free(ptr >>> 0, 1));
1219
+ var LiveWatch = class {
1220
+ __destroy_into_raw() {
1221
+ const ptr = this.__wbg_ptr;
1222
+ this.__wbg_ptr = 0;
1223
+ LiveWatchFinalization.unregister(this);
1224
+ return ptr;
1225
+ }
1226
+ free() {
1227
+ const ptr = this.__destroy_into_raw();
1228
+ wasm.__wbg_livewatch_free(ptr, 0);
1229
+ }
1230
+ /**
1231
+ * @returns {string}
1232
+ */
1233
+ load_newer() {
1234
+ let deferred1_0;
1235
+ let deferred1_1;
1236
+ try {
1237
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1238
+ wasm.livewatch_load_newer(retptr, this.__wbg_ptr);
1239
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1240
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1241
+ deferred1_0 = r0;
1242
+ deferred1_1 = r1;
1243
+ return getStringFromWasm0(r0, r1);
1244
+ } finally {
1245
+ wasm.__wbindgen_add_to_stack_pointer(16);
1246
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
1247
+ }
1248
+ }
1249
+ /**
1250
+ * @returns {string}
1251
+ */
1252
+ load_older() {
1253
+ let deferred1_0;
1254
+ let deferred1_1;
1255
+ try {
1256
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1257
+ wasm.livewatch_load_older(retptr, this.__wbg_ptr);
1258
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1259
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1260
+ deferred1_0 = r0;
1261
+ deferred1_1 = r1;
1262
+ return getStringFromWasm0(r0, r1);
1263
+ } finally {
1264
+ wasm.__wbindgen_add_to_stack_pointer(16);
1265
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
1266
+ }
1267
+ }
1268
+ /**
1269
+ * `page_json` = a página no formato do log ({items: envelopes, hasBefore, hasAfter, anchorIndex?…});
1270
+ * com `ok=false`, `page_json` é a mensagem de erro.
1271
+ * @param {number} req
1272
+ * @param {boolean} ok
1273
+ * @param {string} page_json
1274
+ * @returns {string}
1275
+ */
1276
+ on_history(req, ok, page_json) {
1277
+ let deferred2_0;
1278
+ let deferred2_1;
1279
+ try {
1280
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1281
+ const ptr0 = passStringToWasm0(page_json, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1282
+ const len0 = WASM_VECTOR_LEN;
1283
+ wasm.livewatch_on_history(retptr, this.__wbg_ptr, req, ok, ptr0, len0);
1284
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1285
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1286
+ deferred2_0 = r0;
1287
+ deferred2_1 = r1;
1288
+ return getStringFromWasm0(r0, r1);
1289
+ } finally {
1290
+ wasm.__wbindgen_add_to_stack_pointer(16);
1291
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
1292
+ }
1293
+ }
1294
+ /**
1295
+ * @param {number} now
1296
+ * @param {boolean} online
1297
+ * @param {boolean} visible
1298
+ * @param {number} rand
1299
+ * @param {number} conn
1300
+ * @param {string} text
1301
+ * @returns {string}
1302
+ */
1303
+ on_message(now, online, visible, rand, conn, text) {
1304
+ let deferred2_0;
1305
+ let deferred2_1;
1306
+ try {
1307
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1308
+ const ptr0 = passStringToWasm0(text, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1309
+ const len0 = WASM_VECTOR_LEN;
1310
+ wasm.livewatch_on_message(retptr, this.__wbg_ptr, now, online, visible, rand, conn, ptr0, len0);
1311
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1312
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1313
+ deferred2_0 = r0;
1314
+ deferred2_1 = r1;
1315
+ return getStringFromWasm0(r0, r1);
1316
+ } finally {
1317
+ wasm.__wbindgen_add_to_stack_pointer(16);
1318
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
1319
+ }
1320
+ }
1321
+ /**
1322
+ * @returns {string}
1323
+ */
1324
+ jump_to_end() {
1325
+ let deferred1_0;
1326
+ let deferred1_1;
1327
+ try {
1328
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1329
+ wasm.livewatch_jump_to_end(retptr, this.__wbg_ptr);
1330
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1331
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1332
+ deferred1_0 = r0;
1333
+ deferred1_1 = r1;
1334
+ return getStringFromWasm0(r0, r1);
1335
+ } finally {
1336
+ wasm.__wbindgen_add_to_stack_pointer(16);
1337
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
1338
+ }
1339
+ }
1340
+ /**
1341
+ * @param {number} now
1342
+ * @param {boolean} online
1343
+ * @param {boolean} visible
1344
+ * @param {number} rand
1345
+ * @param {number} req
1346
+ * @param {boolean} ok
1347
+ * @param {string} snapshot_json
1348
+ * @returns {string}
1349
+ */
1350
+ on_snapshot(now, online, visible, rand, req, ok, snapshot_json) {
1351
+ let deferred2_0;
1352
+ let deferred2_1;
1353
+ try {
1354
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1355
+ const ptr0 = passStringToWasm0(snapshot_json, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1356
+ const len0 = WASM_VECTOR_LEN;
1357
+ wasm.livewatch_on_snapshot(retptr, this.__wbg_ptr, now, online, visible, rand, req, ok, ptr0, len0);
1358
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1359
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1360
+ deferred2_0 = r0;
1361
+ deferred2_1 = r1;
1362
+ return getStringFromWasm0(r0, r1);
1363
+ } finally {
1364
+ wasm.__wbindgen_add_to_stack_pointer(16);
1365
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
1366
+ }
1367
+ }
1368
+ /**
1369
+ * Troca de agente (§17.4) no mesmo canal ordenado dos comandos; `to_json` = `{agentId?, model?, effort?}` (o
1370
+ * realtime completa e valida; provider/agentName que vierem são ignorados). O `resolve`
1371
+ * sai com o ref `switch:<switch_id>`.
1372
+ * @param {number} now
1373
+ * @param {boolean} online
1374
+ * @param {boolean} visible
1375
+ * @param {number} rand
1376
+ * @param {string} switch_id
1377
+ * @param {string} to_json
1378
+ * @returns {string}
1379
+ */
1380
+ switch_agent(now, online, visible, rand, switch_id, to_json) {
1381
+ let deferred4_0;
1382
+ let deferred4_1;
1383
+ try {
1384
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1385
+ const ptr0 = passStringToWasm0(switch_id, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1386
+ const len0 = WASM_VECTOR_LEN;
1387
+ const ptr1 = passStringToWasm0(to_json, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1388
+ const len1 = WASM_VECTOR_LEN;
1389
+ wasm.livewatch_switch_agent(retptr, this.__wbg_ptr, now, online, visible, rand, ptr0, len0, ptr1, len1);
1390
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1391
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1392
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
1393
+ var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
1394
+ var ptr3 = r0;
1395
+ var len3 = r1;
1396
+ if (r3) {
1397
+ ptr3 = 0;
1398
+ len3 = 0;
1399
+ throw takeObject(r2);
1400
+ }
1401
+ deferred4_0 = ptr3;
1402
+ deferred4_1 = len3;
1403
+ return getStringFromWasm0(ptr3, len3);
1404
+ } finally {
1405
+ wasm.__wbindgen_add_to_stack_pointer(16);
1406
+ wasm.__wbindgen_export_2(deferred4_0, deferred4_1, 1);
1407
+ }
1408
+ }
1409
+ /**
1410
+ * Só modelo/esforço do mesmo agente (`change_json` = `{model?, effort?}`). Ref `switch:<switch_id>`.
1411
+ * @param {number} now
1412
+ * @param {boolean} online
1413
+ * @param {boolean} visible
1414
+ * @param {number} rand
1415
+ * @param {string} switch_id
1416
+ * @param {string} change_json
1417
+ * @returns {string}
1418
+ */
1419
+ switch_model(now, online, visible, rand, switch_id, change_json) {
1420
+ let deferred4_0;
1421
+ let deferred4_1;
1422
+ try {
1423
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1424
+ const ptr0 = passStringToWasm0(switch_id, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1425
+ const len0 = WASM_VECTOR_LEN;
1426
+ const ptr1 = passStringToWasm0(change_json, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1427
+ const len1 = WASM_VECTOR_LEN;
1428
+ wasm.livewatch_switch_model(retptr, this.__wbg_ptr, now, online, visible, rand, ptr0, len0, ptr1, len1);
1429
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1430
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1431
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
1432
+ var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
1433
+ var ptr3 = r0;
1434
+ var len3 = r1;
1435
+ if (r3) {
1436
+ ptr3 = 0;
1437
+ len3 = 0;
1438
+ throw takeObject(r2);
1439
+ }
1440
+ deferred4_0 = ptr3;
1441
+ deferred4_1 = len3;
1442
+ return getStringFromWasm0(ptr3, len3);
1443
+ } finally {
1444
+ wasm.__wbindgen_add_to_stack_pointer(16);
1445
+ wasm.__wbindgen_export_2(deferred4_0, deferred4_1, 1);
1446
+ }
1447
+ }
1448
+ /**
1449
+ * Cancela a troca agendada (frame `cancelSwitch`). Ref `switch:<switch_id>`.
1450
+ * @param {number} now
1451
+ * @param {boolean} online
1452
+ * @param {boolean} visible
1453
+ * @param {number} rand
1454
+ * @param {string} switch_id
1455
+ * @returns {string}
1456
+ */
1457
+ cancel_switch(now, online, visible, rand, switch_id) {
1458
+ let deferred2_0;
1459
+ let deferred2_1;
1460
+ try {
1461
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1462
+ const ptr0 = passStringToWasm0(switch_id, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1463
+ const len0 = WASM_VECTOR_LEN;
1464
+ wasm.livewatch_cancel_switch(retptr, this.__wbg_ptr, now, online, visible, rand, ptr0, len0);
1465
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1466
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1467
+ deferred2_0 = r0;
1468
+ deferred2_1 = r1;
1469
+ return getStringFromWasm0(r0, r1);
1470
+ } finally {
1471
+ wasm.__wbindgen_add_to_stack_pointer(16);
1472
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
1473
+ }
1474
+ }
1475
+ /**
1476
+ * @returns {number}
1477
+ */
1478
+ next_deadline() {
1479
+ const ret = wasm.livewatch_next_deadline(this.__wbg_ptr);
1480
+ return ret;
1481
+ }
1482
+ /**
1483
+ * @param {number} now
1484
+ * @param {boolean} online
1485
+ * @param {boolean} visible
1486
+ * @param {number} rand
1487
+ * @param {string} token
1488
+ * @returns {string}
1489
+ */
1490
+ token_renewed(now, online, visible, rand, token) {
1491
+ let deferred2_0;
1492
+ let deferred2_1;
1493
+ try {
1494
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1495
+ const ptr0 = passStringToWasm0(token, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1496
+ const len0 = WASM_VECTOR_LEN;
1497
+ wasm.livewatch_token_renewed(retptr, this.__wbg_ptr, now, online, visible, rand, ptr0, len0);
1498
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1499
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1500
+ deferred2_0 = r0;
1501
+ deferred2_1 = r1;
1502
+ return getStringFromWasm0(r0, r1);
1503
+ } finally {
1504
+ wasm.__wbindgen_add_to_stack_pointer(16);
1505
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
1506
+ }
1507
+ }
1508
+ /**
1509
+ * O ref que o próximo `queue_op` vai usar (a borda espera o `resolve` dele).
1510
+ * @returns {string}
1511
+ */
1512
+ next_queue_ref() {
1513
+ let deferred1_0;
1514
+ let deferred1_1;
1515
+ try {
1516
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1517
+ wasm.livewatch_next_queue_ref(retptr, this.__wbg_ptr);
1518
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1519
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1520
+ deferred1_0 = r0;
1521
+ deferred1_1 = r1;
1522
+ return getStringFromWasm0(r0, r1);
1523
+ } finally {
1524
+ wasm.__wbindgen_add_to_stack_pointer(16);
1525
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
1526
+ }
1527
+ }
1528
+ /**
1529
+ * @param {number} now
1530
+ * @param {boolean} online
1531
+ * @param {boolean} visible
1532
+ * @param {number} rand
1533
+ * @param {number} conn
1534
+ * @returns {string}
1535
+ */
1536
+ on_open_failed(now, online, visible, rand, conn) {
1537
+ let deferred1_0;
1538
+ let deferred1_1;
1539
+ try {
1540
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1541
+ wasm.livewatch_on_open_failed(retptr, this.__wbg_ptr, now, online, visible, rand, conn);
1542
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1543
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1544
+ deferred1_0 = r0;
1545
+ deferred1_1 = r1;
1546
+ return getStringFromWasm0(r0, r1);
1547
+ } finally {
1548
+ wasm.__wbindgen_add_to_stack_pointer(16);
1549
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
1550
+ }
1551
+ }
1552
+ /**
1553
+ * A mesma configuração da `LiveSession` + `pageSize?`, `maxWindow?`, `has.history`.
1554
+ * @param {string} config_json
1555
+ */
1556
+ constructor(config_json) {
1557
+ try {
1558
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1559
+ const ptr0 = passStringToWasm0(config_json, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1560
+ const len0 = WASM_VECTOR_LEN;
1561
+ wasm.livewatch_new(retptr, ptr0, len0);
1562
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1563
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1564
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
1565
+ if (r2) {
1566
+ throw takeObject(r1);
1567
+ }
1568
+ this.__wbg_ptr = r0 >>> 0;
1569
+ LiveWatchFinalization.register(this, this.__wbg_ptr, this);
1570
+ return this;
1571
+ } finally {
1572
+ wasm.__wbindgen_add_to_stack_pointer(16);
1573
+ }
1574
+ }
1575
+ /**
1576
+ * @returns {string}
1577
+ */
1578
+ via() {
1579
+ let deferred1_0;
1580
+ let deferred1_1;
1581
+ try {
1582
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1583
+ wasm.livewatch_via(retptr, this.__wbg_ptr);
1584
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1585
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1586
+ deferred1_0 = r0;
1587
+ deferred1_1 = r1;
1588
+ return getStringFromWasm0(r0, r1);
1589
+ } finally {
1590
+ wasm.__wbindgen_add_to_stack_pointer(16);
1591
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
1592
+ }
1593
+ }
1594
+ /**
1595
+ * `content_json` = ContentPart[] (a borda converte texto/anexos); `metadata_json` = `{chave: texto}` ou `""` (sem).
1596
+ * @param {number} now
1597
+ * @param {boolean} online
1598
+ * @param {boolean} visible
1599
+ * @param {number} rand
1600
+ * @param {string} message_id
1601
+ * @param {string} content_json
1602
+ * @param {string} mode
1603
+ * @param {string} metadata_json
1604
+ * @returns {string}
1605
+ */
1606
+ send(now, online, visible, rand, message_id, content_json, mode, metadata_json) {
1607
+ let deferred6_0;
1608
+ let deferred6_1;
1609
+ try {
1610
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1611
+ const ptr0 = passStringToWasm0(message_id, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1612
+ const len0 = WASM_VECTOR_LEN;
1613
+ const ptr1 = passStringToWasm0(content_json, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1614
+ const len1 = WASM_VECTOR_LEN;
1615
+ const ptr2 = passStringToWasm0(mode, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1616
+ const len2 = WASM_VECTOR_LEN;
1617
+ const ptr3 = passStringToWasm0(metadata_json, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1618
+ const len3 = WASM_VECTOR_LEN;
1619
+ wasm.livewatch_send(retptr, this.__wbg_ptr, now, online, visible, rand, ptr0, len0, ptr1, len1, ptr2, len2, ptr3, len3);
1620
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1621
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1622
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
1623
+ var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
1624
+ var ptr5 = r0;
1625
+ var len5 = r1;
1626
+ if (r3) {
1627
+ ptr5 = 0;
1628
+ len5 = 0;
1629
+ throw takeObject(r2);
1630
+ }
1631
+ deferred6_0 = ptr5;
1632
+ deferred6_1 = len5;
1633
+ return getStringFromWasm0(ptr5, len5);
1634
+ } finally {
1635
+ wasm.__wbindgen_add_to_stack_pointer(16);
1636
+ wasm.__wbindgen_export_2(deferred6_0, deferred6_1, 1);
1637
+ }
1638
+ }
1639
+ /**
1640
+ * @param {number} now
1641
+ * @param {boolean} online
1642
+ * @param {boolean} visible
1643
+ * @param {number} rand
1644
+ * @returns {string}
1645
+ */
1646
+ tick(now, online, visible, rand) {
1647
+ let deferred1_0;
1648
+ let deferred1_1;
1649
+ try {
1650
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1651
+ wasm.livewatch_tick(retptr, this.__wbg_ptr, now, online, visible, rand);
1652
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1653
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1654
+ deferred1_0 = r0;
1655
+ deferred1_1 = r1;
1656
+ return getStringFromWasm0(r0, r1);
1657
+ } finally {
1658
+ wasm.__wbindgen_add_to_stack_pointer(16);
1659
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
1660
+ }
1661
+ }
1662
+ /**
1663
+ * @param {number} now
1664
+ * @param {boolean} online
1665
+ * @param {boolean} visible
1666
+ * @param {number} rand
1667
+ * @param {string} why
1668
+ * @param {number} away_ms
1669
+ * @returns {string}
1670
+ */
1671
+ wake(now, online, visible, rand, why, away_ms) {
1672
+ let deferred2_0;
1673
+ let deferred2_1;
1674
+ try {
1675
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1676
+ const ptr0 = passStringToWasm0(why, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1677
+ const len0 = WASM_VECTOR_LEN;
1678
+ wasm.livewatch_wake(retptr, this.__wbg_ptr, now, online, visible, rand, ptr0, len0, away_ms);
1679
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1680
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1681
+ deferred2_0 = r0;
1682
+ deferred2_1 = r1;
1683
+ return getStringFromWasm0(r0, r1);
1684
+ } finally {
1685
+ wasm.__wbindgen_add_to_stack_pointer(16);
1686
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
1687
+ }
1688
+ }
1689
+ /**
1690
+ * @param {number} now
1691
+ * @param {boolean} online
1692
+ * @param {boolean} visible
1693
+ * @param {number} rand
1694
+ * @returns {string}
1695
+ */
1696
+ close(now, online, visible, rand) {
1697
+ let deferred1_0;
1698
+ let deferred1_1;
1699
+ try {
1700
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1701
+ wasm.livewatch_close(retptr, this.__wbg_ptr, now, online, visible, rand);
1702
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1703
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1704
+ deferred1_0 = r0;
1705
+ deferred1_1 = r1;
1706
+ return getStringFromWasm0(r0, r1);
1707
+ } finally {
1708
+ wasm.__wbindgen_add_to_stack_pointer(16);
1709
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
1710
+ }
1711
+ }
1712
+ /**
1713
+ * @param {number} now
1714
+ * @param {boolean} online
1715
+ * @param {boolean} visible
1716
+ * @param {number} rand
1717
+ * @returns {string}
1718
+ */
1719
+ start(now, online, visible, rand) {
1720
+ let deferred1_0;
1721
+ let deferred1_1;
1722
+ try {
1723
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1724
+ wasm.livewatch_start(retptr, this.__wbg_ptr, now, online, visible, rand);
1725
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1726
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1727
+ deferred1_0 = r0;
1728
+ deferred1_1 = r1;
1729
+ return getStringFromWasm0(r0, r1);
1730
+ } finally {
1731
+ wasm.__wbindgen_add_to_stack_pointer(16);
1732
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
1733
+ }
1734
+ }
1735
+ /**
1736
+ * @returns {number}
1737
+ */
1738
+ cursor() {
1739
+ const ret = wasm.livewatch_cursor(this.__wbg_ptr);
1740
+ return ret;
1741
+ }
1742
+ /**
1743
+ * @returns {string}
1744
+ */
1745
+ status() {
1746
+ let deferred1_0;
1747
+ let deferred1_1;
1748
+ try {
1749
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1750
+ wasm.livewatch_status(retptr, this.__wbg_ptr);
1751
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1752
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1753
+ deferred1_0 = r0;
1754
+ deferred1_1 = r1;
1755
+ return getStringFromWasm0(r0, r1);
1756
+ } finally {
1757
+ wasm.__wbindgen_add_to_stack_pointer(16);
1758
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
1759
+ }
1760
+ }
1761
+ /**
1762
+ * Comando cru com `ref` (stop/respond/resend/reset).
1763
+ * @param {number} now
1764
+ * @param {boolean} online
1765
+ * @param {boolean} visible
1766
+ * @param {number} rand
1767
+ * @param {string} frame_json
1768
+ * @returns {string}
1769
+ */
1770
+ command(now, online, visible, rand, frame_json) {
1771
+ let deferred3_0;
1772
+ let deferred3_1;
1773
+ try {
1774
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1775
+ const ptr0 = passStringToWasm0(frame_json, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1776
+ const len0 = WASM_VECTOR_LEN;
1777
+ wasm.livewatch_command(retptr, this.__wbg_ptr, now, online, visible, rand, ptr0, len0);
1778
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1779
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1780
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
1781
+ var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
1782
+ var ptr2 = r0;
1783
+ var len2 = r1;
1784
+ if (r3) {
1785
+ ptr2 = 0;
1786
+ len2 = 0;
1787
+ throw takeObject(r2);
1788
+ }
1789
+ deferred3_0 = ptr2;
1790
+ deferred3_1 = len2;
1791
+ return getStringFromWasm0(ptr2, len2);
1792
+ } finally {
1793
+ wasm.__wbindgen_add_to_stack_pointer(16);
1794
+ wasm.__wbindgen_export_2(deferred3_0, deferred3_1, 1);
1795
+ }
1796
+ }
1797
+ /**
1798
+ * `anchor_json` = {"messageId": "msg_…"} | {"eventId": N}
1799
+ * @param {string} anchor_json
1800
+ * @returns {string}
1801
+ */
1802
+ jump_to(anchor_json) {
1803
+ let deferred3_0;
1804
+ let deferred3_1;
1805
+ try {
1806
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1807
+ const ptr0 = passStringToWasm0(anchor_json, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1808
+ const len0 = WASM_VECTOR_LEN;
1809
+ wasm.livewatch_jump_to(retptr, this.__wbg_ptr, ptr0, len0);
1810
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1811
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1812
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
1813
+ var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
1814
+ var ptr2 = r0;
1815
+ var len2 = r1;
1816
+ if (r3) {
1817
+ ptr2 = 0;
1818
+ len2 = 0;
1819
+ throw takeObject(r2);
1820
+ }
1821
+ deferred3_0 = ptr2;
1822
+ deferred3_1 = len2;
1823
+ return getStringFromWasm0(ptr2, len2);
1824
+ } finally {
1825
+ wasm.__wbindgen_add_to_stack_pointer(16);
1826
+ wasm.__wbindgen_export_2(deferred3_0, deferred3_1, 1);
1827
+ }
1828
+ }
1829
+ /**
1830
+ * @param {number} now
1831
+ * @param {boolean} online
1832
+ * @param {boolean} visible
1833
+ * @param {number} rand
1834
+ * @param {number} conn
1835
+ * @returns {string}
1836
+ */
1837
+ on_open(now, online, visible, rand, conn) {
1838
+ let deferred1_0;
1839
+ let deferred1_1;
1840
+ try {
1841
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1842
+ wasm.livewatch_on_open(retptr, this.__wbg_ptr, now, online, visible, rand, conn);
1843
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1844
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1845
+ deferred1_0 = r0;
1846
+ deferred1_1 = r1;
1847
+ return getStringFromWasm0(r0, r1);
1848
+ } finally {
1849
+ wasm.__wbindgen_add_to_stack_pointer(16);
1850
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
1851
+ }
1852
+ }
1853
+ /**
1854
+ * @param {number} now
1855
+ * @param {boolean} online
1856
+ * @param {boolean} visible
1857
+ * @param {number} rand
1858
+ * @param {number} conn
1859
+ * @param {number} code
1860
+ * @param {string} reason
1861
+ * @returns {string}
1862
+ */
1863
+ on_close(now, online, visible, rand, conn, code, reason) {
1864
+ let deferred2_0;
1865
+ let deferred2_1;
1866
+ try {
1867
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1868
+ const ptr0 = passStringToWasm0(reason, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1869
+ const len0 = WASM_VECTOR_LEN;
1870
+ wasm.livewatch_on_close(retptr, this.__wbg_ptr, now, online, visible, rand, conn, code, ptr0, len0);
1871
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1872
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1873
+ deferred2_0 = r0;
1874
+ deferred2_1 = r1;
1875
+ return getStringFromWasm0(r0, r1);
1876
+ } finally {
1877
+ wasm.__wbindgen_add_to_stack_pointer(16);
1878
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
1879
+ }
1880
+ }
1881
+ /**
1882
+ * @param {number} now
1883
+ * @param {boolean} online
1884
+ * @param {boolean} visible
1885
+ * @param {number} rand
1886
+ * @param {number} conn
1887
+ * @returns {string}
1888
+ */
1889
+ on_error(now, online, visible, rand, conn) {
1890
+ let deferred1_0;
1891
+ let deferred1_1;
1892
+ try {
1893
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1894
+ wasm.livewatch_on_error(retptr, this.__wbg_ptr, now, online, visible, rand, conn);
1895
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1896
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1897
+ deferred1_0 = r0;
1898
+ deferred1_1 = r1;
1899
+ return getStringFromWasm0(r0, r1);
1900
+ } finally {
1901
+ wasm.__wbindgen_add_to_stack_pointer(16);
1902
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
1903
+ }
1904
+ }
1905
+ /**
1906
+ * @param {number} now
1907
+ * @param {boolean} online
1908
+ * @param {boolean} visible
1909
+ * @param {number} rand
1910
+ * @param {number} req
1911
+ * @param {boolean} ok
1912
+ * @param {string} access
1913
+ * @returns {string}
1914
+ */
1915
+ on_probe(now, online, visible, rand, req, ok, access) {
1916
+ let deferred2_0;
1917
+ let deferred2_1;
1918
+ try {
1919
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1920
+ const ptr0 = passStringToWasm0(access, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1921
+ const len0 = WASM_VECTOR_LEN;
1922
+ wasm.livewatch_on_probe(retptr, this.__wbg_ptr, now, online, visible, rand, req, ok, ptr0, len0);
1923
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1924
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1925
+ deferred2_0 = r0;
1926
+ deferred2_1 = r1;
1927
+ return getStringFromWasm0(r0, r1);
1928
+ } finally {
1929
+ wasm.__wbindgen_add_to_stack_pointer(16);
1930
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
1931
+ }
1932
+ }
1933
+ /**
1934
+ * @param {number} now
1935
+ * @param {boolean} online
1936
+ * @param {boolean} visible
1937
+ * @param {number} rand
1938
+ * @param {number} req
1939
+ * @param {boolean} ok
1940
+ * @param {string} events_json
1941
+ * @param {number} from
1942
+ * @param {number} to
1943
+ * @returns {string}
1944
+ */
1945
+ on_range(now, online, visible, rand, req, ok, events_json, from, to) {
1946
+ let deferred2_0;
1947
+ let deferred2_1;
1948
+ try {
1949
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1950
+ const ptr0 = passStringToWasm0(events_json, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1951
+ const len0 = WASM_VECTOR_LEN;
1952
+ wasm.livewatch_on_range(retptr, this.__wbg_ptr, now, online, visible, rand, req, ok, ptr0, len0, from, to);
1953
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1954
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1955
+ deferred2_0 = r0;
1956
+ deferred2_1 = r1;
1957
+ return getStringFromWasm0(r0, r1);
1958
+ } finally {
1959
+ wasm.__wbindgen_add_to_stack_pointer(16);
1960
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
1961
+ }
1962
+ }
1963
+ /**
1964
+ * @param {number} now
1965
+ * @param {boolean} online
1966
+ * @param {boolean} visible
1967
+ * @param {number} rand
1968
+ * @param {number} req
1969
+ * @param {boolean} ok
1970
+ * @param {string} token
1971
+ * @returns {string}
1972
+ */
1973
+ on_token(now, online, visible, rand, req, ok, token) {
1974
+ let deferred2_0;
1975
+ let deferred2_1;
1976
+ try {
1977
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
1978
+ const ptr0 = passStringToWasm0(token, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
1979
+ const len0 = WASM_VECTOR_LEN;
1980
+ wasm.livewatch_on_token(retptr, this.__wbg_ptr, now, online, visible, rand, req, ok, ptr0, len0);
1981
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
1982
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
1983
+ deferred2_0 = r0;
1984
+ deferred2_1 = r1;
1985
+ return getStringFromWasm0(r0, r1);
1986
+ } finally {
1987
+ wasm.__wbindgen_add_to_stack_pointer(16);
1988
+ wasm.__wbindgen_export_2(deferred2_0, deferred2_1, 1);
1989
+ }
1990
+ }
1991
+ /**
1992
+ * @param {number} now
1993
+ * @param {boolean} online
1994
+ * @param {boolean} visible
1995
+ * @param {number} rand
1996
+ * @param {string} op_json
1997
+ * @returns {string}
1998
+ */
1999
+ queue_op(now, online, visible, rand, op_json) {
2000
+ let deferred3_0;
2001
+ let deferred3_1;
2002
+ try {
2003
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
2004
+ const ptr0 = passStringToWasm0(op_json, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
2005
+ const len0 = WASM_VECTOR_LEN;
2006
+ wasm.livewatch_queue_op(retptr, this.__wbg_ptr, now, online, visible, rand, ptr0, len0);
2007
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
2008
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
2009
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
2010
+ var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
2011
+ var ptr2 = r0;
2012
+ var len2 = r1;
2013
+ if (r3) {
2014
+ ptr2 = 0;
2015
+ len2 = 0;
2016
+ throw takeObject(r2);
2017
+ }
2018
+ deferred3_0 = ptr2;
2019
+ deferred3_1 = len2;
2020
+ return getStringFromWasm0(ptr2, len2);
2021
+ } finally {
2022
+ wasm.__wbindgen_add_to_stack_pointer(16);
2023
+ wasm.__wbindgen_export_2(deferred3_0, deferred3_1, 1);
2024
+ }
2025
+ }
2026
+ };
2027
+ var ReducerFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
2028
+ }, unregister: () => {
2029
+ } } : new FinalizationRegistry((ptr) => wasm.__wbg_reducer_free(ptr >>> 0, 1));
2030
+ var Reducer = class {
2031
+ __destroy_into_raw() {
2032
+ const ptr = this.__wbg_ptr;
2033
+ this.__wbg_ptr = 0;
2034
+ ReducerFinalization.unregister(this);
2035
+ return ptr;
2036
+ }
2037
+ free() {
2038
+ const ptr = this.__destroy_into_raw();
2039
+ wasm.__wbg_reducer_free(ptr, 0);
2040
+ }
2041
+ /**
2042
+ * Parte de um estado (o snapshot) em vez do vazio.
2043
+ * @param {string} state_json
2044
+ */
2045
+ load_state(state_json) {
2046
+ try {
2047
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
2048
+ const ptr0 = passStringToWasm0(state_json, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
2049
+ const len0 = WASM_VECTOR_LEN;
2050
+ wasm.reducer_load_state(retptr, this.__wbg_ptr, ptr0, len0);
2051
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
2052
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
2053
+ if (r1) {
2054
+ throw takeObject(r0);
2055
+ }
2056
+ } finally {
2057
+ wasm.__wbindgen_add_to_stack_pointer(16);
2058
+ }
2059
+ }
2060
+ /**
2061
+ * @returns {string}
2062
+ */
2063
+ state_json() {
2064
+ let deferred1_0;
2065
+ let deferred1_1;
2066
+ try {
2067
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
2068
+ wasm.reducer_state_json(retptr, this.__wbg_ptr);
2069
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
2070
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
2071
+ deferred1_0 = r0;
2072
+ deferred1_1 = r1;
2073
+ return getStringFromWasm0(r0, r1);
2074
+ } finally {
2075
+ wasm.__wbindgen_add_to_stack_pointer(16);
2076
+ wasm.__wbindgen_export_2(deferred1_0, deferred1_1, 1);
2077
+ }
2078
+ }
2079
+ constructor() {
2080
+ const ret = wasm.reducer_new();
2081
+ this.__wbg_ptr = ret >>> 0;
2082
+ ReducerFinalization.register(this, this.__wbg_ptr, this);
2083
+ return this;
2084
+ }
2085
+ /**
2086
+ * @param {string} event_json
2087
+ */
2088
+ apply(event_json) {
2089
+ try {
2090
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
2091
+ const ptr0 = passStringToWasm0(event_json, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
2092
+ const len0 = WASM_VECTOR_LEN;
2093
+ wasm.reducer_apply(retptr, this.__wbg_ptr, ptr0, len0);
2094
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
2095
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
2096
+ if (r1) {
2097
+ throw takeObject(r0);
2098
+ }
2099
+ } finally {
2100
+ wasm.__wbindgen_add_to_stack_pointer(16);
2101
+ }
2102
+ }
2103
+ };
2104
+ async function __wbg_load(module, imports) {
2105
+ if (typeof Response === "function" && module instanceof Response) {
2106
+ if (typeof WebAssembly.instantiateStreaming === "function") {
2107
+ try {
2108
+ return await WebAssembly.instantiateStreaming(module, imports);
2109
+ } catch (e) {
2110
+ if (module.headers.get("Content-Type") != "application/wasm") {
2111
+ console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
2112
+ } else {
2113
+ throw e;
2114
+ }
2115
+ }
2116
+ }
2117
+ const bytes = await module.arrayBuffer();
2118
+ return await WebAssembly.instantiate(bytes, imports);
2119
+ } else {
2120
+ const instance = await WebAssembly.instantiate(module, imports);
2121
+ if (instance instanceof WebAssembly.Instance) {
2122
+ return { instance, module };
2123
+ } else {
2124
+ return instance;
2125
+ }
2126
+ }
2127
+ }
2128
+ function __wbg_get_imports() {
2129
+ const imports = {};
2130
+ imports.wbg = {};
2131
+ imports.wbg.__wbindgen_error_new = function(arg0, arg1) {
2132
+ const ret = new Error(getStringFromWasm0(arg0, arg1));
2133
+ return addHeapObject(ret);
2134
+ };
2135
+ imports.wbg.__wbindgen_throw = function(arg0, arg1) {
2136
+ throw new Error(getStringFromWasm0(arg0, arg1));
2137
+ };
2138
+ return imports;
2139
+ }
2140
+ function __wbg_init_memory(imports, memory) {
2141
+ }
2142
+ function __wbg_finalize_init(instance, module) {
2143
+ wasm = instance.exports;
2144
+ __wbg_init.__wbindgen_wasm_module = module;
2145
+ cachedDataViewMemory0 = null;
2146
+ cachedUint8ArrayMemory0 = null;
2147
+ return wasm;
2148
+ }
2149
+ function initSync(module) {
2150
+ if (wasm !== void 0) return wasm;
2151
+ if (typeof module !== "undefined") {
2152
+ if (Object.getPrototypeOf(module) === Object.prototype) {
2153
+ ({ module } = module);
2154
+ } else {
2155
+ console.warn("using deprecated parameters for `initSync()`; pass a single object instead");
2156
+ }
2157
+ }
2158
+ const imports = __wbg_get_imports();
2159
+ __wbg_init_memory(imports);
2160
+ if (!(module instanceof WebAssembly.Module)) {
2161
+ module = new WebAssembly.Module(module);
2162
+ }
2163
+ const instance = new WebAssembly.Instance(module, imports);
2164
+ return __wbg_finalize_init(instance, module);
2165
+ }
2166
+ async function __wbg_init(module_or_path) {
2167
+ if (wasm !== void 0) return wasm;
2168
+ if (typeof module_or_path !== "undefined") {
2169
+ if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
2170
+ ({ module_or_path } = module_or_path);
2171
+ } else {
2172
+ console.warn("using deprecated parameters for the initialization function; pass a single object instead");
2173
+ }
2174
+ }
2175
+ const imports = __wbg_get_imports();
2176
+ if (typeof module_or_path === "string" || typeof Request === "function" && module_or_path instanceof Request || typeof URL === "function" && module_or_path instanceof URL) {
2177
+ module_or_path = fetch(module_or_path);
2178
+ }
2179
+ __wbg_init_memory(imports);
2180
+ const { instance, module } = await __wbg_load(await module_or_path, imports);
2181
+ return __wbg_finalize_init(instance, module);
2182
+ }
2183
+ var live_default = __wbg_init;
2184
+
2185
+ // ../core-live/src/native.ts
2186
+ var ready = false;
2187
+ var loading = null;
2188
+ function decode(b64) {
2189
+ if (typeof atob === "function") {
2190
+ const bin = atob(b64);
2191
+ const out = new Uint8Array(bin.length);
2192
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
2193
+ return out;
2194
+ }
2195
+ return Uint8Array.from(Buffer.from(b64, "base64"));
2196
+ }
2197
+ function loadCore() {
2198
+ if (ready) return Promise.resolve(live_exports);
2199
+ loading ??= import("./bytes-HBD44S56.js").then(({ WASM_BASE64 }) => {
2200
+ if (!ready) {
2201
+ initSync({ module: decode(WASM_BASE64) });
2202
+ ready = true;
2203
+ }
2204
+ return live_exports;
2205
+ });
2206
+ return loading;
2207
+ }
2208
+ function coreIfReady() {
2209
+ return ready ? live_exports : null;
2210
+ }
2211
+ function core() {
2212
+ if (!ready) throw new Error("SmoothAgent: o n\xFAcleo ainda est\xE1 carregando \u2014 aguarde `loadCore()`");
2213
+ return live_exports;
2214
+ }
2215
+
2216
+ // ../core-live/src/edge.ts
2217
+ var Edge = class {
2218
+ constructor(make, d, chatId, random, handle) {
2219
+ this.d = d;
2220
+ this.chatId = chatId;
2221
+ this.random = random;
2222
+ this.handle = handle;
2223
+ if (coreIfReady()) this.core = make();
2224
+ else
2225
+ void loadCore().then(() => {
2226
+ if (this.stopped && !this.pending.length) return;
2227
+ const c = this.core = make();
2228
+ const queued = this.pending;
2229
+ this.pending = [];
2230
+ for (const p of queued) p(c);
2231
+ });
2232
+ }
2233
+ sockets = /* @__PURE__ */ new Map();
2234
+ timer = null;
2235
+ stopped = false;
2236
+ /** O núcleo desta casca; `null` até o wasm carregar (as entradas esperam em `pending`, em ordem). */
2237
+ core = null;
2238
+ pending = [];
2239
+ /** Roda `fn` com o núcleo: na hora se já carregou, senão na ordem em que foi pedido, quando carregar. */
2240
+ when(fn) {
2241
+ if (this.core) fn(this.core);
2242
+ else this.pending.push(fn);
2243
+ }
2244
+ env() {
2245
+ return [this.d.clock.now(), this.d.env.online(), this.d.env.visible(), this.random()];
2246
+ }
2247
+ /** Uma entrada pro núcleo; executa os efeitos devolvidos, em ordem; re-arma o timer. */
2248
+ run(input) {
2249
+ if (this.stopped) return;
2250
+ this.when((c) => this.exec(JSON.parse(input(c, this.env()))));
2251
+ }
2252
+ /** Executa uma lista de efeitos já devolvida (quando quem chamou precisou do JSON antes). */
2253
+ exec(fx) {
2254
+ for (const f of fx) this.one(f);
2255
+ this.arm();
2256
+ }
2257
+ /** Para tudo (depois do close do núcleo): sem timer, sem novas entradas. */
2258
+ stop() {
2259
+ this.stopped = true;
2260
+ this.disarm();
2261
+ if (!this.core) this.pending = [];
2262
+ }
2263
+ arm() {
2264
+ this.disarm();
2265
+ if (this.stopped || !this.core) return;
2266
+ const at = this.core.next_deadline();
2267
+ if (at < 0) return;
2268
+ this.timer = this.d.clock.setTimeout(() => {
2269
+ this.timer = null;
2270
+ this.run((c, e) => c.tick(...e));
2271
+ }, Math.max(0, at - this.d.clock.now()));
2272
+ }
2273
+ disarm() {
2274
+ if (this.timer !== null) {
2275
+ this.d.clock.clearTimeout(this.timer);
2276
+ this.timer = null;
2277
+ }
2278
+ }
2279
+ one(f) {
2280
+ const d = this.d;
2281
+ const chatId = this.chatId;
2282
+ switch (f.k) {
2283
+ case "token": {
2284
+ const req = f.req;
2285
+ d.token().then(
2286
+ (t) => this.run((c, e) => c.on_token(...e, req, true, t)),
2287
+ // o motivo decide: `revoked`/`missing`/`invalid` param de vez; o resto (rede, 500) entra no backoff
2288
+ (err) => this.run((c, e) => c.on_token(...e, req, false, err instanceof SmoothAgentAuthError ? err.reason : "error"))
2289
+ );
2290
+ return;
2291
+ }
2292
+ case "invalidateToken":
2293
+ d.invalidateToken?.();
2294
+ return;
2295
+ case "probe": {
2296
+ const req = f.req;
2297
+ d.probeAccess(chatId).then(
2298
+ (a) => this.run((c, e) => c.on_probe(...e, req, true, a)),
2299
+ () => this.run((c, e) => c.on_probe(...e, req, false, ""))
2300
+ );
2301
+ return;
2302
+ }
2303
+ case "range": {
2304
+ const { req, from, to } = f;
2305
+ d.eventsRange(chatId, from, to).then(
2306
+ (r) => this.run((c, e) => c.on_range(...e, req, true, JSON.stringify(r.events), r.range.from, r.range.to)),
2307
+ () => this.run((c, e) => c.on_range(...e, req, false, "[]", 0, 0))
2308
+ );
2309
+ return;
2310
+ }
2311
+ case "snapshot": {
2312
+ const req = f.req;
2313
+ d.snapshot(chatId).then(
2314
+ (s) => this.run((c, e) => c.on_snapshot(...e, req, true, JSON.stringify(s))),
2315
+ () => this.run((c, e) => c.on_snapshot(...e, req, false, ""))
2316
+ );
2317
+ return;
2318
+ }
2319
+ case "open": {
2320
+ const { conn, url, protocols } = f;
2321
+ return this.open(conn, url, protocols);
2322
+ }
2323
+ case "send": {
2324
+ const { conn, text } = f;
2325
+ const sock = this.sockets.get(conn);
2326
+ if (sock && sock.readyState === 1) sock.send(text);
2327
+ return;
2328
+ }
2329
+ case "close": {
2330
+ const { conn, code, reason } = f;
2331
+ const sock = this.sockets.get(conn);
2332
+ this.sockets.delete(conn);
2333
+ if (!sock) return;
2334
+ sock.onopen = sock.onmessage = sock.onclose = sock.onerror = null;
2335
+ try {
2336
+ sock.close(code, reason);
2337
+ } catch {
2338
+ }
2339
+ return;
2340
+ }
2341
+ default:
2342
+ this.handle(f);
2343
+ }
2344
+ }
2345
+ open(conn, url, protocols) {
2346
+ let sock;
2347
+ try {
2348
+ sock = this.d.openSocket(url, protocols);
2349
+ } catch {
2350
+ this.run((c, e) => c.on_open_failed(...e, conn));
2351
+ return;
2352
+ }
2353
+ this.sockets.set(conn, sock);
2354
+ sock.onopen = () => this.run((c, e) => c.on_open(...e, conn));
2355
+ sock.onmessage = (ev) => this.run((c, e) => c.on_message(...e, conn, String(ev.data)));
2356
+ sock.onerror = () => this.run((c, e) => c.on_error(...e, conn));
2357
+ sock.onclose = (ev) => {
2358
+ this.sockets.delete(conn);
2359
+ this.run((c, e) => c.on_close(...e, conn, ev.code, ev.reason ?? ""));
2360
+ };
2361
+ }
2362
+ };
2363
+
2364
+ // ../core-live/src/wasm/empty.ts
2365
+ var EMPTY_STATE_JSON = '{"seq":0,"chat":{"state":"idle"},"items":{},"order":[],"history":[],"tasks":{},"pending":{},"limits":{},"usage":{"chat":{}},"runs":[],"switches":[]}';
2366
+
2367
+ // ../core-live/src/backoff.ts
2368
+ var DEFAULT_BACKOFF = {
2369
+ baseMs: 250,
2370
+ factor: 2,
2371
+ capVisibleMs: 3e4,
2372
+ capHiddenMs: 3e5,
2373
+ stableMs: 1e4
2374
+ };
2375
+
2376
+ // ../core-live/src/stream.ts
2377
+ var newRef = () => `r_${uuidv7()}`;
2378
+ var ChatStream = class {
2379
+ constructor(d, opts, l) {
2380
+ this.d = d;
2381
+ this.opts = opts;
2382
+ this.l = l;
2383
+ const cfg = JSON.stringify(sessionConfig(d, opts));
2384
+ this.edge = new Edge(() => new (core()).LiveSession(cfg), d, opts.chatId, opts.random ?? Math.random, (f) => this.handle(f));
2385
+ this.unWake = d.env.onWake((why, awayMs) => this.edge.run((c, e) => c.wake(...e, why, awayMs ?? 0)));
2386
+ this.edge.run((c, e) => c.start(...e));
2387
+ }
2388
+ edge;
2389
+ waiting = /* @__PURE__ */ new Map();
2390
+ closed = false;
2391
+ unWake;
2392
+ // ------------------------------------------------------------------ API (a mesma de antes)
2393
+ get status() {
2394
+ return this.edge.core?.status() ?? (this.closed ? "closed" : "connecting");
2395
+ }
2396
+ get cursor() {
2397
+ return this.edge.core?.cursor() ?? this.opts.resumeFrom?.cursor ?? 0;
2398
+ }
2399
+ get via() {
2400
+ return this.edge.core?.via() || null;
2401
+ }
2402
+ get box() {
2403
+ const b = this.edge.core?.box_presence();
2404
+ return b ? JSON.parse(b) : null;
2405
+ }
2406
+ /**
2407
+ * Manda um comando (send/queue/stop/respond/resend/reset). Resolve com o `ack` — que só vem depois de
2408
+ * gravado no log. Cai o socket antes do ack: o núcleo reenvia o MESMO frame no próximo transporte; o
2409
+ * servidor devolve `duplicate`. Nunca rejeita por transporte; só por close()/revogação.
2410
+ */
2411
+ command(frame) {
2412
+ if (this.closed) return Promise.reject(new Error("stream closed"));
2413
+ return new Promise((resolve, reject) => {
2414
+ this.waiting.set(frame.ref, { resolve, reject });
2415
+ this.edge.run((c, e) => c.command(...e, JSON.stringify(frame)));
2416
+ });
2417
+ }
2418
+ /** Token do usuário renovado: vai pelo socket do conector sem derrubar. */
2419
+ tokenRenewed(token) {
2420
+ this.edge.run((c, e) => c.token_renewed(...e, token));
2421
+ }
2422
+ retry() {
2423
+ this.edge.run((c, e) => c.wake(...e, "manual", 0));
2424
+ }
2425
+ close() {
2426
+ if (this.closed) return;
2427
+ this.edge.run((c, e) => c.close(...e));
2428
+ this.closed = true;
2429
+ this.unWake();
2430
+ this.edge.stop();
2431
+ }
2432
+ handle(f) {
2433
+ const v = f.v;
2434
+ switch (f.k) {
2435
+ case "onSnapshot":
2436
+ return this.l.snapshot?.(v);
2437
+ case "onEvents":
2438
+ return this.l.events?.(v);
2439
+ case "onInbox":
2440
+ return this.l.inbox?.(v);
2441
+ case "onQueue":
2442
+ return this.l.queue?.(v);
2443
+ case "onBox":
2444
+ return this.l.box?.(v, f.via);
2445
+ case "onStatus":
2446
+ return this.l.status?.(v);
2447
+ case "onDebug":
2448
+ return this.l.debug?.(v);
2449
+ case "onViolation":
2450
+ return this.l.violation?.(v);
2451
+ case "onOther":
2452
+ return this.l.other?.(v);
2453
+ case "resolve": {
2454
+ const w = this.waiting.get(f.ref);
2455
+ this.waiting.delete(f.ref);
2456
+ return w?.resolve(v);
2457
+ }
2458
+ case "reject": {
2459
+ const w = this.waiting.get(f.ref);
2460
+ this.waiting.delete(f.ref);
2461
+ return w?.reject(new Error(String(f.v)));
2462
+ }
2463
+ }
2464
+ }
2465
+ };
2466
+ function sessionConfig(d, opts) {
2467
+ const b = opts.backoff ?? DEFAULT_BACKOFF;
2468
+ return {
2469
+ chatId: opts.chatId,
2470
+ connectorUrl: d.connectorUrl(opts.chatId),
2471
+ ...opts.resumeFrom ? { resumeCursor: opts.resumeFrom.cursor, resumeInboxVersion: opts.resumeFrom.inboxVersion } : {},
2472
+ includeRaw: opts.includeRaw ?? false,
2473
+ strict: opts.strict ?? false,
2474
+ pingEveryMs: opts.pingEveryMs,
2475
+ pongTimeoutMs: opts.pongTimeoutMs,
2476
+ switchGraceMs: opts.switchGraceMs,
2477
+ syncTimeoutMs: opts.syncTimeoutMs,
2478
+ gapTimeoutMs: opts.gapTimeoutMs,
2479
+ longAwayMs: opts.longAwayMs,
2480
+ ackTimeoutMs: opts.ackTimeoutMs,
2481
+ queueCheckEveryMs: opts.queueCheckEveryMs,
2482
+ queueCheckMinMs: opts.queueCheckMinMs,
2483
+ backoff: { baseMs: b.baseMs, factor: b.factor, capVisibleMs: b.capVisibleMs, capHiddenMs: b.capHiddenMs, stableMs: b.stableMs },
2484
+ has: { probeAccess: !!d.probeAccess, eventsRange: !!d.eventsRange, snapshot: !!d.snapshot }
2485
+ };
2486
+ }
2487
+
2488
+ // ../core-live/src/types.ts
2489
+ function toContentParts(content, attachments = []) {
2490
+ const parts = typeof content === "string" ? [{ type: "text", text: content }] : [...content];
2491
+ for (const fileId of attachments) parts.push({ type: "file", fileId });
2492
+ return parts;
2493
+ }
2494
+
2495
+ // ../core-live/src/watch.ts
2496
+ var SendNotConfirmedError = class extends Error {
2497
+ constructor(reason, messageId, content, mode, cause) {
2498
+ super(reason === "closed" ? "stream closed" : reason === "timeout" ? "send: sem confirma\xE7\xE3o no prazo" : "send: n\xE3o confirmado");
2499
+ this.reason = reason;
2500
+ this.messageId = messageId;
2501
+ this.content = content;
2502
+ this.mode = mode;
2503
+ this.cause = cause;
2504
+ }
2505
+ name = "SendNotConfirmedError";
2506
+ };
2507
+ var CommandAbortedError = class extends Error {
2508
+ constructor(ref) {
2509
+ super("stream closed");
2510
+ this.ref = ref;
2511
+ }
2512
+ name = "CommandAbortedError";
2513
+ };
2514
+ var SEND_FALLBACK_MS = 2e3;
2515
+ var REST_RETRY_MS = 5e3;
2516
+ var REST_RETRY_MAX_MS = 6e4;
2517
+ function safeCause(e) {
2518
+ const x = e ?? {};
2519
+ const out = new Error(typeof x.message === "string" ? x.message : String(e));
2520
+ if (typeof x.name === "string") out.name = x.name;
2521
+ if (typeof x.status === "number") out.status = x.status;
2522
+ if (typeof x.code === "string") out.code = x.code;
2523
+ return out;
2524
+ }
2525
+ var EMPTY_INBOX = { version: -1, pending: [], queue: [], notDelivered: [], responses: [] };
2526
+ var EMPTY_QUEUE = { version: -1, owner: "cold", turn: "idle", items: [], notDelivered: [] };
2527
+ var LiveChat = class {
2528
+ constructor(d, o) {
2529
+ this.d = d;
2530
+ this.o = o;
2531
+ this.state = {
2532
+ version: 0,
2533
+ // a timeline vazia do núcleo (forma completa: order, items, runs…) antes do wasm e do 1º snapshot
2534
+ timeline: JSON.parse(EMPTY_STATE_JSON),
2535
+ messages: [],
2536
+ effectiveSelection: { switchableNow: true },
2537
+ queue: EMPTY_QUEUE,
2538
+ inbox: EMPTY_INBOX,
2539
+ needsProvider: null,
2540
+ box: null,
2541
+ local: { sending: [] },
2542
+ history: { anchor: "end", items: [], hasBefore: false, hasAfter: false, loadingBefore: false, loadingAfter: false, newWhileDetached: 0 },
2543
+ sync: { status: "connecting", cursor: 0, via: null, violations: [] }
2544
+ };
2545
+ const cfg = sessionConfig(d, o);
2546
+ cfg.has.history = !!d.history;
2547
+ const wcfg = JSON.stringify({ ...cfg, pageSize: o.pageSize, maxWindow: o.maxWindow, refNonce: uuidv7(d.clock.now()).replace(/-/g, "") });
2548
+ this.edge = new Edge(() => new (core()).LiveWatch(wcfg), d, o.chatId, o.random ?? Math.random, (f) => this.handle(f));
2549
+ this.unWake = d.env.onWake((why, awayMs) => this.edge.run((c, e) => c.wake(...e, why, awayMs ?? 0)));
2550
+ this.edge.run((c, e) => c.start(...e));
2551
+ }
2552
+ edge;
2553
+ state;
2554
+ listeners = /* @__PURE__ */ new Set();
2555
+ eventTaps = /* @__PURE__ */ new Set();
2556
+ waiting = /* @__PURE__ */ new Map();
2557
+ historyWaiting = /* @__PURE__ */ new Map();
2558
+ /** os `send` esperando, NA ORDEM em que foram mandados (o Map guarda a ordem de inserção) */
2559
+ sends = /* @__PURE__ */ new Map();
2560
+ /** a corrente do REST: um pedido por vez, em ordem (B nunca passa na frente de A) */
2561
+ restBusy = false;
2562
+ restRetry = null;
2563
+ /** falhas de vez seguidas da corrente (a espera cresce; zera quando uma grava) */
2564
+ restFails = 0;
2565
+ /** gravados pelo REST e ainda em `local.sending` do núcleo (que não viu o ack): a tela mostra `pending` */
2566
+ restStored = /* @__PURE__ */ new Map();
2567
+ /** o `local.sending` como o núcleo mandou (antes da sobreposição do REST) */
2568
+ coreLocal = [];
2569
+ /** itens que vieram de páginas do histórico (não estão na timeline viva) */
2570
+ pageItems = /* @__PURE__ */ new Map();
2571
+ historyIds = [];
2572
+ closed = false;
2573
+ unWake;
2574
+ // ------------------------------------------------------------------ leitura
2575
+ getState = () => this.state;
2576
+ /** Compatível com `useSyncExternalStore(live.subscribe, live.getState)`. */
2577
+ subscribe = (cb) => {
2578
+ this.listeners.add(cb);
2579
+ return () => this.listeners.delete(cb);
2580
+ };
2581
+ /** Só chama quando o pedaço escolhido muda (a fila não re-renderiza a cada delta de texto — T3). */
2582
+ select(fn, cb, eq = Object.is) {
2583
+ let prev = fn(this.state);
2584
+ cb(prev);
2585
+ return this.subscribe((s) => {
2586
+ const next = fn(s);
2587
+ if (!eq(prev, next)) {
2588
+ prev = next;
2589
+ cb(next);
2590
+ }
2591
+ });
2592
+ }
2593
+ /** Eventos aplicados, em ordem (o `prompt()` e o `events()` usam). */
2594
+ tap(cb) {
2595
+ this.eventTaps.add(cb);
2596
+ return () => this.eventTaps.delete(cb);
2597
+ }
2598
+ get chatId() {
2599
+ return this.o.chatId;
2600
+ }
2601
+ // ------------------------------------------------------------------ comandos
2602
+ /**
2603
+ * Manda uma mensagem. Aparece na hora em `local.sending`; sai quando a inbox do log a mostra. Resolve quando
2604
+ * gravada: pelo socket ou, se ele não confirmar em `sendFallbackMs`, pelo REST com o mesmo messageId (o servidor
2605
+ * deduplica). `timeoutMs`: rejeita com `SendNotConfirmedError` ('timeout') se nada confirmou no prazo.
2606
+ *
2607
+ * O `timeoutMs` só desiste de ESPERAR: não cancela o envio pelo socket (o núcleo segue reenviando aquele frame
2608
+ * até o ack ou o `close()`), então a mensagem ainda pode chegar à fila depois do timeout — e, chegando, a ordem
2609
+ * relativa dela com os `send` seguintes não é garantida (o caminho do REST também não espera mais por ela).
2610
+ * Reenviar com o mesmo `messageId` é seguro (o servidor deduplica) — com o MESMO `metadata`: outro = `conflict`.
2611
+ *
2612
+ * `metadata`: chave → texto do app (até 16 chaves `^[A-Za-z0-9_.:-]{1,64}$`, sem o prefixo `sa.`; valores de até
2613
+ * 512 caracteres). Volta como `metadata` no item `user_message` e nos itens da fila; o agente/LLM NUNCA vê.
2614
+ * Fora dos limites = `rejected` `invalid_request`. `{}` = sem metadata.
2615
+ */
2616
+ async send(content, opts = {}) {
2617
+ const messageId = opts.messageId ?? newMessageId(this.d.clock.now());
2618
+ const parts = toContentParts(content, opts.attachments);
2619
+ const mode = opts.mode ?? "auto";
2620
+ const metadata = opts.metadata && Object.keys(opts.metadata).length ? { ...opts.metadata } : void 0;
2621
+ if (this.closed) throw new SendNotConfirmedError("closed", messageId, parts, mode);
2622
+ const r = await new Promise((resolve, reject) => {
2623
+ const prev = this.sends.get(messageId);
2624
+ if (prev && !prev.done) {
2625
+ prev.done = true;
2626
+ for (const t of prev.timers) this.d.clock.clearTimeout(t);
2627
+ }
2628
+ const ps = {
2629
+ messageId,
2630
+ content: parts,
2631
+ mode,
2632
+ ...metadata ? { metadata } : {},
2633
+ timers: [],
2634
+ rest: false,
2635
+ done: false,
2636
+ resolve: prev ? (x) => (prev.resolve(x), resolve(x)) : resolve,
2637
+ reject: prev ? (e) => (prev.reject(e), reject(e)) : reject
2638
+ };
2639
+ this.sends.set(messageId, ps);
2640
+ const fallback = this.o.sendFallbackMs ?? SEND_FALLBACK_MS;
2641
+ if (this.d.postMessage && Number.isFinite(fallback)) ps.timers.push(this.d.clock.setTimeout(() => this.viaRest(ps), Math.max(0, fallback)));
2642
+ if (opts.timeoutMs !== void 0 && Number.isFinite(opts.timeoutMs))
2643
+ ps.timers.push(this.d.clock.setTimeout(() => this.settleSend(ps, new SendNotConfirmedError("timeout", messageId, parts, mode)), Math.max(0, opts.timeoutMs)));
2644
+ this.waiting.set(`send:${messageId}`, {
2645
+ resolve: (x) => this.settleSend(ps, x),
2646
+ // o núcleo desistiu (fechou): vale o REST, se houver
2647
+ reject: (e) => this.coreGaveUp(ps, e)
2648
+ });
2649
+ this.edge.run((c, e) => c.send(...e, messageId, JSON.stringify(parts), mode, metadata ? JSON.stringify(metadata) : ""));
2650
+ });
2651
+ return { ...r, messageId };
2652
+ }
2653
+ /** Pede o caminho durável pra este send (e, pela ordem, pra todos os anteriores ainda esperando). */
2654
+ viaRest(ps) {
2655
+ if (ps.done || !this.d.postMessage) return;
2656
+ ps.rest = true;
2657
+ this.pumpRest();
2658
+ }
2659
+ /**
2660
+ * A corrente do REST, por chat: grava UM por vez, na ordem dos `send`. A cabeça é o send mais antigo ainda
2661
+ * esperando; se algum depois dela pediu o REST, ela vai antes (a fila no servidor fica na ordem em que o usuário
2662
+ * mandou). A cabeça confirmada (por qualquer caminho) libera a próxima. Falhou de vez: com o chat aberto a corrente
2663
+ * para e tenta de novo com espera crescente, 5 s até 60 s (o socket também segue tentando); fechado, a cabeça e TODAS as de trás
2664
+ * rejeitam — nenhuma pula a que não foi gravada.
2665
+ */
2666
+ pumpRest() {
2667
+ if (this.restBusy || !this.d.postMessage) return;
2668
+ const order = [...this.sends.values()].filter((x) => !x.done);
2669
+ const head = order[0];
2670
+ if (!head || !order.some((x) => x.rest)) return;
2671
+ if (this.restRetry !== null) {
2672
+ this.d.clock.clearTimeout(this.restRetry);
2673
+ this.restRetry = null;
2674
+ }
2675
+ this.restBusy = true;
2676
+ this.d.postMessage(this.o.chatId, { clientMessageId: head.messageId, content: head.content, mode: head.mode, ...head.metadata ? { metadata: head.metadata } : {} }).then(
2677
+ (r) => {
2678
+ this.restBusy = false;
2679
+ this.restFails = 0;
2680
+ if (r.status === "accepted" || r.status === "duplicate") this.markStored(head.messageId, r.version ?? r.inboxVersion);
2681
+ this.settleSend(head, r);
2682
+ this.pumpRest();
2683
+ },
2684
+ (e) => {
2685
+ this.restBusy = false;
2686
+ if (head.done) return this.pumpRest();
2687
+ if (this.closed) {
2688
+ const cause = safeCause(e);
2689
+ this.restBusy = true;
2690
+ for (const x of [...this.sends.values()].filter((y) => !y.done)) this.settleSend(x, new SendNotConfirmedError("failed", x.messageId, x.content, x.mode, cause));
2691
+ this.restBusy = false;
2692
+ return;
2693
+ }
2694
+ const wait = Math.min(REST_RETRY_MAX_MS, REST_RETRY_MS * 2 ** this.restFails++);
2695
+ this.restRetry = this.d.clock.setTimeout(() => {
2696
+ this.restRetry = null;
2697
+ this.pumpRest();
2698
+ }, wait);
2699
+ }
2700
+ );
2701
+ }
2702
+ coreGaveUp(ps, e) {
2703
+ if (ps.done) return;
2704
+ if (this.d.postMessage) this.viaRest(ps);
2705
+ else this.settleSend(ps, new SendNotConfirmedError("closed", ps.messageId, ps.content, ps.mode, e));
2706
+ }
2707
+ settleSend(ps, r) {
2708
+ if (ps.done) return;
2709
+ ps.done = true;
2710
+ for (const t of ps.timers) this.d.clock.clearTimeout(t);
2711
+ if (this.sends.get(ps.messageId) === ps) this.sends.delete(ps.messageId);
2712
+ if (r instanceof Error) ps.reject(r);
2713
+ else ps.resolve(r);
2714
+ if (!this.restBusy) this.pumpRest();
2715
+ }
2716
+ /** Gravado pelo REST: no `local.sending` passa de `sending` a `pending` (o núcleo não viu o ack). */
2717
+ markStored(messageId, version) {
2718
+ if (this.closed || !this.coreLocal.some((l) => l.messageId === messageId)) return;
2719
+ this.restStored.set(messageId, version);
2720
+ this.state = { ...this.state, local: { sending: this.overlayLocal() } };
2721
+ for (const l of this.listeners) l(this.state);
2722
+ }
2723
+ overlayLocal() {
2724
+ for (const id of [...this.restStored.keys()]) if (!this.coreLocal.some((l) => l.messageId === id)) this.restStored.delete(id);
2725
+ if (!this.restStored.size) return this.coreLocal;
2726
+ return this.coreLocal.map((l) => {
2727
+ if (l.status !== "sending" || !this.restStored.has(l.messageId)) return l;
2728
+ const v = this.restStored.get(l.messageId);
2729
+ return { ...l, status: "pending", ...v !== void 0 ? { ackVersion: v } : {} };
2730
+ });
2731
+ }
2732
+ stop() {
2733
+ const stopId = uuidv7(this.d.clock.now());
2734
+ return this.command({ t: "stop", ref: `stop:${stopId}`, chatId: this.o.chatId, stopId });
2735
+ }
2736
+ respond(requestId, answer) {
2737
+ return this.command({ t: "respond", ref: `respond:${requestId}:${uuidv7(this.d.clock.now())}`, chatId: this.o.chatId, requestId, answer });
2738
+ }
2739
+ /** Sessão nova do provedor (era o recycle); `clearHistory` também esconde o histórico até aqui. */
2740
+ reset(opts = {}) {
2741
+ const resetId = uuidv7(this.d.clock.now());
2742
+ return this.command({ t: "reset", ref: `reset:${resetId}`, chatId: this.o.chatId, resetId, ...opts.clearHistory ? { clearHistory: true } : {} });
2743
+ }
2744
+ /**
2745
+ * Troca de agente (§17.4): um comando da fila no MESMO canal ordenado do `send` — "troquei e mandei" chega
2746
+ * na ordem, sem esperar nada. O dono aplica antes do próximo run; uma troca nova substitui a pendente
2747
+ * (`queue.pendingSwitch`). A forma é a do REST (`agentId`, `model?`, `effort?`): o servidor completa o resto e
2748
+ * valida o acesso; `provider`/`agentName` não vão (o servidor ignoraria).
2749
+ */
2750
+ switchAgent(to) {
2751
+ const switchId = uuidv7(this.d.clock.now());
2752
+ return this.wait(`switch:${switchId}`, (c, e) => c.switch_agent(...e, switchId, JSON.stringify(to)));
2753
+ }
2754
+ /**
2755
+ * Troca SÓ modelo/esforço do agente de agora (o que não vier fica o de agora): o mesmo comando `switch`, sem
2756
+ * `agentId` — o servidor completa com o agente atual (a box aplica ao vivo, sem sessão nova). `null` = voltar
2757
+ * ao padrão do agente (vai no frame como `reset`).
2758
+ */
2759
+ switchModel(change) {
2760
+ const switchId = uuidv7(this.d.clock.now());
2761
+ return this.wait(`switch:${switchId}`, (c, e) => c.switch_model(...e, switchId, JSON.stringify(change)));
2762
+ }
2763
+ /** Cancela a troca agendada (`queue.pendingSwitch`): o comando `cancelSwitch`, no mesmo canal ordenado. */
2764
+ cancelSwitch() {
2765
+ const switchId = uuidv7(this.d.clock.now());
2766
+ return this.wait(`switch:${switchId}`, (c, e) => c.cancel_switch(...e, switchId));
2767
+ }
2768
+ resend(messageId) {
2769
+ return this.command({ t: "resend", ref: newRef(), chatId: this.o.chatId, messageId });
2770
+ }
2771
+ /** Fila: sempre em cima da versão que a tela está vendo; `conflict` traz (e aplica) o estado novo. */
2772
+ queue = {
2773
+ reorder: (order) => this.queueOp({ kind: "reorder", order }),
2774
+ edit: (messageId, content) => this.queueOp({ kind: "edit", messageId, content: toContentParts(content) }),
2775
+ remove: (messageId) => this.queueOp({ kind: "remove", messageId }),
2776
+ sendNow: (messageId) => this.queueOp({ kind: "sendNow", messageId })
2777
+ };
2778
+ queueOp(op) {
2779
+ if (this.closed) return Promise.reject(new Error("stream closed"));
2780
+ return new Promise(
2781
+ (resolve, reject) => this.edge.when((c) => this.wait(c.next_queue_ref(), (w, e) => w.queue_op(...e, JSON.stringify(op))).then(resolve, reject))
2782
+ );
2783
+ }
2784
+ command(frame) {
2785
+ return this.wait(frame.ref, (c, e) => c.command(...e, JSON.stringify(frame)));
2786
+ }
2787
+ wait(ref, input) {
2788
+ if (this.closed) return Promise.reject(new Error("stream closed"));
2789
+ return new Promise((resolve, reject) => {
2790
+ this.waiting.set(ref, { resolve, reject });
2791
+ this.edge.run(input);
2792
+ });
2793
+ }
2794
+ retry() {
2795
+ this.edge.run((c, e) => c.wake(...e, "manual", 0));
2796
+ }
2797
+ tokenRenewed(token) {
2798
+ this.edge.run((c, e) => c.token_renewed(...e, token));
2799
+ }
2800
+ /**
2801
+ * Fecha. Nenhuma espera fica pendurada: o `send` não confirmado vai pelo REST (mesmo messageId) e resolve quando
2802
+ * gravado; sem REST, rejeita com `SendNotConfirmedError` ('closed', com a mensagem). Os demais comandos
2803
+ * rejeitam com `CommandAbortedError`.
2804
+ */
2805
+ close() {
2806
+ if (this.closed) return;
2807
+ this.edge.run((c, e) => c.close(...e));
2808
+ this.closed = true;
2809
+ this.unWake();
2810
+ this.edge.stop();
2811
+ this.listeners.clear();
2812
+ this.eventTaps.clear();
2813
+ const left = [...this.waiting];
2814
+ this.waiting.clear();
2815
+ for (const [ref, w] of left) w.reject(new CommandAbortedError(ref));
2816
+ for (const ps of [...this.sends.values()]) this.coreGaveUp(ps, new Error("stream closed"));
2817
+ this.pumpRest();
2818
+ }
2819
+ // ------------------------------------------------------------------ histórico (§4.9)
2820
+ history = {
2821
+ /** Rola pra cima: página de itens fechados antes do primeiro da janela. */
2822
+ loadOlder: () => this.page((c) => c.load_older()),
2823
+ /** Só na janela parada: página depois do último item; encontrando o ao vivo, recola no fim. */
2824
+ loadNewer: () => this.page((c) => c.load_newer()),
2825
+ /** Abre "em volta" de uma mensagem ou evento. O ao vivo continua aplicando por baixo. */
2826
+ jumpTo: (anchor) => this.page((c) => c.jump_to(JSON.stringify(anchor))),
2827
+ /** Volta pro fim (cola no ao vivo). */
2828
+ jumpToEnd: () => this.page((c) => c.jump_to_end())
2829
+ };
2830
+ /** Roda um pedido de histórico; resolve quando a página chegou e foi aplicada (ou na hora, se não pediu). */
2831
+ page(input) {
2832
+ if (this.closed) return Promise.resolve();
2833
+ return new Promise(
2834
+ (resolve) => this.edge.when((c) => {
2835
+ const fx = JSON.parse(input(c));
2836
+ const req = fx.find((f) => f.k === "history")?.req;
2837
+ if (req === void 0) resolve();
2838
+ else this.historyWaiting.set(req, resolve);
2839
+ this.edge.exec(fx);
2840
+ })
2841
+ );
2842
+ }
2843
+ // ------------------------------------------------------------------ efeitos do núcleo
2844
+ handle(f) {
2845
+ switch (f.k) {
2846
+ case "patch":
2847
+ return this.applyPatch(f.v);
2848
+ case "tap": {
2849
+ const evs = f.v;
2850
+ for (const t of this.eventTaps) t(evs);
2851
+ return;
2852
+ }
2853
+ case "history": {
2854
+ const req = f.req;
2855
+ const finish = (input) => {
2856
+ if (!this.closed && this.edge.core) this.edge.exec(JSON.parse(input(this.edge.core)));
2857
+ const w = this.historyWaiting.get(req);
2858
+ this.historyWaiting.delete(req);
2859
+ w?.();
2860
+ };
2861
+ this.d.history(this.o.chatId, f.q).then(
2862
+ (page) => finish((c) => c.on_history(req, true, JSON.stringify(page))),
2863
+ (e) => finish((c) => c.on_history(req, false, e instanceof Error ? e.message : String(e)))
2864
+ );
2865
+ return;
2866
+ }
2867
+ case "onStatus":
2868
+ if (f.v === "auth_failed") this.o.onAuthFailed?.();
2869
+ return;
2870
+ case "onDebug":
2871
+ return this.o.onDebug?.(f.v);
2872
+ case "onViolation":
2873
+ return this.o.onViolation?.(f.v);
2874
+ case "resolve": {
2875
+ const w = this.waiting.get(f.ref);
2876
+ this.waiting.delete(f.ref);
2877
+ return w?.resolve(f.v);
2878
+ }
2879
+ case "reject": {
2880
+ const w = this.waiting.get(f.ref);
2881
+ this.waiting.delete(f.ref);
2882
+ return w?.reject(String(f.v) === "stream closed" ? new CommandAbortedError(f.ref) : new Error(String(f.v)));
2883
+ }
2884
+ }
2885
+ }
2886
+ applyPatch(p) {
2887
+ const prev = this.state;
2888
+ let timeline = prev.timeline;
2889
+ if (p.timeline && "replace" in p.timeline) {
2890
+ timeline = p.timeline.replace;
2891
+ } else if (p.timeline) {
2892
+ const t = p.timeline;
2893
+ timeline = { ...timeline, ...t.set };
2894
+ for (const k of t.del) delete timeline[k];
2895
+ if (Object.keys(t.items).length) timeline.items = { ...timeline.items, ...t.items };
2896
+ }
2897
+ let history = prev.history;
2898
+ if (p.history) {
2899
+ const { ids, items, ...flags } = p.history;
2900
+ for (const [id, it] of Object.entries(items ?? {})) this.pageItems.set(id, it);
2901
+ this.historyIds = ids;
2902
+ history = { ...flags, items: [] };
2903
+ }
2904
+ if (p.history || p.timeline) {
2905
+ const live = timeline.items ?? {};
2906
+ history = { ...history, items: this.historyIds.map((id) => live[id] ?? this.pageItems.get(id)).filter((x) => x !== void 0) };
2907
+ }
2908
+ this.state = {
2909
+ version: p.version,
2910
+ timeline,
2911
+ messages: p.messages ?? prev.messages,
2912
+ effectiveSelection: p.effectiveSelection ?? prev.effectiveSelection,
2913
+ queue: p.queue ?? prev.queue,
2914
+ inbox: p.inbox ?? prev.inbox,
2915
+ needsProvider: p.needsProvider !== void 0 ? p.needsProvider : prev.needsProvider,
2916
+ box: p.box !== void 0 ? p.box : prev.box,
2917
+ local: p.local ? { sending: (this.coreLocal = p.local, this.overlayLocal()) } : prev.local,
2918
+ history,
2919
+ sync: p.sync ?? prev.sync
2920
+ };
2921
+ for (const l of this.listeners) l(this.state);
2922
+ }
2923
+ };
2924
+
2925
+ // ../core-live/src/prompt.ts
2926
+ var PromptRejectedError = class extends Error {
2927
+ constructor(code, message) {
2928
+ super(message);
2929
+ this.code = code;
2930
+ this.name = "PromptRejectedError";
2931
+ }
2932
+ };
2933
+ var RunHandle = class {
2934
+ constructor(live, content, opts = {}, onSettled) {
2935
+ this.live = live;
2936
+ this.onSettled = onSettled;
2937
+ this.result = new Promise((res, rej) => {
2938
+ this.resolve = res;
2939
+ this.reject = rej;
2940
+ });
2941
+ this.result.catch(() => {
2942
+ });
2943
+ this.untap = live.tap((evs) => evs.forEach((e) => this.onEvent(e)));
2944
+ live.send(content, opts).then((r) => {
2945
+ this.messageId = r.messageId;
2946
+ if (r.status === "rejected") return this.fail(new PromptRejectedError(r.code, r.message));
2947
+ if (r.status === "conflict") return this.fail(new PromptRejectedError("conflict", "conflict"));
2948
+ this.watchQueue();
2949
+ }).catch((e) => this.fail(e));
2950
+ if (opts.messageId) this.messageId = opts.messageId;
2951
+ }
2952
+ result;
2953
+ state = "sending";
2954
+ messageId = "";
2955
+ runId;
2956
+ resolve;
2957
+ reject;
2958
+ handlers = {};
2959
+ buffer = [];
2960
+ wakeIterators = [];
2961
+ text = "";
2962
+ items = [];
2963
+ untap;
2964
+ unselect = null;
2965
+ on(type, cb) {
2966
+ ;
2967
+ (this.handlers[type] ??= []).push(cb);
2968
+ return this;
2969
+ }
2970
+ /** STOP do chat (o run é dele). O `result` resolve com `stopped` quando o run fechar. */
2971
+ stop() {
2972
+ return this.live.stop();
2973
+ }
2974
+ /** Para de ouvir; o agente segue. O `result` resolve com `cancelled`. */
2975
+ cancel() {
2976
+ this.settle("cancelled");
2977
+ }
2978
+ [Symbol.asyncIterator]() {
2979
+ let i = 0;
2980
+ return {
2981
+ next: () => new Promise((resolve) => {
2982
+ const pull = () => {
2983
+ if (i < this.buffer.length) return resolve({ value: this.buffer[i++], done: false });
2984
+ if (this.state === "done") return resolve({ value: void 0, done: true });
2985
+ this.wakeIterators.push(pull);
2986
+ };
2987
+ pull();
2988
+ })
2989
+ };
2990
+ }
2991
+ // ------------------------------------------------------------------
2992
+ watchQueue() {
2993
+ const mine = (q) => q.messageId === this.messageId;
2994
+ this.unselect = this.live.select(
2995
+ (s) => {
2996
+ const nd = s.queue?.notDelivered?.find(mine) ?? s.inbox.notDelivered?.find(mine);
2997
+ if (nd) return `not_delivered:${nd.notDeliveredReason ?? ""}`;
2998
+ const q = s.queue?.items?.find(mine);
2999
+ return q && q.mode === "queue" || s.inbox.queue.some(mine) ? "queued" : "";
3000
+ },
3001
+ (where) => {
3002
+ if (where.startsWith("not_delivered:") && !this.runId) {
3003
+ const reason = where.slice("not_delivered:".length);
3004
+ return this.settle("not_delivered", void 0, void 0, reason || void 0);
3005
+ }
3006
+ if (where === "queued" && this.state === "sending") {
3007
+ this.state = "queued";
3008
+ this.emit({ type: "queued" });
3009
+ }
3010
+ }
3011
+ );
3012
+ }
3013
+ onEvent(e) {
3014
+ if (this.state === "done") return;
3015
+ const d = e.data ?? {};
3016
+ if (!this.runId) {
3017
+ const item = d.item;
3018
+ const trigger = d.trigger;
3019
+ const read = (e.type === "item.started" || e.type === "item.completed") && item?.kind === "user_message" && item.messageId === this.messageId;
3020
+ if (this.messageId !== "" && (e.type === "run.started" && trigger?.messageIds?.includes(this.messageId) || read)) {
3021
+ this.runId = e.runId ?? d.runId ?? item?.runId;
3022
+ if (this.runId) {
3023
+ this.state = "running";
3024
+ this.emit({ type: "started", runId: this.runId });
3025
+ }
3026
+ }
3027
+ if (!this.runId) return;
3028
+ }
3029
+ const runOf = e.runId ?? d.runId;
3030
+ if (runOf !== this.runId) return;
3031
+ this.emit({ type: "event", event: e });
3032
+ if (e.type === "item.delta") {
3033
+ const delta = d.delta;
3034
+ const piece = delta ? delta.path === "text" ? delta.append : void 0 : d.text;
3035
+ if (piece) {
3036
+ this.text += piece;
3037
+ this.emit({ type: "text", delta: piece, text: this.text });
3038
+ }
3039
+ } else if (e.type === "item.completed") {
3040
+ const item = d.item ?? d;
3041
+ this.items.push(item);
3042
+ this.emit({ type: "item", item });
3043
+ } else if (e.type === "run.completed") {
3044
+ const status = d.status ?? "completed";
3045
+ this.settle(status, d.usage, d.error);
3046
+ }
3047
+ }
3048
+ /**
3049
+ * O texto do run = os itens `text` fechados. Um steer no Codex CORTA a resposta em andamento
3050
+ * (`steerBoundary: 'model_call'`): o parcial fecha `interrupted` e outra resposta começa já com o
3051
+ * steer — a resposta final é a que completou; o parcial cortado só entra se não houver outra.
3052
+ */
3053
+ finalText() {
3054
+ const texts = this.items.filter(
3055
+ (i) => typeof i === "object" && i !== null && i.kind === "text"
3056
+ );
3057
+ if (!texts.length) return this.text;
3058
+ const done = texts.filter((i) => i.status !== "interrupted");
3059
+ return (done.length ? done : texts).map((i) => i.text).join("");
3060
+ }
3061
+ settle(status, usage, error, notDeliveredReason) {
3062
+ if (this.state === "done") return;
3063
+ const result = {
3064
+ status,
3065
+ messageId: this.messageId,
3066
+ text: this.finalText(),
3067
+ items: this.items,
3068
+ ...this.runId ? { runId: this.runId } : {},
3069
+ ...usage !== void 0 ? { usage } : {},
3070
+ ...error !== void 0 ? { error } : {},
3071
+ ...notDeliveredReason ? { notDeliveredReason } : {}
3072
+ };
3073
+ this.emit({ type: "done", result });
3074
+ this.state = "done";
3075
+ this.cleanup();
3076
+ this.resolve(result);
3077
+ }
3078
+ fail(e) {
3079
+ if (this.state === "done") return;
3080
+ this.state = "done";
3081
+ this.cleanup();
3082
+ this.reject(e);
3083
+ }
3084
+ cleanup() {
3085
+ this.untap();
3086
+ this.unselect?.();
3087
+ const wake = this.wakeIterators;
3088
+ this.wakeIterators = [];
3089
+ wake.forEach((w) => w());
3090
+ this.onSettled?.();
3091
+ }
3092
+ emit(ev) {
3093
+ this.buffer.push(ev);
3094
+ for (const h of this.handlers[ev.type] ?? []) {
3095
+ try {
3096
+ h(ev);
3097
+ } catch {
3098
+ }
3099
+ }
3100
+ const wake = this.wakeIterators;
3101
+ this.wakeIterators = [];
3102
+ wake.forEach((w) => w());
3103
+ }
3104
+ };
3105
+
3106
+ // ../core-live/src/feed.ts
3107
+ var ChatListLive = class {
3108
+ constructor(d, filter = {}) {
3109
+ this.d = d;
3110
+ const fcfg = JSON.stringify({ url: d.url, ...filter.agentId ? { agentId: filter.agentId } : {} });
3111
+ const deps = { connectorUrl: () => d.url, openSocket: d.openSocket, token: d.token, invalidateToken: d.invalidateToken, clock: d.clock, env: d.env };
3112
+ this.edge = new Edge(() => new (core()).LiveFeed(fcfg), deps, "", Math.random, (fx) => {
3113
+ if (fx.k !== "feedState") return;
3114
+ this.state = fx.v;
3115
+ for (const l of this.listeners) l(this.state);
3116
+ });
3117
+ this.unWake = d.env.onWake((why, awayMs) => this.edge.run((c, e) => c.wake(...e, why, awayMs ?? 0)));
3118
+ this.edge.run((c, e) => c.start(...e));
3119
+ }
3120
+ edge;
3121
+ state = { version: -1, rows: [], status: "connecting" };
3122
+ listeners = /* @__PURE__ */ new Set();
3123
+ unWake;
3124
+ closed = false;
3125
+ getState = () => this.state;
3126
+ subscribe = (cb) => {
3127
+ this.listeners.add(cb);
3128
+ return () => this.listeners.delete(cb);
3129
+ };
3130
+ close() {
3131
+ if (this.closed) return;
3132
+ this.edge.run((c, e) => c.close(...e));
3133
+ this.closed = true;
3134
+ this.unWake();
3135
+ this.edge.stop();
3136
+ }
3137
+ };
3138
+
3139
+ // ../core-live/src/client.ts
3140
+ function restTransient(e) {
3141
+ const st = e?.status;
3142
+ return st === void 0 || st === 408 || st === 429 || st >= 500;
3143
+ }
3144
+ var LiveClient = class {
3145
+ constructor(o) {
3146
+ this.o = o;
3147
+ this.clock = o.clock ?? systemClock;
3148
+ this.tokens = new TokenSource({ token: o.token, getToken: o.getToken, clock: this.clock });
3149
+ this.fetch = authedFetch(this.tokens, o.fetch ?? globalThis.fetch.bind(globalThis));
3150
+ this.api = `${o.baseUrl.replace(/\/$/, "")}/v3`;
3151
+ void loadCore().catch(() => {
3152
+ });
3153
+ this.tokens.onRenew((t) => {
3154
+ for (const e of this.entries.values()) e.live.tokenRenewed(t);
3155
+ });
3156
+ }
3157
+ tokens;
3158
+ /** `fetch` com o token e a regra do 401 (a SDK gerada usa o mesmo). */
3159
+ fetch;
3160
+ clock;
3161
+ entries = /* @__PURE__ */ new Map();
3162
+ lists = /* @__PURE__ */ new Set();
3163
+ api;
3164
+ /** O estado ao vivo do chat. Chame `close()` no handle quando a tela desmontar. */
3165
+ watch(chatId) {
3166
+ let e = this.entries.get(chatId);
3167
+ if (e) {
3168
+ e.refs++;
3169
+ if (e.closeTimer !== null) {
3170
+ this.clock.clearTimeout(e.closeTimer);
3171
+ e.closeTimer = null;
3172
+ }
3173
+ } else {
3174
+ e = { live: new LiveChat(this.deps(), this.watchOptions(chatId)), refs: 1, closeTimer: null };
3175
+ this.entries.set(chatId, e);
3176
+ }
3177
+ const entry = e;
3178
+ let released = false;
3179
+ const release = () => {
3180
+ if (released) return;
3181
+ released = true;
3182
+ this.release(chatId, entry);
3183
+ };
3184
+ return new Proxy(entry.live, {
3185
+ get(target, key) {
3186
+ if (key === "release") return release;
3187
+ if (key === "close") return release;
3188
+ const v = Reflect.get(target, key, target);
3189
+ return typeof v === "function" ? v.bind(target) : v;
3190
+ }
3191
+ });
3192
+ }
3193
+ /**
3194
+ * Eventos crus, já sem duplicado/buraco e com a troca de transporte. Termina no `return()`/break.
3195
+ * - `after`: começa DEPOIS deste seq (retomar de onde parou: todo evento de `after+1` em diante, sem snapshot);
3196
+ * sem `after`, começa no estado atual (o snapshot do servidor; `onSnapshot(seq)` diz até onde ele cobre).
3197
+ * - `onSnapshot(seq)`: o servidor mandou um snapshot em vez dos eventos — os anteriores a `seq` NÃO vêm
3198
+ * (início sem `after`, ou resync depois de um buraco que não fechou). Nunca pula em silêncio (M46).
3199
+ * - `includeRaw`: os eventos trazem o `raw` do provedor.
3200
+ * Um socket próprio (não o do `watch()`), pra o cursor ser só dele.
3201
+ */
3202
+ async *events(chatId, o = {}) {
3203
+ const queue = [];
3204
+ let wake = null;
3205
+ const stream = new ChatStream(
3206
+ this.deps(),
3207
+ {
3208
+ ...this.o.stream,
3209
+ chatId,
3210
+ ...o.includeRaw ? { includeRaw: true } : {},
3211
+ ...o.after !== void 0 ? { resumeFrom: { cursor: o.after, inboxVersion: -1 } } : {},
3212
+ ...this.o.strict ? { strict: true } : {}
3213
+ },
3214
+ {
3215
+ events: (evs) => {
3216
+ queue.push(...evs);
3217
+ wake?.();
3218
+ },
3219
+ snapshot: (s) => o.onSnapshot?.(s.seq),
3220
+ status: (st) => {
3221
+ if (st === "auth_failed") {
3222
+ this.tokens.markRevoked();
3223
+ this.o.onAuthRevoked?.();
3224
+ }
3225
+ },
3226
+ debug: (e) => this.o.onDebug?.(chatId, e),
3227
+ violation: (v) => this.o.onViolation?.(chatId, v)
3228
+ }
3229
+ );
3230
+ const unRenew = this.tokens.onRenew((t) => stream.tokenRenewed(t));
3231
+ try {
3232
+ for (; ; ) {
3233
+ while (queue.length) yield queue.shift();
3234
+ await new Promise((r) => wake = r);
3235
+ wake = null;
3236
+ }
3237
+ } finally {
3238
+ unRenew?.();
3239
+ stream.close();
3240
+ }
3241
+ }
3242
+ /** Manda e acompanha só esse run. `result` nunca rejeita por transporte. */
3243
+ prompt(chatId, content, opts = {}) {
3244
+ const h = this.watch(chatId);
3245
+ return new RunHandle(h, content, opts, () => h.release());
3246
+ }
3247
+ /** A lista lateral ao vivo (UserFeed): título, estado, esperando o quê, não lidas. Filtro por agente aqui. */
3248
+ watchList(filter = {}) {
3249
+ const d = this.deps();
3250
+ const list = new ChatListLive(
3251
+ { url: `${this.api.replace(/^http/, "ws")}/me/feed`, openSocket: d.openSocket, token: d.token, invalidateToken: d.invalidateToken, clock: d.clock, env: d.env },
3252
+ filter
3253
+ );
3254
+ this.lists.add(list);
3255
+ return list;
3256
+ }
3257
+ /** Marca como lido até `seq` (vale pra todos os dispositivos do usuário; o feed atualiza o unreadCount). */
3258
+ async markRead(chatId, seq) {
3259
+ await this.json(`/chats/${encodeURIComponent(chatId)}/read`, { method: "POST", body: JSON.stringify({ seq }), headers: { "Content-Type": "application/json" } });
3260
+ }
3261
+ /** Fecha tudo agora. */
3262
+ close() {
3263
+ for (const e of this.entries.values()) {
3264
+ if (e.closeTimer !== null) this.clock.clearTimeout(e.closeTimer);
3265
+ e.live.close();
3266
+ }
3267
+ this.entries.clear();
3268
+ for (const l of this.lists) l.close();
3269
+ this.lists.clear();
3270
+ }
3271
+ release(chatId, e) {
3272
+ if (--e.refs > 0) return;
3273
+ e.closeTimer = this.clock.setTimeout(() => {
3274
+ if (e.refs > 0 || this.entries.get(chatId) !== e) return;
3275
+ e.live.close();
3276
+ this.entries.delete(chatId);
3277
+ }, this.o.keepAliveMs ?? 3e5);
3278
+ }
3279
+ watchOptions(chatId) {
3280
+ return {
3281
+ ...this.o.stream,
3282
+ chatId,
3283
+ onDebug: (e) => this.o.onDebug?.(chatId, e),
3284
+ ...this.o.strict ? { strict: true } : {},
3285
+ onViolation: (v) => this.o.onViolation?.(chatId, v),
3286
+ onAuthFailed: () => {
3287
+ this.tokens.markRevoked();
3288
+ this.o.onAuthRevoked?.();
3289
+ }
3290
+ };
3291
+ }
3292
+ deps() {
3293
+ const wsBase = this.api.replace(/^http/, "ws");
3294
+ const WS = this.o.WebSocket ?? globalThis.WebSocket;
3295
+ if (!WS) throw new Error("SmoothAgent: sem WebSocket neste ambiente \u2014 passe `WebSocket` nas op\xE7\xF5es");
3296
+ const openSocket = (url, protocols) => new WS(url, protocols);
3297
+ return {
3298
+ connectorUrl: (id) => `${wsBase}/chats/${encodeURIComponent(id)}/live`,
3299
+ openSocket,
3300
+ token: () => this.tokens.get(),
3301
+ invalidateToken: () => this.tokens.invalidate(),
3302
+ clock: this.clock,
3303
+ env: this.o.env ?? browserEnv() ?? serverEnv,
3304
+ eventsRange: (id, from, to) => this.json(`/chats/${encodeURIComponent(id)}/events/range?after=${from - 1}&until=${to}`),
3305
+ snapshot: (id) => this.json(`/chats/${encodeURIComponent(id)}/snapshot`),
3306
+ probeAccess: async (id) => {
3307
+ const res = await this.fetch(`${this.api}/chats/${encodeURIComponent(id)}`, { headers: { Accept: "application/json" } });
3308
+ if (res.status === 401) return "unauthorized";
3309
+ if (res.status === 403 || res.status === 404) return "forbidden";
3310
+ return "ok";
3311
+ },
3312
+ history: async (id, q) => fromControlPage(id, await this.json(`/chats/${encodeURIComponent(id)}/history?${historyQs(q)}`)),
3313
+ postMessage: (id, m) => this.postMessage(id, m)
3314
+ };
3315
+ }
3316
+ /**
3317
+ * O caminho durável do `send` (REST `SendMessage`): a mesma fila fria do ChatLog, deduplicada pelo
3318
+ * `clientMessageId` (= o messageId do socket) e pela Idempotency-Key (a mesma). Falha passageira: repete com
3319
+ * espera (`untilStored`) e, esgotado, rejeita; recusa do servidor = `rejected` com o código do §6.
3320
+ */
3321
+ async postMessage(id, m) {
3322
+ const call = () => this.json(`/chats/${encodeURIComponent(id)}/messages`, {
3323
+ method: "POST",
3324
+ body: JSON.stringify(m),
3325
+ headers: { "Content-Type": "application/json", "Idempotency-Key": m.clientMessageId }
3326
+ });
3327
+ try {
3328
+ const r = await untilStored(call, { clock: this.clock, isTransient: (e) => restTransient(e) });
3329
+ const v = r.inboxVersion ?? 0;
3330
+ return r.status === "duplicate" ? { status: "duplicate", messageId: m.clientMessageId, inboxVersion: v } : { status: "accepted", messageId: m.clientMessageId, inboxVersion: v };
3331
+ } catch (e) {
3332
+ if (restTransient(e)) throw e;
3333
+ const err = e;
3334
+ const code = KNOWN_ERROR_CODES.includes(err.code ?? "") ? err.code : "internal";
3335
+ return { status: "rejected", code, message: err.message ?? code };
3336
+ }
3337
+ }
3338
+ async json(path, init) {
3339
+ const res = await this.fetch(`${this.api}${path}`, { ...init, headers: { Accept: "application/json", ...init?.headers ?? {} } });
3340
+ if (!res.ok) {
3341
+ const body = await res.json().catch(() => ({}));
3342
+ throw Object.assign(new Error(body.error?.message ?? `HTTP ${res.status}`), { code: body.error?.code, status: res.status });
3343
+ }
3344
+ return await res.json();
3345
+ }
3346
+ };
3347
+ function fromControlPage(_chatId, p) {
3348
+ const num = (v) => v === null || v === void 0 ? null : Number(v);
3349
+ return {
3350
+ items: p.data.map((entry) => ({ ...entry.event, seq: entry.seq })),
3351
+ firstEventId: num(p.firstEventId),
3352
+ lastEventId: num(p.lastEventId),
3353
+ hasBefore: p.hasBefore,
3354
+ hasAfter: p.hasAfter,
3355
+ ...p.anchorIndex !== void 0 ? { anchorIndex: p.anchorIndex } : {},
3356
+ headEventId: num(p.headEventId) ?? 0,
3357
+ ...p.liveFromEventId !== void 0 && p.liveFromEventId !== null ? { liveFromEventId: Number(p.liveFromEventId) } : {}
3358
+ };
3359
+ }
3360
+ function historyQs(q) {
3361
+ const p = new URLSearchParams();
3362
+ if (q.limit) p.set("limit", String(q.limit));
3363
+ if ("before" in q) p.set("before", String(q.before));
3364
+ else if ("after" in q) p.set("after", String(q.after));
3365
+ else if ("around" in q) p.set("around", "messageId" in q.around ? q.around.messageId : String(q.around.eventId));
3366
+ else p.set("anchor", "end");
3367
+ return p.toString();
3368
+ }
3369
+ function browserEnv() {
3370
+ const g = globalThis;
3371
+ if (!g.document || !g.addEventListener) return null;
3372
+ const doc = g.document;
3373
+ return {
3374
+ online: () => g.navigator?.onLine !== false,
3375
+ visible: () => doc.visibilityState !== "hidden",
3376
+ onWake: (cb) => {
3377
+ let hiddenAt = null;
3378
+ const onOnline = () => cb("online");
3379
+ const onFocus = () => cb("focus");
3380
+ const onVis = () => {
3381
+ if (doc.visibilityState === "hidden") hiddenAt = Date.now();
3382
+ else {
3383
+ cb("visible", hiddenAt === null ? 0 : Date.now() - hiddenAt);
3384
+ hiddenAt = null;
3385
+ }
3386
+ };
3387
+ g.addEventListener("online", onOnline);
3388
+ g.addEventListener("focus", onFocus);
3389
+ doc.addEventListener("visibilitychange", onVis);
3390
+ return () => {
3391
+ g.removeEventListener("online", onOnline);
3392
+ g.removeEventListener("focus", onFocus);
3393
+ doc.removeEventListener("visibilitychange", onVis);
3394
+ };
3395
+ }
3396
+ };
3397
+ }
3398
+ export {
3399
+ LiveClient,
3400
+ fromControlPage
3401
+ };
3402
+ //# sourceMappingURL=client-TQOOMRH6.js.map