@openclaw/gateway-client 2026.11.3 → 2026.11.5-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -0
- package/dist/.source-module-urls/64fb00de7b626c888cb871ea7e5171ebc35f3a7ee91800fc2345f930b9e361e7.json +1 -0
- package/dist/browser.d.mts +6 -5
- package/dist/browser.mjs +4 -3
- package/dist/index.d.mts +5 -5
- package/dist/index.mjs +224 -235
- package/dist/{protocol-client-Dg5tIB1S.d.mts → protocol-client-DmQZQQS7.d.mts} +2 -5
- package/dist/{protocol-request-CtVhe3Bj.d.mts → protocol-request-CRDNYiYG.d.mts} +2 -0
- package/dist/{readiness-CkF8_J-1.d.mts → readiness-BuLm1Ikf.d.mts} +12 -17
- package/dist/{readiness-CwRz4ZX8.mjs → readiness-C7IsnvXj.mjs} +11 -10
- package/dist/readiness.d.mts +1 -1
- package/dist/readiness.mjs +1 -2
- package/dist/scope-upgrade.d.mts +2 -3
- package/dist/{session-subscriptions-DJ5H6a_1.mjs → session-subscriptions-Bc7A64MY.mjs} +977 -264
- package/dist/{session-subscriptions-Bcq6_wtR.d.mts → session-subscriptions-UQlp58bR.d.mts} +15 -2
- package/dist/{timeouts-F2UKsnjG.mjs → timeouts-BBVOnLnf.mjs} +2 -5
- package/dist/timeouts.mjs +1 -2
- package/package.json +3 -2
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { _ as normalizeOptionalString, c as clearGatewayConnectTimeout, g as normalizeNullableString, m as startGatewayConnectTimeout, p as resolveSafeTimeoutDelayMs, t as DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS } from "./timeouts-
|
|
1
|
+
import { _ as normalizeOptionalString, c as clearGatewayConnectTimeout, d as resolveFiniteTimeoutDelayMs, g as normalizeNullableString, m as startGatewayConnectTimeout, p as resolveSafeTimeoutDelayMs, t as DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS } from "./timeouts-BBVOnLnf.mjs";
|
|
2
2
|
import { ConnectErrorDetailCodes, readConnectErrorDetailCode, readConnectErrorRecoveryAdvice, readPairingConnectErrorDetails } from "@openclaw/gateway-protocol/connect-error-details";
|
|
3
3
|
import { isGatewayEventFrame, isGatewayResponseFrame } from "@openclaw/gateway-protocol/frame-guards";
|
|
4
4
|
import { GATEWAY_SUSPEND_IDENTITY_RETRY_AFTER_MS, isGatewayRestartUnavailableError, isGatewaySuspendUnavailableError } from "@openclaw/gateway-protocol/restart-unavailable";
|
|
5
|
+
import { isRetryableGatewayStartupUnavailableError } from "@openclaw/gateway-protocol/startup-unavailable";
|
|
5
6
|
import { GATEWAY_ASSISTANT_ERROR_FALLBACK_TEXT } from "@openclaw/gateway-protocol/gateway-error-details";
|
|
6
7
|
//#region packages/gateway-client/src/device-auth.ts
|
|
7
8
|
function normalizeDeviceMetadataForAuth(value) {
|
|
@@ -52,6 +53,10 @@ function isRecord(value) {
|
|
|
52
53
|
function asRecord(value) {
|
|
53
54
|
return asOptionalObjectRecord(value) ?? {};
|
|
54
55
|
}
|
|
56
|
+
/** Returns a non-array record or undefined. */
|
|
57
|
+
function asOptionalRecord(value) {
|
|
58
|
+
return isRecord(value) ? value : void 0;
|
|
59
|
+
}
|
|
55
60
|
/** Returns a non-array record or null. */
|
|
56
61
|
function asNullableRecord(value) {
|
|
57
62
|
return isRecord(value) ? value : null;
|
|
@@ -276,6 +281,146 @@ function resolveModelCatalogConnect(params) {
|
|
|
276
281
|
};
|
|
277
282
|
}
|
|
278
283
|
//#endregion
|
|
284
|
+
//#region packages/normalization-core/src/cjk-chars.ts
|
|
285
|
+
const WEIGHTED_CJK_RANGES = [
|
|
286
|
+
[
|
|
287
|
+
[183, 183],
|
|
288
|
+
[12288, 12703],
|
|
289
|
+
[19968, 40869],
|
|
290
|
+
[44032, 55215],
|
|
291
|
+
[65281, 65376]
|
|
292
|
+
],
|
|
293
|
+
[
|
|
294
|
+
[4352, 4607],
|
|
295
|
+
[11904, 12287],
|
|
296
|
+
[12704, 19967],
|
|
297
|
+
[40870, 40959],
|
|
298
|
+
[40960, 42239],
|
|
299
|
+
[42752, 42759],
|
|
300
|
+
[43360, 43391],
|
|
301
|
+
[55216, 55295],
|
|
302
|
+
[63744, 64255]
|
|
303
|
+
],
|
|
304
|
+
[
|
|
305
|
+
[711, 711],
|
|
306
|
+
[713, 715],
|
|
307
|
+
[729, 729],
|
|
308
|
+
[746, 747],
|
|
309
|
+
[773, 773],
|
|
310
|
+
[803, 803],
|
|
311
|
+
[65040, 65103],
|
|
312
|
+
[65377, 65500],
|
|
313
|
+
[65504, 65510]
|
|
314
|
+
],
|
|
315
|
+
[[119648, 119665]],
|
|
316
|
+
[
|
|
317
|
+
[94176, 94207],
|
|
318
|
+
[110576, 110591],
|
|
319
|
+
[110592, 110959],
|
|
320
|
+
[127488, 127743],
|
|
321
|
+
[131072, 195103],
|
|
322
|
+
[196608, 210047]
|
|
323
|
+
]
|
|
324
|
+
];
|
|
325
|
+
new RegExp(`[${WEIGHTED_CJK_RANGES.flatMap((ranges) => ranges.map(([start, end]) => `\\u{${start.toString(16)}}-\\u{${end.toString(16)}}`)).join("")}]`, "u");
|
|
326
|
+
(() => {
|
|
327
|
+
const maxCodePoint = Math.max(...WEIGHTED_CJK_RANGES.flatMap((ranges) => ranges.map(([, end]) => end)));
|
|
328
|
+
const categories = new Uint8Array(maxCodePoint + 1);
|
|
329
|
+
for (const [bucket, ranges] of WEIGHTED_CJK_RANGES.entries()) for (const [start, end] of ranges) categories.fill(bucket + 1, start, end + 1);
|
|
330
|
+
return categories;
|
|
331
|
+
})();
|
|
332
|
+
//#endregion
|
|
333
|
+
//#region packages/normalization-core/src/error-coercion.ts
|
|
334
|
+
/** Preserves Error values and stringifies every other value into a new Error. */
|
|
335
|
+
function toStringifiedError(value) {
|
|
336
|
+
return value instanceof Error ? value : new Error(String(value));
|
|
337
|
+
}
|
|
338
|
+
//#endregion
|
|
339
|
+
//#region packages/normalization-core/src/stable-stringify.ts
|
|
340
|
+
const preserveString = (value) => value;
|
|
341
|
+
/** Writes the same deterministic text without retaining completed container strings. */
|
|
342
|
+
function writeStableStringify(value, write, normalizeString = preserveString) {
|
|
343
|
+
write(stringifyStableValue(value, /* @__PURE__ */ new WeakSet(), normalizeString, write));
|
|
344
|
+
}
|
|
345
|
+
function stringifyStableValue(value, stack, normalizeString, write) {
|
|
346
|
+
if (value === null || value === void 0) return String(value);
|
|
347
|
+
if (typeof value === "number" && !Number.isFinite(value)) return JSON.stringify(String(value));
|
|
348
|
+
if (typeof value === "bigint") return JSON.stringify(value.toString());
|
|
349
|
+
if (typeof value === "string") return JSON.stringify(normalizeString(value));
|
|
350
|
+
if (typeof value !== "object") return JSON.stringify(value) ?? "null";
|
|
351
|
+
if (stack.has(value)) return JSON.stringify("[Circular]");
|
|
352
|
+
stack.add(value);
|
|
353
|
+
try {
|
|
354
|
+
if (value instanceof Error) return stringifyStableValue({
|
|
355
|
+
name: value.name,
|
|
356
|
+
message: value.message,
|
|
357
|
+
stack: value.stack
|
|
358
|
+
}, stack, normalizeString, write);
|
|
359
|
+
if (value instanceof Uint8Array) return stringifyStableValue({
|
|
360
|
+
type: "Uint8Array",
|
|
361
|
+
data: encodeBase64(value)
|
|
362
|
+
}, stack, normalizeString, write);
|
|
363
|
+
if (Array.isArray(value)) {
|
|
364
|
+
if (write) {
|
|
365
|
+
write("[");
|
|
366
|
+
let separator = "";
|
|
367
|
+
for (const entry of value) {
|
|
368
|
+
write(separator);
|
|
369
|
+
write(stringifyStableValue(entry, stack, normalizeString, write));
|
|
370
|
+
separator = ",";
|
|
371
|
+
}
|
|
372
|
+
write("]");
|
|
373
|
+
return "";
|
|
374
|
+
}
|
|
375
|
+
const serializedEntries = [];
|
|
376
|
+
for (const entry of value) serializedEntries.push(stringifyStableValue(entry, stack, normalizeString));
|
|
377
|
+
return `[${serializedEntries.join(",")}]`;
|
|
378
|
+
}
|
|
379
|
+
const record = value;
|
|
380
|
+
const keys = Object.keys(record);
|
|
381
|
+
const fields = normalizeString === preserveString ? keys.sort() : keys.map((key) => ({
|
|
382
|
+
key,
|
|
383
|
+
normalizedKey: normalizeString(key)
|
|
384
|
+
})).sort((left, right) => {
|
|
385
|
+
return compareStableStrings(left.normalizedKey, right.normalizedKey) || compareStableStrings(left.key, right.key);
|
|
386
|
+
});
|
|
387
|
+
write?.("{");
|
|
388
|
+
const serializedFields = normalizeString === preserveString ? keys : [];
|
|
389
|
+
let separator = "";
|
|
390
|
+
let fieldIndex = 0;
|
|
391
|
+
for (const field of fields) {
|
|
392
|
+
const key = typeof field === "string" ? field : field.key;
|
|
393
|
+
const prefix = `${JSON.stringify(typeof field === "string" ? field : field.normalizedKey)}:`;
|
|
394
|
+
if (write) {
|
|
395
|
+
write(`${separator}${prefix}`);
|
|
396
|
+
write(stringifyStableValue(record[key], stack, normalizeString, write));
|
|
397
|
+
separator = ",";
|
|
398
|
+
} else serializedFields[fieldIndex++] = `${prefix}${stringifyStableValue(record[key], stack, normalizeString)}`;
|
|
399
|
+
}
|
|
400
|
+
if (write) {
|
|
401
|
+
write("}");
|
|
402
|
+
return "";
|
|
403
|
+
}
|
|
404
|
+
return `{${serializedFields.join(",")}}`;
|
|
405
|
+
} finally {
|
|
406
|
+
stack.delete(value);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
function encodeBase64(value) {
|
|
410
|
+
let binary = "";
|
|
411
|
+
for (const byte of value) binary += String.fromCharCode(byte);
|
|
412
|
+
return btoa(binary);
|
|
413
|
+
}
|
|
414
|
+
function compareStableStrings(left, right) {
|
|
415
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
416
|
+
}
|
|
417
|
+
//#endregion
|
|
418
|
+
//#region packages/normalization-core/src/string-normalization.ts
|
|
419
|
+
/** Retains runtime string entries from arrays without normalizing their contents. */
|
|
420
|
+
function filterStringEntries(value) {
|
|
421
|
+
return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
|
|
422
|
+
}
|
|
423
|
+
//#endregion
|
|
279
424
|
//#region packages/retry/src/index.ts
|
|
280
425
|
const MAX_TIMER_TIMEOUT_MS = 2147e6;
|
|
281
426
|
function createAbortError(message, options) {
|
|
@@ -407,24 +552,20 @@ function clampNumber(value, fallback, min, max) {
|
|
|
407
552
|
if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
|
|
408
553
|
return Math.min(Math.max(value, min ?? Number.NEGATIVE_INFINITY), max ?? Number.POSITIVE_INFINITY);
|
|
409
554
|
}
|
|
410
|
-
function resolveAttemptCount(value, fallback) {
|
|
411
|
-
return Math.max(1, Math.round(clampNumber(value, fallback)));
|
|
412
|
-
}
|
|
413
555
|
function resolveRetryDelayMs(value) {
|
|
414
556
|
return Math.min(Math.max(Math.round(value === Number.POSITIVE_INFINITY ? MAX_TIMER_TIMEOUT_MS : Number.isFinite(value) ? value : 0), 0), MAX_TIMER_TIMEOUT_MS);
|
|
415
557
|
}
|
|
416
|
-
function resolveJitterConfig(value, fallback) {
|
|
417
|
-
if (value === "full") return "full";
|
|
418
|
-
return typeof value === "number" && Number.isFinite(value) ? Math.min(Math.max(value, 0), 1) : fallback;
|
|
419
|
-
}
|
|
420
558
|
function resolveRetryConfig(defaults = DEFAULT_RETRY_CONFIG, overrides) {
|
|
421
|
-
const attempts =
|
|
559
|
+
const attempts = Math.max(1, Math.round(clampNumber(overrides?.attempts, defaults.attempts)));
|
|
422
560
|
const minDelayMs = resolveRetryDelayMs(clampNumber(overrides?.minDelayMs, defaults.minDelayMs, 0));
|
|
561
|
+
const maxDelayMs = Math.max(minDelayMs, resolveRetryDelayMs(clampNumber(overrides?.maxDelayMs, defaults.maxDelayMs, 0)));
|
|
562
|
+
const jitter = overrides?.jitter;
|
|
563
|
+
const fallbackJitter = defaults.jitter;
|
|
423
564
|
return {
|
|
424
565
|
attempts,
|
|
425
566
|
minDelayMs,
|
|
426
|
-
maxDelayMs
|
|
427
|
-
jitter:
|
|
567
|
+
maxDelayMs,
|
|
568
|
+
jitter: jitter === "full" ? jitter : typeof jitter === "number" && Number.isFinite(jitter) ? Math.min(Math.max(jitter, 0), 1) : fallbackJitter
|
|
428
569
|
};
|
|
429
570
|
}
|
|
430
571
|
function applyJitter(delayMs, jitter, mode, random) {
|
|
@@ -464,7 +605,7 @@ function createRetryRunner(runtime = {}) {
|
|
|
464
605
|
return await fn();
|
|
465
606
|
} catch (err) {
|
|
466
607
|
attemptErrors.push(err);
|
|
467
|
-
if (attempt >= maxAttempts || !shouldRetry(err, attempt)) break;
|
|
608
|
+
if (attempt >= maxAttempts || runtime.shouldRetry?.(err) === false || !shouldRetry(err, attempt)) break;
|
|
468
609
|
if (numeric) {
|
|
469
610
|
await runtimeSleep(resolveRetryDelayMs(initialDelayMs * 2 ** (attempt - 1)));
|
|
470
611
|
continue;
|
|
@@ -603,18 +744,29 @@ var GatewayPendingRequests = class {
|
|
|
603
744
|
for (const pending of this.pending.values()) if (pending.unbounded) return true;
|
|
604
745
|
return false;
|
|
605
746
|
}
|
|
606
|
-
|
|
747
|
+
releaseHeldRequests(isCurrent) {
|
|
748
|
+
for (const pending of this.pending.values()) {
|
|
749
|
+
if (!isCurrent()) return;
|
|
750
|
+
const send = pending.afterHello;
|
|
751
|
+
pending.afterHello = void 0;
|
|
752
|
+
send?.();
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
request(sender, method, params, options, deferUntilHello = false) {
|
|
607
756
|
let id;
|
|
608
757
|
try {
|
|
609
|
-
|
|
758
|
+
this.requestSequence += 1;
|
|
759
|
+
id = `${this.requestSequence}:${this.opts.createRequestId()}`;
|
|
610
760
|
} catch (error) {
|
|
611
|
-
return Promise.reject(
|
|
761
|
+
return Promise.reject(toStringifiedError(error));
|
|
612
762
|
}
|
|
613
763
|
const requestedTimeoutMs = options?.timeoutMs === null ? void 0 : options?.timeoutMs ?? this.opts.requestTimeoutMs;
|
|
614
764
|
const timeoutMs = typeof requestedTimeoutMs === "number" && Number.isFinite(requestedTimeoutMs) ? resolveSafeTimeoutDelayMs(requestedTimeoutMs, { minMs: 0 }) : void 0;
|
|
615
765
|
return new Promise((resolve, reject) => {
|
|
616
766
|
let timeout;
|
|
767
|
+
let startupRetry;
|
|
617
768
|
let requestSent = false;
|
|
769
|
+
let inFlight = false;
|
|
618
770
|
const pending = {
|
|
619
771
|
resolve: (value) => resolve(value),
|
|
620
772
|
reject,
|
|
@@ -623,9 +775,19 @@ var GatewayPendingRequests = class {
|
|
|
623
775
|
onAccepted: options?.onAccepted,
|
|
624
776
|
unbounded: timeoutMs === void 0,
|
|
625
777
|
method,
|
|
626
|
-
startedAtMs: this.opts.nowMs()
|
|
778
|
+
startedAtMs: this.opts.nowMs(),
|
|
779
|
+
prepareRetry: () => {
|
|
780
|
+
inFlight = false;
|
|
781
|
+
requestSent = false;
|
|
782
|
+
if (options?.signal?.aborted) {
|
|
783
|
+
onAbort();
|
|
784
|
+
return false;
|
|
785
|
+
}
|
|
786
|
+
return true;
|
|
787
|
+
}
|
|
627
788
|
};
|
|
628
789
|
const cleanup = () => {
|
|
790
|
+
clearTimeout(startupRetry);
|
|
629
791
|
if (timeout !== void 0) clearTimeout(timeout);
|
|
630
792
|
options?.signal?.removeEventListener("abort", onAbort);
|
|
631
793
|
if (this.bootstrapPause?.probe?.pending === pending) {
|
|
@@ -641,6 +803,7 @@ var GatewayPendingRequests = class {
|
|
|
641
803
|
return true;
|
|
642
804
|
};
|
|
643
805
|
const onAbort = () => {
|
|
806
|
+
if (options?.retainSentResultOnAbort && inFlight) return;
|
|
644
807
|
if (!retire("CLIENT_ABORTED")) return;
|
|
645
808
|
reject(this.opts.createRequestAbortError?.(method) ?? /* @__PURE__ */ new Error(`gateway request aborted for ${method}`));
|
|
646
809
|
};
|
|
@@ -670,7 +833,7 @@ var GatewayPendingRequests = class {
|
|
|
670
833
|
params
|
|
671
834
|
});
|
|
672
835
|
const send = () => {
|
|
673
|
-
if (this.pending.get(id) !== pending || options?.signal?.aborted ||
|
|
836
|
+
if (this.pending.get(id) !== pending || options?.signal?.aborted || timeoutMs !== void 0 && this.opts.nowMs() - pending.startedAtMs >= timeoutMs) return;
|
|
674
837
|
const pause = pending.resend ? this.bootstrapPause : void 0;
|
|
675
838
|
if (pause && !pause.announced && !pause.timer && !pause.probe) pause.probe = {
|
|
676
839
|
pending,
|
|
@@ -679,18 +842,26 @@ var GatewayPendingRequests = class {
|
|
|
679
842
|
pending.waitingForResume = Boolean(pause && (pause.announced || pause.probe?.pending !== pending));
|
|
680
843
|
if (pending.waitingForResume) return;
|
|
681
844
|
try {
|
|
845
|
+
inFlight = true;
|
|
682
846
|
sender.send(frame);
|
|
683
847
|
if (this.pending.get(id) !== pending) return;
|
|
684
|
-
requestSent =
|
|
848
|
+
requestSent = inFlight;
|
|
685
849
|
this.invoke("sent", () => options?.onSent?.(id));
|
|
686
850
|
} catch (error) {
|
|
687
|
-
if (retire("CLIENT_SEND_ERROR")) reject(
|
|
851
|
+
if (retire("CLIENT_SEND_ERROR")) reject(toStringifiedError(error));
|
|
688
852
|
}
|
|
689
853
|
};
|
|
854
|
+
pending.retryStartup = (retryAfterMs) => {
|
|
855
|
+
pending.resend = send;
|
|
856
|
+
clearTimeout(startupRetry);
|
|
857
|
+
startupRetry = setTimeout(send, resolveFiniteTimeoutDelayMs(retryAfterMs, GATEWAY_SUSPEND_IDENTITY_RETRY_AFTER_MS));
|
|
858
|
+
startupRetry.unref?.();
|
|
859
|
+
};
|
|
690
860
|
if (method === "agent.identity.get" || method === "sessions.subscribe" || method === "sessions.groups.list" || method === "question.list" || method === "sessions.list") pending.resend = send;
|
|
691
|
-
|
|
861
|
+
if (deferUntilHello) pending.afterHello = send;
|
|
862
|
+
else send();
|
|
692
863
|
} catch (error) {
|
|
693
|
-
if (retire("CLIENT_SEND_ERROR")) reject(
|
|
864
|
+
if (retire("CLIENT_SEND_ERROR")) reject(toStringifiedError(error));
|
|
694
865
|
}
|
|
695
866
|
});
|
|
696
867
|
}
|
|
@@ -705,7 +876,16 @@ var GatewayPendingRequests = class {
|
|
|
705
876
|
}
|
|
706
877
|
return;
|
|
707
878
|
}
|
|
879
|
+
const startupDetails = frame.error?.details;
|
|
880
|
+
if (!frame.ok && isRetryableGatewayStartupUnavailableError(frame.error) && startupDetails !== null && typeof startupDetails === "object" && "method" in startupDetails && startupDetails.method === pending.method && !pending.acceptedNotified) {
|
|
881
|
+
if (pending.prepareRetry()) {
|
|
882
|
+
pending.retryStartup?.(frame.error?.retryAfterMs);
|
|
883
|
+
if (this.bootstrapPause?.probe?.pending === pending && this.bootstrapPause.probe.revision === this.bootstrapPause.revision) this.resumeBootstrapRequests();
|
|
884
|
+
}
|
|
885
|
+
return;
|
|
886
|
+
}
|
|
708
887
|
if (!frame.ok && pending.resend && !pending.acceptedNotified && frame.error?.code === "UNAVAILABLE" && frame.error.retryable === true && (isGatewaySuspendUnavailableError(frame.error) || isGatewayRestartUnavailableError(frame.error))) {
|
|
888
|
+
if (!pending.prepareRetry()) return;
|
|
709
889
|
if (this.bootstrapPause?.probe?.pending === pending) this.bootstrapPause.probe = void 0;
|
|
710
890
|
this.pauseBootstrapRequests(isGatewayRestartUnavailableError(frame.error) ? Math.ceil(Math.max(GATEWAY_SUSPEND_IDENTITY_RETRY_AFTER_MS, frame.error.retryAfterMs ?? 0) * (1 + Math.random() * .2)) : frame.error.retryAfterMs);
|
|
711
891
|
pending.waitingForResume = true;
|
|
@@ -736,10 +916,6 @@ var GatewayPendingRequests = class {
|
|
|
736
916
|
pending.reject(error);
|
|
737
917
|
}
|
|
738
918
|
}
|
|
739
|
-
allocateRequestId() {
|
|
740
|
-
this.requestSequence += 1;
|
|
741
|
-
return `${this.requestSequence}:${this.opts.createRequestId()}`;
|
|
742
|
-
}
|
|
743
919
|
finishTiming(id, pending, ok, errorCode) {
|
|
744
920
|
const endedAtMs = this.opts.nowMs();
|
|
745
921
|
this.invoke("request timing", () => this.opts.onTiming?.({
|
|
@@ -762,6 +938,10 @@ var GatewayPendingRequests = class {
|
|
|
762
938
|
};
|
|
763
939
|
//#endregion
|
|
764
940
|
//#region packages/gateway-client/src/protocol-client.ts
|
|
941
|
+
const DEFAULT_CONNECT_FAILURE = Object.freeze({
|
|
942
|
+
closeCode: 1008,
|
|
943
|
+
closeReason: "connect failed"
|
|
944
|
+
});
|
|
765
945
|
/**
|
|
766
946
|
* Browser-safe gateway wire client. Environment adapters own transport and auth
|
|
767
947
|
* policy; this class owns the single socket/handshake/reconnect/frame state machine.
|
|
@@ -783,6 +963,7 @@ var GatewayProtocolClient = class {
|
|
|
783
963
|
this.reconnectSignal = null;
|
|
784
964
|
this.socketOpened = false;
|
|
785
965
|
this.helloReceived = false;
|
|
966
|
+
this.readyForRequests = false;
|
|
786
967
|
this.connectTiming = null;
|
|
787
968
|
this.reconnectSupervisor = new RetrySupervisor({
|
|
788
969
|
initialMs: opts.reconnect.initialMs,
|
|
@@ -842,9 +1023,9 @@ var GatewayProtocolClient = class {
|
|
|
842
1023
|
}
|
|
843
1024
|
request(method, params, options) {
|
|
844
1025
|
const socket = this.socket;
|
|
845
|
-
if (!socket
|
|
1026
|
+
if (!socket || this.socketOpened && !socket.isOpen()) return Promise.reject(/* @__PURE__ */ new Error("gateway not connected"));
|
|
846
1027
|
if (typeof method !== "string" || method.length === 0) return Promise.reject(/* @__PURE__ */ new Error("invalid request frame: method must be a non-empty string"));
|
|
847
|
-
return this.requests.request(socket, method, params, options);
|
|
1028
|
+
return this.requests.request(socket, method, params, options, !this.readyForRequests);
|
|
848
1029
|
}
|
|
849
1030
|
addEventListener(listener) {
|
|
850
1031
|
return this.listeners.add(listener);
|
|
@@ -886,17 +1067,80 @@ var GatewayProtocolClient = class {
|
|
|
886
1067
|
this.connectSent = this.connectRequestSent = false;
|
|
887
1068
|
this.socketOpened = false;
|
|
888
1069
|
this.helloReceived = false;
|
|
1070
|
+
this.readyForRequests = false;
|
|
889
1071
|
this.connectFailure = void 0;
|
|
890
1072
|
let socket;
|
|
891
1073
|
try {
|
|
892
1074
|
socket = this.opts.createSocket({
|
|
893
|
-
open: () =>
|
|
1075
|
+
open: () => {
|
|
1076
|
+
if (!this.isActive(socket, generation)) return;
|
|
1077
|
+
this.socketOpened = true;
|
|
1078
|
+
this.recordTiming("socket-open", generation);
|
|
1079
|
+
if (this.connectNonce) {
|
|
1080
|
+
this.sendConnect(socket, generation);
|
|
1081
|
+
return;
|
|
1082
|
+
}
|
|
1083
|
+
this.clearHandshakeTimer();
|
|
1084
|
+
const armedAt = Date.now();
|
|
1085
|
+
this.handshakeTimer = setTimeout(() => {
|
|
1086
|
+
this.handshakeTimer = null;
|
|
1087
|
+
if (!this.isActive(socket, generation) || this.connectSent || !socket.isOpen()) return;
|
|
1088
|
+
if (this.opts.handshake.mode === "fallback") {
|
|
1089
|
+
this.recordTiming("fallback", generation);
|
|
1090
|
+
this.sendConnect(socket, generation);
|
|
1091
|
+
return;
|
|
1092
|
+
}
|
|
1093
|
+
const elapsedMs = Date.now() - armedAt;
|
|
1094
|
+
const error = new Error(this.opts.handshake.timeoutMessage?.(elapsedMs) ?? `gateway connect challenge timeout after ${elapsedMs}ms`);
|
|
1095
|
+
this.opts.onConnectError?.(error);
|
|
1096
|
+
socket.close(1008, "connect challenge timeout");
|
|
1097
|
+
}, this.opts.handshake.timeoutMs);
|
|
1098
|
+
this.handshakeTimer.unref?.();
|
|
1099
|
+
},
|
|
894
1100
|
message: (data) => this.handleMessage(socket, generation, data),
|
|
895
|
-
close: (code, reason) =>
|
|
896
|
-
|
|
1101
|
+
close: (code, reason) => {
|
|
1102
|
+
if (this.socket !== socket) {
|
|
1103
|
+
if (this.stoppedSocket?.socket === socket) {
|
|
1104
|
+
const context = {
|
|
1105
|
+
...this.stoppedSocket.context,
|
|
1106
|
+
code,
|
|
1107
|
+
reason
|
|
1108
|
+
};
|
|
1109
|
+
this.stoppedSocket = void 0;
|
|
1110
|
+
this.invoke("close", () => this.opts.onClose?.(context, {
|
|
1111
|
+
retry: false,
|
|
1112
|
+
notify: true
|
|
1113
|
+
}));
|
|
1114
|
+
}
|
|
1115
|
+
return;
|
|
1116
|
+
}
|
|
1117
|
+
this.socket = null;
|
|
1118
|
+
this.connectionAbort?.abort();
|
|
1119
|
+
this.clearHandshakeTimer();
|
|
1120
|
+
const context = {
|
|
1121
|
+
...this.closeContext(),
|
|
1122
|
+
code,
|
|
1123
|
+
reason,
|
|
1124
|
+
generation
|
|
1125
|
+
};
|
|
1126
|
+
this.connectFailure = void 0;
|
|
1127
|
+
const decision = this.opts.resolveClose(context);
|
|
1128
|
+
this.requests.flush(decision.pendingError ?? context.connectFailure?.error ?? /* @__PURE__ */ new Error(`gateway closed (${code}): ${reason}`));
|
|
1129
|
+
this.invoke("close", () => this.opts.onClose?.(context, decision));
|
|
1130
|
+
if (decision.retry && !this.stopped && !this.socket && !this.reconnectSignal) {
|
|
1131
|
+
const error = context.connectFailure?.error;
|
|
1132
|
+
const retryAfterMs = error instanceof GatewayProtocolRequestError && error.retryable && error.retryAfterMs !== void 0 && Number.isFinite(error.retryAfterMs) && error.retryAfterMs > 0 ? error.retryAfterMs : void 0;
|
|
1133
|
+
this.scheduleReconnect(decision.reconnectDelayMs ?? context.connectFailure?.reconnectDelayMs, retryAfterMs);
|
|
1134
|
+
}
|
|
1135
|
+
},
|
|
1136
|
+
error: (error) => {
|
|
1137
|
+
if (!this.isActive(socket, generation) || this.connectSent) return;
|
|
1138
|
+
this.connectFailure = { error };
|
|
1139
|
+
this.opts.onConnectError?.(error);
|
|
1140
|
+
}
|
|
897
1141
|
});
|
|
898
1142
|
} catch (error) {
|
|
899
|
-
const normalized =
|
|
1143
|
+
const normalized = toStringifiedError(error);
|
|
900
1144
|
this.opts.onSocketFactoryError?.(normalized);
|
|
901
1145
|
this.opts.onConnectError?.(normalized);
|
|
902
1146
|
if (this.opts.rethrowSocketFactoryError?.(normalized)) {
|
|
@@ -919,34 +1163,6 @@ var GatewayProtocolClient = class {
|
|
|
919
1163
|
usedFallback: false
|
|
920
1164
|
};
|
|
921
1165
|
}
|
|
922
|
-
handleOpen(socket, generation) {
|
|
923
|
-
if (!this.isActive(socket, generation)) return;
|
|
924
|
-
this.socketOpened = true;
|
|
925
|
-
this.recordTiming("socket-open", generation);
|
|
926
|
-
if (this.connectNonce) {
|
|
927
|
-
this.sendConnect(socket, generation);
|
|
928
|
-
return;
|
|
929
|
-
}
|
|
930
|
-
this.armHandshakeTimer(socket, generation);
|
|
931
|
-
}
|
|
932
|
-
armHandshakeTimer(socket, generation) {
|
|
933
|
-
this.clearHandshakeTimer();
|
|
934
|
-
const armedAt = Date.now();
|
|
935
|
-
this.handshakeTimer = setTimeout(() => {
|
|
936
|
-
this.handshakeTimer = null;
|
|
937
|
-
if (!this.isActive(socket, generation) || this.connectSent || !socket.isOpen()) return;
|
|
938
|
-
if (this.opts.handshake.mode === "fallback") {
|
|
939
|
-
this.recordTiming("fallback", generation);
|
|
940
|
-
this.sendConnect(socket, generation);
|
|
941
|
-
return;
|
|
942
|
-
}
|
|
943
|
-
const elapsedMs = Date.now() - armedAt;
|
|
944
|
-
const error = new Error(this.opts.handshake.timeoutMessage?.(elapsedMs) ?? `gateway connect challenge timeout after ${elapsedMs}ms`);
|
|
945
|
-
this.opts.onConnectError?.(error);
|
|
946
|
-
socket.close(1008, "connect challenge timeout");
|
|
947
|
-
}, this.opts.handshake.timeoutMs);
|
|
948
|
-
this.handshakeTimer.unref?.();
|
|
949
|
-
}
|
|
950
1166
|
sendConnect(socket, generation) {
|
|
951
1167
|
if (!this.isActive(socket, generation) || !socket.isOpen() || this.connectSent) return;
|
|
952
1168
|
this.connectSent = true;
|
|
@@ -975,11 +1191,8 @@ var GatewayProtocolClient = class {
|
|
|
975
1191
|
}
|
|
976
1192
|
handleConnectPlanError(socket, generation, error) {
|
|
977
1193
|
if (!this.isConnectCurrent(socket, generation)) return;
|
|
978
|
-
const normalized =
|
|
979
|
-
const outcome = this.opts.onConnectPlanError?.(normalized) ??
|
|
980
|
-
closeCode: 1008,
|
|
981
|
-
closeReason: "connect failed"
|
|
982
|
-
};
|
|
1194
|
+
const normalized = toStringifiedError(error);
|
|
1195
|
+
const outcome = this.opts.onConnectPlanError?.(normalized) ?? DEFAULT_CONNECT_FAILURE;
|
|
983
1196
|
this.opts.onConnectError?.(outcome.error ?? normalized);
|
|
984
1197
|
if (outcome.stop) this.stopped = true;
|
|
985
1198
|
socket.close(outcome.closeCode, outcome.closeReason);
|
|
@@ -994,9 +1207,10 @@ var GatewayProtocolClient = class {
|
|
|
994
1207
|
plan
|
|
995
1208
|
};
|
|
996
1209
|
this.recordTiming("connect-plan-ready", generation, plan);
|
|
997
|
-
this.
|
|
998
|
-
|
|
999
|
-
|
|
1210
|
+
this.requests.request(socket, "connect", this.opts.buildConnectParams(plan), { onSent: () => {
|
|
1211
|
+
this.connectRequestSent = true;
|
|
1212
|
+
this.recordTiming("request-sent", generation, plan);
|
|
1213
|
+
} }).then((hello) => {
|
|
1000
1214
|
if (!this.isConnectCurrent(socket, generation)) return;
|
|
1001
1215
|
this.helloReceived = true;
|
|
1002
1216
|
this.requests.setSuspensionPhase(hello.snapshot?.suspension?.phase);
|
|
@@ -1007,6 +1221,9 @@ var GatewayProtocolClient = class {
|
|
|
1007
1221
|
const publishHello = () => {
|
|
1008
1222
|
if (!this.isConnectCurrent(socket, generation)) return;
|
|
1009
1223
|
this.invoke("hello", () => this.opts.onHello?.(hello));
|
|
1224
|
+
if (!this.isConnectCurrent(socket, generation)) return;
|
|
1225
|
+
this.requests.releaseHeldRequests(() => this.isConnectCurrent(socket, generation));
|
|
1226
|
+
if (this.isConnectCurrent(socket, generation)) this.readyForRequests = true;
|
|
1010
1227
|
};
|
|
1011
1228
|
const accepted = this.opts.onConnectHello?.(hello, context);
|
|
1012
1229
|
if (accepted instanceof Promise) return accepted.then(publishHello);
|
|
@@ -1015,10 +1232,7 @@ var GatewayProtocolClient = class {
|
|
|
1015
1232
|
if (!this.isActive(socket, generation)) return;
|
|
1016
1233
|
const requestError = error instanceof GatewayProtocolRequestError ? error : new GatewayProtocolRequestError({ message: String(error) });
|
|
1017
1234
|
this.connectFailure = { error: requestError };
|
|
1018
|
-
const outcome = this.opts.onConnectFailure?.(requestError, context) ??
|
|
1019
|
-
closeCode: 1008,
|
|
1020
|
-
closeReason: "connect failed"
|
|
1021
|
-
};
|
|
1235
|
+
const outcome = this.opts.onConnectFailure?.(requestError, context) ?? DEFAULT_CONNECT_FAILURE;
|
|
1022
1236
|
const applyFailure = (decision) => {
|
|
1023
1237
|
if (!this.isActive(socket, generation)) return;
|
|
1024
1238
|
this.connectFailure = {
|
|
@@ -1037,8 +1251,8 @@ var GatewayProtocolClient = class {
|
|
|
1037
1251
|
return applyFailure(outcome);
|
|
1038
1252
|
}).catch((error) => {
|
|
1039
1253
|
if (!this.isConnectCurrent(socket, generation)) return;
|
|
1040
|
-
this.opts.onConnectError?.(
|
|
1041
|
-
this.closeSocket(
|
|
1254
|
+
this.opts.onConnectError?.(toStringifiedError(error));
|
|
1255
|
+
this.closeSocket(DEFAULT_CONNECT_FAILURE.closeCode, DEFAULT_CONNECT_FAILURE.closeReason);
|
|
1042
1256
|
});
|
|
1043
1257
|
}
|
|
1044
1258
|
handleMessage(socket, generation, raw) {
|
|
@@ -1064,7 +1278,7 @@ var GatewayProtocolClient = class {
|
|
|
1064
1278
|
return;
|
|
1065
1279
|
}
|
|
1066
1280
|
this.connectNonce = nonce;
|
|
1067
|
-
this.serverCapabilities =
|
|
1281
|
+
this.serverCapabilities = filterStringEntries(payload?.capabilities);
|
|
1068
1282
|
const challengeTs = payload?.ts;
|
|
1069
1283
|
this.connectChallengeTs = typeof challengeTs === "number" && Number.isSafeInteger(challengeTs) && challengeTs >= 0 ? challengeTs : null;
|
|
1070
1284
|
this.recordTiming("challenge", generation);
|
|
@@ -1096,7 +1310,7 @@ var GatewayProtocolClient = class {
|
|
|
1096
1310
|
}
|
|
1097
1311
|
dispatchEvent(socket, generation, event) {
|
|
1098
1312
|
const listeners = this.listeners.snapshot();
|
|
1099
|
-
if (event.event === "gateway.suspension"
|
|
1313
|
+
if (event.event === "gateway.suspension") this.requests.setSuspensionPhase(asRecord(event.payload).phase);
|
|
1100
1314
|
else if (event.event === "shutdown" && typeof asRecord(event.payload).restartExpectedMs === "number") this.requests.setSuspensionPhase("draining");
|
|
1101
1315
|
this.invoke("event", () => this.opts.onEvent?.(event));
|
|
1102
1316
|
for (const [listener, subscription] of listeners) {
|
|
@@ -1104,46 +1318,6 @@ var GatewayProtocolClient = class {
|
|
|
1104
1318
|
if (this.listeners.isCurrent(listener, subscription)) this.invoke("event listener", () => listener(event));
|
|
1105
1319
|
}
|
|
1106
1320
|
}
|
|
1107
|
-
handleClose(socket, generation, code, reason) {
|
|
1108
|
-
if (this.socket !== socket) {
|
|
1109
|
-
if (this.stoppedSocket?.socket === socket) {
|
|
1110
|
-
const context = {
|
|
1111
|
-
...this.stoppedSocket.context,
|
|
1112
|
-
code,
|
|
1113
|
-
reason
|
|
1114
|
-
};
|
|
1115
|
-
this.stoppedSocket = void 0;
|
|
1116
|
-
this.invoke("close", () => this.opts.onClose?.(context, {
|
|
1117
|
-
retry: false,
|
|
1118
|
-
notify: true
|
|
1119
|
-
}));
|
|
1120
|
-
}
|
|
1121
|
-
return;
|
|
1122
|
-
}
|
|
1123
|
-
this.socket = null;
|
|
1124
|
-
this.connectionAbort?.abort();
|
|
1125
|
-
this.clearHandshakeTimer();
|
|
1126
|
-
const context = {
|
|
1127
|
-
...this.closeContext(),
|
|
1128
|
-
code,
|
|
1129
|
-
reason,
|
|
1130
|
-
generation
|
|
1131
|
-
};
|
|
1132
|
-
this.connectFailure = void 0;
|
|
1133
|
-
const decision = this.opts.resolveClose(context);
|
|
1134
|
-
this.requests.flush(decision.pendingError ?? context.connectFailure?.error ?? /* @__PURE__ */ new Error(`gateway closed (${code}): ${reason}`));
|
|
1135
|
-
this.invoke("close", () => this.opts.onClose?.(context, decision));
|
|
1136
|
-
if (decision.retry && !this.stopped && !this.socket && !this.reconnectSignal) {
|
|
1137
|
-
const error = context.connectFailure?.error;
|
|
1138
|
-
const retryAfterMs = error instanceof GatewayProtocolRequestError && error.retryable && error.retryAfterMs !== void 0 && Number.isFinite(error.retryAfterMs) && error.retryAfterMs > 0 ? error.retryAfterMs : void 0;
|
|
1139
|
-
this.scheduleReconnect(decision.reconnectDelayMs ?? context.connectFailure?.reconnectDelayMs, retryAfterMs);
|
|
1140
|
-
}
|
|
1141
|
-
}
|
|
1142
|
-
handleSocketError(socket, generation, error) {
|
|
1143
|
-
if (!this.isActive(socket, generation) || this.connectSent) return;
|
|
1144
|
-
this.connectFailure = { error };
|
|
1145
|
-
this.opts.onConnectError?.(error);
|
|
1146
|
-
}
|
|
1147
1321
|
scheduleReconnect(overrideMs, minimumMs = 0) {
|
|
1148
1322
|
if (overrideMs !== void 0) this.reconnectSupervisor.nextDelayOverrideMs = overrideMs;
|
|
1149
1323
|
const retry = this.reconnectSupervisor.next();
|
|
@@ -1236,87 +1410,613 @@ function shouldPauseGatewayReconnect(params) {
|
|
|
1236
1410
|
return NON_RECOVERABLE_AUTH_ERRORS.has(code) || params.protocolMismatchIsTerminal === true && code === ConnectErrorDetailCodes.PROTOCOL_MISMATCH || params.clientVersionMismatchIsTerminal === true && code === ConnectErrorDetailCodes.CLIENT_VERSION_MISMATCH;
|
|
1237
1411
|
}
|
|
1238
1412
|
//#endregion
|
|
1239
|
-
//#region
|
|
1240
|
-
const
|
|
1241
|
-
|
|
1242
|
-
function
|
|
1243
|
-
|
|
1413
|
+
//#region node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_u64.js
|
|
1414
|
+
const fromNumH = (n) => n / 2 ** 32 | 0;
|
|
1415
|
+
const fromNumL = (n) => n >>> 0;
|
|
1416
|
+
function setU64FromNum(view, byteOffset, n, isLE) {
|
|
1417
|
+
const h = fromNumH(n);
|
|
1418
|
+
const l = fromNumL(n);
|
|
1419
|
+
view.setUint32(byteOffset, isLE ? l : h, isLE);
|
|
1420
|
+
view.setUint32(byteOffset + 4, isLE ? h : l, isLE);
|
|
1244
1421
|
}
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1422
|
+
//#endregion
|
|
1423
|
+
//#region node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/utils.js
|
|
1424
|
+
/**
|
|
1425
|
+
* Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
|
|
1426
|
+
* @param a - value to test
|
|
1427
|
+
* @returns `true` when the value is a Uint8Array-compatible view.
|
|
1428
|
+
* @example
|
|
1429
|
+
* Check whether a value is a Uint8Array-compatible view.
|
|
1430
|
+
* ```ts
|
|
1431
|
+
* isBytes(new Uint8Array([1, 2, 3]));
|
|
1432
|
+
* ```
|
|
1433
|
+
*/
|
|
1434
|
+
function isBytes(a) {
|
|
1435
|
+
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
|
|
1258
1436
|
}
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1437
|
+
const atitle = (title) => title ? `"${title}" ` : "";
|
|
1438
|
+
/**
|
|
1439
|
+
* Asserts something is a non-negative integer.
|
|
1440
|
+
* @param n - number to validate
|
|
1441
|
+
* @param title - label included in thrown errors
|
|
1442
|
+
* @returns The validated number.
|
|
1443
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
1444
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
1445
|
+
* @example
|
|
1446
|
+
* Validate a non-negative integer option.
|
|
1447
|
+
* ```ts
|
|
1448
|
+
* anumber(32, 'length');
|
|
1449
|
+
* ```
|
|
1450
|
+
*/
|
|
1451
|
+
function anumber(n, title = "") {
|
|
1452
|
+
if (typeof n !== "number") throw new TypeError(atitle(title) + "expected number, got " + typeof n);
|
|
1453
|
+
if (!Number.isSafeInteger(n) || n < 0) throw new RangeError(atitle(title) + "expected integer >= 0, got " + n);
|
|
1454
|
+
return n;
|
|
1455
|
+
}
|
|
1456
|
+
/**
|
|
1457
|
+
* Asserts something is Uint8Array.
|
|
1458
|
+
* @param value - value to validate
|
|
1459
|
+
* @param length - optional exact length constraint
|
|
1460
|
+
* @param title - label included in thrown errors
|
|
1461
|
+
* @returns The validated byte array.
|
|
1462
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
1463
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
1464
|
+
* @example
|
|
1465
|
+
* Validate that a value is a byte array.
|
|
1466
|
+
* ```ts
|
|
1467
|
+
* abytes(new Uint8Array([1, 2, 3]));
|
|
1468
|
+
* ```
|
|
1469
|
+
*/
|
|
1470
|
+
function abytes(value, length, title = "") {
|
|
1471
|
+
if (isBytes(value) && (length === void 0 || value.length === length)) return value;
|
|
1472
|
+
if (length !== void 0) anumber(length, "length");
|
|
1473
|
+
const bytes = isBytes(value);
|
|
1474
|
+
const ofLen = length !== void 0 ? ` of length ${length}` : "";
|
|
1475
|
+
const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
|
|
1476
|
+
const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
|
|
1477
|
+
if (!bytes) throw new TypeError(message);
|
|
1478
|
+
throw new RangeError(message);
|
|
1479
|
+
}
|
|
1480
|
+
const aobject = (value, label) => {
|
|
1481
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value);
|
|
1482
|
+
};
|
|
1483
|
+
const aopts = (value, label) => {
|
|
1484
|
+
aobject(value, label);
|
|
1485
|
+
const proto = Object.getPrototypeOf(value);
|
|
1486
|
+
if (proto !== Object.prototype && proto !== null) throw new TypeError(`"${label}" expected plain object`);
|
|
1487
|
+
if (Object.hasOwn(value, "__proto__")) throw new TypeError(`"${label}.__proto__" is not allowed`);
|
|
1488
|
+
};
|
|
1489
|
+
/**
|
|
1490
|
+
* Asserts a hash instance has not been destroyed or finished.
|
|
1491
|
+
* @param instance - hash instance to validate
|
|
1492
|
+
* @param checkFinished - whether to reject finalized instances
|
|
1493
|
+
* @throws If the hash instance has already been destroyed or finalized. {@link Error}
|
|
1494
|
+
* @example
|
|
1495
|
+
* Validate that a hash instance is still usable.
|
|
1496
|
+
* ```ts
|
|
1497
|
+
* import { aexists } from '@noble/hashes/utils.js';
|
|
1498
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
1499
|
+
* const hash = sha256.create();
|
|
1500
|
+
* aexists(hash);
|
|
1501
|
+
* ```
|
|
1502
|
+
*/
|
|
1503
|
+
function aexists(instance, checkFinished = true) {
|
|
1504
|
+
if (instance.destroyed) throw new Error("hash was destroyed");
|
|
1505
|
+
if (checkFinished && instance.finished) throw new Error("digest() was already called");
|
|
1506
|
+
}
|
|
1507
|
+
/**
|
|
1508
|
+
* Asserts output is a sufficiently-sized byte array.
|
|
1509
|
+
* @param out - destination buffer
|
|
1510
|
+
* @param instance - hash instance providing output length
|
|
1511
|
+
* Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
|
|
1512
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
1513
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
1514
|
+
* @example
|
|
1515
|
+
* Validate a caller-provided digest buffer.
|
|
1516
|
+
* ```ts
|
|
1517
|
+
* import { aoutput } from '@noble/hashes/utils.js';
|
|
1518
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
1519
|
+
* const hash = sha256.create();
|
|
1520
|
+
* aoutput(new Uint8Array(hash.outputLen), hash);
|
|
1521
|
+
* ```
|
|
1522
|
+
*/
|
|
1523
|
+
function aoutput(out, instance) {
|
|
1524
|
+
abytes(out, void 0, "output");
|
|
1525
|
+
const min = instance.outputLen;
|
|
1526
|
+
if (!(out.length >= min)) throw new RangeError("\"output\" expected length >= " + min);
|
|
1527
|
+
}
|
|
1528
|
+
/**
|
|
1529
|
+
* Zeroizes typed arrays in place. Warning: JS provides no guarantees.
|
|
1530
|
+
* @param arrays - arrays to overwrite with zeros
|
|
1531
|
+
* @example
|
|
1532
|
+
* Zeroize sensitive buffers in place.
|
|
1533
|
+
* ```ts
|
|
1534
|
+
* clean(new Uint8Array([1, 2, 3]));
|
|
1535
|
+
* ```
|
|
1536
|
+
*/
|
|
1537
|
+
function clean(...arrays) {
|
|
1538
|
+
for (let i = 0; i < arrays.length; i++) arrays[i].fill(0);
|
|
1539
|
+
}
|
|
1540
|
+
/**
|
|
1541
|
+
* Creates a DataView for byte-level manipulation.
|
|
1542
|
+
* @param arr - source typed array
|
|
1543
|
+
* @returns DataView over the same buffer region.
|
|
1544
|
+
* @example
|
|
1545
|
+
* Create a DataView over an existing buffer.
|
|
1546
|
+
* ```ts
|
|
1547
|
+
* createView(new Uint8Array(4));
|
|
1548
|
+
* ```
|
|
1549
|
+
*/
|
|
1550
|
+
function createView(arr) {
|
|
1551
|
+
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
1552
|
+
}
|
|
1553
|
+
/**
|
|
1554
|
+
* Rotate-right operation for uint32 values.
|
|
1555
|
+
* @param word - source word
|
|
1556
|
+
* @param shift - shift amount in bits
|
|
1557
|
+
* @returns Rotated word.
|
|
1558
|
+
* @example
|
|
1559
|
+
* Rotate a 32-bit word to the right.
|
|
1560
|
+
* ```ts
|
|
1561
|
+
* rotr(0x12345678, 8);
|
|
1562
|
+
* ```
|
|
1563
|
+
*/
|
|
1564
|
+
function rotr(word, shift) {
|
|
1565
|
+
return word << 32 - shift | word >>> shift;
|
|
1566
|
+
}
|
|
1567
|
+
const hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")();
|
|
1568
|
+
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
|
|
1569
|
+
/**
|
|
1570
|
+
* Convert byte array to hex string.
|
|
1571
|
+
* Uses the built-in function when available and assumes it matches the tested
|
|
1572
|
+
* fallback semantics.
|
|
1573
|
+
* @param bytes - bytes to encode
|
|
1574
|
+
* @returns Lowercase hexadecimal string.
|
|
1575
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
1576
|
+
* @example
|
|
1577
|
+
* Convert bytes to lowercase hexadecimal.
|
|
1578
|
+
* ```ts
|
|
1579
|
+
* bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
|
|
1580
|
+
* ```
|
|
1581
|
+
*/
|
|
1582
|
+
function bytesToHex(bytes) {
|
|
1583
|
+
abytes(bytes);
|
|
1584
|
+
if (hasHexBuiltin) return bytes.toHex();
|
|
1585
|
+
let hex = "";
|
|
1586
|
+
for (let i = 0; i < bytes.length; i++) hex += hexes[bytes[i]];
|
|
1587
|
+
return hex;
|
|
1588
|
+
}
|
|
1589
|
+
/**
|
|
1590
|
+
* Merges default options and passed options.
|
|
1591
|
+
* @param defaults - base option object
|
|
1592
|
+
* @param opts - user overrides
|
|
1593
|
+
* @param title - label included in thrown override errors
|
|
1594
|
+
* @returns Fresh merged option object with a null prototype.
|
|
1595
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
1596
|
+
* @example
|
|
1597
|
+
* Merge user overrides onto default options.
|
|
1598
|
+
* ```ts
|
|
1599
|
+
* checkOpts({ dkLen: 32 }, { asyncTick: 10 });
|
|
1600
|
+
* ```
|
|
1601
|
+
*/
|
|
1602
|
+
function checkOpts(defaults, opts, title = "opts") {
|
|
1603
|
+
aopts(defaults, "defaults");
|
|
1604
|
+
if (opts !== void 0) aopts(opts, title);
|
|
1605
|
+
return Object.assign(Object.create(null), defaults, opts);
|
|
1606
|
+
}
|
|
1607
|
+
/**
|
|
1608
|
+
* Creates a callable hash function from a stateful class constructor.
|
|
1609
|
+
* @param hashCons - hash constructor or factory
|
|
1610
|
+
* @param info - optional metadata such as DER OID
|
|
1611
|
+
* @returns Frozen callable hash wrapper with `.create()`.
|
|
1612
|
+
* Wrapper construction eagerly calls `hashCons(undefined)` once to read
|
|
1613
|
+
* `outputLen` / `blockLen`, so constructor side effects happen at module
|
|
1614
|
+
* init time.
|
|
1615
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
1616
|
+
* @example
|
|
1617
|
+
* Wrap a stateful hash constructor into a callable helper.
|
|
1618
|
+
* ```ts
|
|
1619
|
+
* import { createHasher } from '@noble/hashes/utils.js';
|
|
1620
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
1621
|
+
* const wrapped = createHasher(sha256.create, { oid: sha256.oid });
|
|
1622
|
+
* wrapped(new Uint8Array([1]));
|
|
1623
|
+
* ```
|
|
1624
|
+
*/
|
|
1625
|
+
function createHasher(hashCons, info = {}) {
|
|
1626
|
+
if (typeof hashCons !== "function") throw new TypeError("\"hashCons\" expected function, got type=" + typeof hashCons);
|
|
1627
|
+
info = checkOpts({}, info, "info");
|
|
1628
|
+
const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
|
|
1629
|
+
const tmp = hashCons(void 0);
|
|
1630
|
+
hashC.outputLen = tmp.outputLen;
|
|
1631
|
+
hashC.blockLen = tmp.blockLen;
|
|
1632
|
+
hashC.canXOF = tmp.canXOF;
|
|
1633
|
+
hashC.create = (opts) => hashCons(opts);
|
|
1634
|
+
Object.assign(hashC, info);
|
|
1635
|
+
return Object.freeze(hashC);
|
|
1636
|
+
}
|
|
1637
|
+
/**
|
|
1638
|
+
* Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
|
|
1639
|
+
* @param suffix - final OID byte for the selected hash.
|
|
1640
|
+
* The helper accepts any byte even though only the documented NIST hash
|
|
1641
|
+
* suffixes are meaningful downstream.
|
|
1642
|
+
* @returns Object containing the DER-encoded OID.
|
|
1643
|
+
* @example
|
|
1644
|
+
* Build OID metadata for a NIST hash.
|
|
1645
|
+
* ```ts
|
|
1646
|
+
* oidNist(0x01);
|
|
1647
|
+
* ```
|
|
1648
|
+
*/
|
|
1649
|
+
const oidNist = (suffix) => ({ oid: Uint8Array.from([
|
|
1650
|
+
6,
|
|
1651
|
+
9,
|
|
1652
|
+
96,
|
|
1653
|
+
134,
|
|
1654
|
+
72,
|
|
1655
|
+
1,
|
|
1656
|
+
101,
|
|
1657
|
+
3,
|
|
1658
|
+
4,
|
|
1659
|
+
2,
|
|
1660
|
+
suffix
|
|
1661
|
+
]) });
|
|
1662
|
+
//#endregion
|
|
1663
|
+
//#region node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_md.js
|
|
1664
|
+
/**
|
|
1665
|
+
* Internal Merkle-Damgard hash utils.
|
|
1666
|
+
* @module
|
|
1667
|
+
*/
|
|
1668
|
+
/**
|
|
1669
|
+
* Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.
|
|
1670
|
+
* Returns bits from `b` when `a` is set, otherwise from `c`.
|
|
1671
|
+
* The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never
|
|
1672
|
+
* set the same bit.
|
|
1673
|
+
* @param a - selector word
|
|
1674
|
+
* @param b - word chosen when selector bit is set
|
|
1675
|
+
* @param c - word chosen when selector bit is clear
|
|
1676
|
+
* @returns Mixed 32-bit word.
|
|
1677
|
+
* @example
|
|
1678
|
+
* Combine three words with the shared 32-bit choice primitive.
|
|
1679
|
+
* ```ts
|
|
1680
|
+
* Chi(0xffffffff, 0x12345678, 0x87654321);
|
|
1681
|
+
* ```
|
|
1682
|
+
*/
|
|
1683
|
+
function Chi(a, b, c) {
|
|
1684
|
+
return a & b ^ ~a & c;
|
|
1685
|
+
}
|
|
1686
|
+
/**
|
|
1687
|
+
* Shared 32-bit majority primitive reused by SHA-256 and SHA-1.
|
|
1688
|
+
* Returns bits shared by at least two inputs.
|
|
1689
|
+
* @param a - first input word
|
|
1690
|
+
* @param b - second input word
|
|
1691
|
+
* @param c - third input word
|
|
1692
|
+
* @returns Mixed 32-bit word.
|
|
1693
|
+
* @example
|
|
1694
|
+
* Combine three words with the shared 32-bit majority primitive.
|
|
1695
|
+
* ```ts
|
|
1696
|
+
* Maj(0xffffffff, 0x12345678, 0x87654321);
|
|
1697
|
+
* ```
|
|
1698
|
+
*/
|
|
1699
|
+
function Maj(a, b, c) {
|
|
1700
|
+
return a & b ^ a & c ^ b & c;
|
|
1701
|
+
}
|
|
1702
|
+
/**
|
|
1703
|
+
* Merkle-Damgard hash construction base class.
|
|
1704
|
+
* Could be used to create MD5, RIPEMD, SHA1, SHA2.
|
|
1705
|
+
* Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
|
|
1706
|
+
* strings with partial-byte tails.
|
|
1707
|
+
* @param blockLen - internal block size in bytes
|
|
1708
|
+
* @param outputLen - digest size in bytes
|
|
1709
|
+
* @param padOffset - trailing length field size in bytes
|
|
1710
|
+
* @param isLE - whether length and state words are encoded in little-endian
|
|
1711
|
+
* @example
|
|
1712
|
+
* Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
|
|
1713
|
+
* ```ts
|
|
1714
|
+
* import { _SHA1 } from '@noble/hashes/legacy.js';
|
|
1715
|
+
* const hash = new _SHA1();
|
|
1716
|
+
* hash.update(new Uint8Array([97, 98, 99]));
|
|
1717
|
+
* hash.digest();
|
|
1718
|
+
* ```
|
|
1719
|
+
*/
|
|
1720
|
+
var HashMD = class {
|
|
1721
|
+
blockLen;
|
|
1722
|
+
outputLen;
|
|
1723
|
+
canXOF = false;
|
|
1724
|
+
padOffset;
|
|
1725
|
+
isLE;
|
|
1726
|
+
buffer;
|
|
1727
|
+
view;
|
|
1728
|
+
finished = false;
|
|
1729
|
+
length = 0;
|
|
1730
|
+
pos = 0;
|
|
1731
|
+
destroyed = false;
|
|
1732
|
+
constructor(blockLen, outputLen, padOffset, isLE) {
|
|
1733
|
+
this.blockLen = blockLen;
|
|
1734
|
+
this.outputLen = outputLen;
|
|
1735
|
+
this.padOffset = padOffset;
|
|
1736
|
+
this.isLE = isLE;
|
|
1737
|
+
this.buffer = new Uint8Array(blockLen);
|
|
1738
|
+
this.view = createView(this.buffer);
|
|
1739
|
+
}
|
|
1740
|
+
update(data) {
|
|
1741
|
+
aexists(this);
|
|
1742
|
+
abytes(data);
|
|
1743
|
+
const { view, buffer, blockLen } = this;
|
|
1744
|
+
const len = data.length;
|
|
1745
|
+
let processed = false;
|
|
1746
|
+
for (let pos = 0; pos < len;) {
|
|
1747
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
|
1748
|
+
if (take === blockLen) {
|
|
1749
|
+
const dataView = createView(data);
|
|
1750
|
+
for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
|
|
1751
|
+
processed = true;
|
|
1752
|
+
continue;
|
|
1753
|
+
}
|
|
1754
|
+
buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
|
|
1755
|
+
this.pos += take;
|
|
1756
|
+
pos += take;
|
|
1757
|
+
if (this.pos === blockLen) {
|
|
1758
|
+
this.process(view, 0);
|
|
1759
|
+
this.pos = 0;
|
|
1760
|
+
processed = true;
|
|
1277
1761
|
}
|
|
1278
|
-
write("]");
|
|
1279
|
-
return "";
|
|
1280
1762
|
}
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
return
|
|
1284
|
-
}
|
|
1285
|
-
const record = value;
|
|
1286
|
-
const keys = Object.keys(record);
|
|
1287
|
-
const fields = normalizeString === preserveString ? keys.sort() : keys.map((key) => ({
|
|
1288
|
-
key,
|
|
1289
|
-
normalizedKey: normalizeString(key)
|
|
1290
|
-
})).sort((left, right) => {
|
|
1291
|
-
return compareStableStrings(left.normalizedKey, right.normalizedKey) || compareStableStrings(left.key, right.key);
|
|
1292
|
-
});
|
|
1293
|
-
write?.("{");
|
|
1294
|
-
const serializedFields = normalizeString === preserveString ? keys : [];
|
|
1295
|
-
let separator = "";
|
|
1296
|
-
let fieldIndex = 0;
|
|
1297
|
-
for (const field of fields) {
|
|
1298
|
-
const key = typeof field === "string" ? field : field.key;
|
|
1299
|
-
const prefix = `${JSON.stringify(typeof field === "string" ? field : field.normalizedKey)}:`;
|
|
1300
|
-
if (write) {
|
|
1301
|
-
write(`${separator}${prefix}`);
|
|
1302
|
-
write(stringifyStableValue(record[key], stack, normalizeString, write));
|
|
1303
|
-
separator = ",";
|
|
1304
|
-
} else serializedFields[fieldIndex++] = `${prefix}${stringifyStableValue(record[key], stack, normalizeString)}`;
|
|
1763
|
+
this.length += data.length;
|
|
1764
|
+
if (processed) this.roundClean();
|
|
1765
|
+
return this;
|
|
1305
1766
|
}
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1767
|
+
digestInto(out) {
|
|
1768
|
+
aexists(this);
|
|
1769
|
+
aoutput(out, this);
|
|
1770
|
+
this.finished = true;
|
|
1771
|
+
const { buffer, view, blockLen, isLE } = this;
|
|
1772
|
+
let { pos } = this;
|
|
1773
|
+
buffer[pos++] = 128;
|
|
1774
|
+
buffer.fill(0, pos);
|
|
1775
|
+
if (this.padOffset > blockLen - pos) {
|
|
1776
|
+
this.process(view, 0);
|
|
1777
|
+
buffer.fill(0);
|
|
1778
|
+
}
|
|
1779
|
+
setU64FromNum(view, blockLen - 8, this.length * 8, isLE);
|
|
1780
|
+
this.process(view, 0);
|
|
1781
|
+
this.roundClean();
|
|
1782
|
+
const oview = out === buffer ? view : createView(out);
|
|
1783
|
+
const len = this.outputLen;
|
|
1784
|
+
const outLen = len / 4;
|
|
1785
|
+
const state = this.get();
|
|
1786
|
+
if (len % 4 || outLen > state.length) throw new Error("invalid outputLen");
|
|
1787
|
+
for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);
|
|
1788
|
+
}
|
|
1789
|
+
digest() {
|
|
1790
|
+
const { buffer, outputLen } = this;
|
|
1791
|
+
this.digestInto(buffer);
|
|
1792
|
+
const res = buffer.slice(0, outputLen);
|
|
1793
|
+
this.destroy();
|
|
1794
|
+
return res;
|
|
1795
|
+
}
|
|
1796
|
+
_cloneIntoMeta(to) {
|
|
1797
|
+
const { buffer, length, finished, destroyed, pos } = this;
|
|
1798
|
+
to.destroyed = destroyed;
|
|
1799
|
+
to.finished = finished;
|
|
1800
|
+
to.length = length;
|
|
1801
|
+
to.pos = pos;
|
|
1802
|
+
if (pos) to.buffer.set(buffer);
|
|
1803
|
+
return to;
|
|
1804
|
+
}
|
|
1805
|
+
clone() {
|
|
1806
|
+
return this._cloneInto();
|
|
1309
1807
|
}
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1808
|
+
};
|
|
1809
|
+
/**
|
|
1810
|
+
* Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
|
|
1811
|
+
* Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
|
|
1812
|
+
*/
|
|
1813
|
+
/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the
|
|
1814
|
+
* square roots of the first eight prime numbers. Exported as a shared table; callers must treat
|
|
1815
|
+
* it as read-only because constructors copy words from it by index. */
|
|
1816
|
+
const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
|
1817
|
+
1779033703,
|
|
1818
|
+
3144134277,
|
|
1819
|
+
1013904242,
|
|
1820
|
+
2773480762,
|
|
1821
|
+
1359893119,
|
|
1822
|
+
2600822924,
|
|
1823
|
+
528734635,
|
|
1824
|
+
1541459225
|
|
1825
|
+
]);
|
|
1826
|
+
//#endregion
|
|
1827
|
+
//#region node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/sha2.js
|
|
1828
|
+
/**
|
|
1829
|
+
* SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
|
|
1830
|
+
* SHA256 is the fastest hash implementable in JS, even faster than Blake3.
|
|
1831
|
+
* Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and
|
|
1832
|
+
* {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.
|
|
1833
|
+
* @module
|
|
1834
|
+
*/
|
|
1835
|
+
/**
|
|
1836
|
+
* SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits
|
|
1837
|
+
* of the cube roots of the first 64 primes (2..311).
|
|
1838
|
+
*/
|
|
1839
|
+
const SHA256_K = /* @__PURE__ */ Uint32Array.from([
|
|
1840
|
+
1116352408,
|
|
1841
|
+
1899447441,
|
|
1842
|
+
3049323471,
|
|
1843
|
+
3921009573,
|
|
1844
|
+
961987163,
|
|
1845
|
+
1508970993,
|
|
1846
|
+
2453635748,
|
|
1847
|
+
2870763221,
|
|
1848
|
+
3624381080,
|
|
1849
|
+
310598401,
|
|
1850
|
+
607225278,
|
|
1851
|
+
1426881987,
|
|
1852
|
+
1925078388,
|
|
1853
|
+
2162078206,
|
|
1854
|
+
2614888103,
|
|
1855
|
+
3248222580,
|
|
1856
|
+
3835390401,
|
|
1857
|
+
4022224774,
|
|
1858
|
+
264347078,
|
|
1859
|
+
604807628,
|
|
1860
|
+
770255983,
|
|
1861
|
+
1249150122,
|
|
1862
|
+
1555081692,
|
|
1863
|
+
1996064986,
|
|
1864
|
+
2554220882,
|
|
1865
|
+
2821834349,
|
|
1866
|
+
2952996808,
|
|
1867
|
+
3210313671,
|
|
1868
|
+
3336571891,
|
|
1869
|
+
3584528711,
|
|
1870
|
+
113926993,
|
|
1871
|
+
338241895,
|
|
1872
|
+
666307205,
|
|
1873
|
+
773529912,
|
|
1874
|
+
1294757372,
|
|
1875
|
+
1396182291,
|
|
1876
|
+
1695183700,
|
|
1877
|
+
1986661051,
|
|
1878
|
+
2177026350,
|
|
1879
|
+
2456956037,
|
|
1880
|
+
2730485921,
|
|
1881
|
+
2820302411,
|
|
1882
|
+
3259730800,
|
|
1883
|
+
3345764771,
|
|
1884
|
+
3516065817,
|
|
1885
|
+
3600352804,
|
|
1886
|
+
4094571909,
|
|
1887
|
+
275423344,
|
|
1888
|
+
430227734,
|
|
1889
|
+
506948616,
|
|
1890
|
+
659060556,
|
|
1891
|
+
883997877,
|
|
1892
|
+
958139571,
|
|
1893
|
+
1322822218,
|
|
1894
|
+
1537002063,
|
|
1895
|
+
1747873779,
|
|
1896
|
+
1955562222,
|
|
1897
|
+
2024104815,
|
|
1898
|
+
2227730452,
|
|
1899
|
+
2361852424,
|
|
1900
|
+
2428436474,
|
|
1901
|
+
2756734187,
|
|
1902
|
+
3204031479,
|
|
1903
|
+
3329325298
|
|
1904
|
+
]);
|
|
1905
|
+
/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */
|
|
1906
|
+
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
|
|
1907
|
+
/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */
|
|
1908
|
+
var SHA2_32B = class extends HashMD {
|
|
1909
|
+
A = 0;
|
|
1910
|
+
B = 0;
|
|
1911
|
+
C = 0;
|
|
1912
|
+
D = 0;
|
|
1913
|
+
E = 0;
|
|
1914
|
+
F = 0;
|
|
1915
|
+
G = 0;
|
|
1916
|
+
H = 0;
|
|
1917
|
+
constructor(outputLen, IV) {
|
|
1918
|
+
super(64, outputLen, 8, false);
|
|
1919
|
+
this.A = IV[0] | 0;
|
|
1920
|
+
this.B = IV[1] | 0;
|
|
1921
|
+
this.C = IV[2] | 0;
|
|
1922
|
+
this.D = IV[3] | 0;
|
|
1923
|
+
this.E = IV[4] | 0;
|
|
1924
|
+
this.F = IV[5] | 0;
|
|
1925
|
+
this.G = IV[6] | 0;
|
|
1926
|
+
this.H = IV[7] | 0;
|
|
1927
|
+
}
|
|
1928
|
+
get() {
|
|
1929
|
+
const { A, B, C, D, E, F, G, H } = this;
|
|
1930
|
+
return [
|
|
1931
|
+
A,
|
|
1932
|
+
B,
|
|
1933
|
+
C,
|
|
1934
|
+
D,
|
|
1935
|
+
E,
|
|
1936
|
+
F,
|
|
1937
|
+
G,
|
|
1938
|
+
H
|
|
1939
|
+
];
|
|
1940
|
+
}
|
|
1941
|
+
set(A, B, C, D, E, F, G, H) {
|
|
1942
|
+
this.A = A | 0;
|
|
1943
|
+
this.B = B | 0;
|
|
1944
|
+
this.C = C | 0;
|
|
1945
|
+
this.D = D | 0;
|
|
1946
|
+
this.E = E | 0;
|
|
1947
|
+
this.F = F | 0;
|
|
1948
|
+
this.G = G | 0;
|
|
1949
|
+
this.H = H | 0;
|
|
1950
|
+
}
|
|
1951
|
+
_cloneInto(to) {
|
|
1952
|
+
(to ||= new this.constructor()).set(...this.get());
|
|
1953
|
+
return this._cloneIntoMeta(to);
|
|
1954
|
+
}
|
|
1955
|
+
process(view, offset) {
|
|
1956
|
+
for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);
|
|
1957
|
+
for (let i = 16; i < 64; i++) {
|
|
1958
|
+
const W15 = SHA256_W[i - 15];
|
|
1959
|
+
const W2 = SHA256_W[i - 2];
|
|
1960
|
+
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
|
|
1961
|
+
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
|
|
1962
|
+
SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
|
|
1963
|
+
}
|
|
1964
|
+
let { A, B, C, D, E, F, G, H } = this;
|
|
1965
|
+
for (let i = 0; i < 64; i++) {
|
|
1966
|
+
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
|
|
1967
|
+
const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
|
|
1968
|
+
const T2 = (rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22)) + Maj(A, B, C) | 0;
|
|
1969
|
+
H = G;
|
|
1970
|
+
G = F;
|
|
1971
|
+
F = E;
|
|
1972
|
+
E = D + T1 | 0;
|
|
1973
|
+
D = C;
|
|
1974
|
+
C = B;
|
|
1975
|
+
B = A;
|
|
1976
|
+
A = T1 + T2 | 0;
|
|
1977
|
+
}
|
|
1978
|
+
A = A + this.A | 0;
|
|
1979
|
+
B = B + this.B | 0;
|
|
1980
|
+
C = C + this.C | 0;
|
|
1981
|
+
D = D + this.D | 0;
|
|
1982
|
+
E = E + this.E | 0;
|
|
1983
|
+
F = F + this.F | 0;
|
|
1984
|
+
G = G + this.G | 0;
|
|
1985
|
+
H = H + this.H | 0;
|
|
1986
|
+
this.set(A, B, C, D, E, F, G, H);
|
|
1987
|
+
}
|
|
1988
|
+
roundClean() {
|
|
1989
|
+
clean(SHA256_W);
|
|
1990
|
+
}
|
|
1991
|
+
destroy() {
|
|
1992
|
+
this.destroyed = true;
|
|
1993
|
+
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
|
1994
|
+
clean(this.buffer);
|
|
1995
|
+
}
|
|
1996
|
+
};
|
|
1997
|
+
/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */
|
|
1998
|
+
var _SHA256 = class extends SHA2_32B {
|
|
1999
|
+
constructor() {
|
|
2000
|
+
super(32, SHA256_IV);
|
|
2001
|
+
}
|
|
2002
|
+
};
|
|
2003
|
+
/**
|
|
2004
|
+
* SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:
|
|
2005
|
+
*
|
|
2006
|
+
* - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.
|
|
2007
|
+
* - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
|
|
2008
|
+
* - Each sha256 hash is executing 2^18 bit operations.
|
|
2009
|
+
* - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.
|
|
2010
|
+
* @param msg - message bytes to hash
|
|
2011
|
+
* @param opts - Reserved hash options.
|
|
2012
|
+
* @returns Digest bytes.
|
|
2013
|
+
* @example
|
|
2014
|
+
* Hash a message with SHA2-256.
|
|
2015
|
+
* ```ts
|
|
2016
|
+
* sha256(new Uint8Array([97, 98, 99]));
|
|
2017
|
+
* ```
|
|
2018
|
+
*/
|
|
2019
|
+
const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), /* @__PURE__ */ oidNist(1));
|
|
1320
2020
|
//#endregion
|
|
1321
2021
|
//#region packages/gateway-client/src/session-projection-message-content.ts
|
|
1322
2022
|
function readSessionMessageDisplayContent(message) {
|
|
@@ -1334,11 +2034,9 @@ function readSessionMessageDisplayContent(message) {
|
|
|
1334
2034
|
const text = normalizeNullableString(entry ? entry.text : block);
|
|
1335
2035
|
if (text) texts.push(text);
|
|
1336
2036
|
}
|
|
1337
|
-
const fallback = texts.length === 0 ? normalizeNullableString(record?.text) : null;
|
|
1338
2037
|
return {
|
|
1339
|
-
text:
|
|
1340
|
-
hasNonText
|
|
1341
|
-
usesFallbackText: fallback !== null
|
|
2038
|
+
text: (texts.length === 0 ? normalizeNullableString(record?.text) : null) ?? texts.join("\n"),
|
|
2039
|
+
hasNonText
|
|
1342
2040
|
};
|
|
1343
2041
|
}
|
|
1344
2042
|
/** Status notices remain visible but do not define the terminal reply they accompany. */
|
|
@@ -1474,6 +2172,7 @@ function createSessionProjectionEntry(message, options) {
|
|
|
1474
2172
|
//#endregion
|
|
1475
2173
|
//#region packages/gateway-client/src/session-projection-final-identity.ts
|
|
1476
2174
|
/** Terminal identity rules used to reconcile live and durable assistant projections. */
|
|
2175
|
+
const contentIdentityEncoder = new TextEncoder();
|
|
1477
2176
|
/** A run's selected text reply can inherit its terminal tool stop reason. */
|
|
1478
2177
|
function isToolUsePersistedFinalRow(message) {
|
|
1479
2178
|
return asNullableRecord(message)?.["stopReason"] === "toolUse" && !isSessionProjectionToolContinuation(message);
|
|
@@ -1515,8 +2214,9 @@ function readFinalContentIdentity(message) {
|
|
|
1515
2214
|
const identity = readSessionMessageIdentity(message);
|
|
1516
2215
|
const record = asNullableRecord(terminalMessage);
|
|
1517
2216
|
const metadata = asNullableRecord(record?.["__openclaw"]);
|
|
2217
|
+
const hash = sha256.create();
|
|
1518
2218
|
try {
|
|
1519
|
-
|
|
2219
|
+
writeStableStringify([
|
|
1520
2220
|
identity?.role ?? "assistant",
|
|
1521
2221
|
display.text,
|
|
1522
2222
|
display.hasNonText ? record?.content ?? null : null,
|
|
@@ -1526,9 +2226,12 @@ function readFinalContentIdentity(message) {
|
|
|
1526
2226
|
metadata?.cliSessionId ?? null,
|
|
1527
2227
|
metadata?.externalId ?? null
|
|
1528
2228
|
] : null
|
|
1529
|
-
])
|
|
2229
|
+
], (chunk) => hash.update(contentIdentityEncoder.encode(chunk)));
|
|
2230
|
+
return `content:sha256:${bytesToHex(hash.digest())}`;
|
|
1530
2231
|
} catch {
|
|
1531
2232
|
return null;
|
|
2233
|
+
} finally {
|
|
2234
|
+
hash.destroy();
|
|
1532
2235
|
}
|
|
1533
2236
|
}
|
|
1534
2237
|
function hasTerminalStopReason(message) {
|
|
@@ -1668,6 +2371,7 @@ function reduceSessionProjectionRunEvent(projection, event, scope = {}) {
|
|
|
1668
2371
|
type: "runTerminal",
|
|
1669
2372
|
...base,
|
|
1670
2373
|
status: event.state === "aborted" ? "aborted" : event.state === "error" ? errorKind === "timeout" ? "timeout" : "error" : event.yielded === true && stopReason === "end_turn" ? "yielded" : stopReason === "error" ? "error" : "completed",
|
|
2374
|
+
...event.suppressErrorNotice === true ? { suppressErrorNotice: true } : {},
|
|
1671
2375
|
...stopReason === null ? {} : { stopReason },
|
|
1672
2376
|
...errorKind === null ? {} : { errorKind },
|
|
1673
2377
|
...typeof event.errorMessage === "string" ? { errorMessage: event.errorMessage } : {}
|
|
@@ -1846,13 +2550,14 @@ function reconcileSessionProjectionSnapshot(state, messages, scope = {}, options
|
|
|
1846
2550
|
};
|
|
1847
2551
|
}
|
|
1848
2552
|
function updateRun(state, incoming) {
|
|
1849
|
-
const incomingErrorMessage = normalizeNullableString(incoming.errorMessage);
|
|
2553
|
+
const incomingErrorMessage = incoming.suppressErrorNotice ? null : normalizeNullableString(incoming.errorMessage);
|
|
1850
2554
|
const incomingSeq = typeof incoming.seq === "number" && Number.isSafeInteger(incoming.seq) && incoming.seq >= 0 ? incoming.seq : void 0;
|
|
1851
2555
|
const normalizedIncoming = {
|
|
1852
2556
|
...incoming,
|
|
1853
2557
|
seq: incomingSeq
|
|
1854
2558
|
};
|
|
1855
2559
|
if (incomingErrorMessage) normalizedIncoming.errorMessage = incomingErrorMessage;
|
|
2560
|
+
else if (incoming.suppressErrorNotice) normalizedIncoming.errorMessage = void 0;
|
|
1856
2561
|
else delete normalizedIncoming.errorMessage;
|
|
1857
2562
|
const current = state.runs[incoming.runId];
|
|
1858
2563
|
const resumesErrorProjection = current?.status === "error" && incoming.status === "streaming" && current.seq !== void 0 && incomingSeq !== void 0 && incomingSeq > current.seq && isSessionProjectionErrorMessage(current.message, current.errorMessage);
|
|
@@ -1863,9 +2568,10 @@ function updateRun(state, incoming) {
|
|
|
1863
2568
|
const canAcceptFinal = currentHasDisplayableMessage ? current.status === incoming.status || (current.acceptedFinalMessageIdentities?.length ?? 0) > 0 : canRecoverSessionProjectionFinal(current.message, incoming.message);
|
|
1864
2569
|
const acceptFinal = incomingIsFinal && canAcceptFinal && incomingFinalIdentity !== null && !hasSessionProjectionAcceptedFinal(current, incoming.message);
|
|
1865
2570
|
const recoverMessage = acceptFinal && !currentHasDisplayableMessage;
|
|
1866
|
-
const recoverError = normalizeNullableString(current.errorMessage) === null && incomingErrorMessage !== null;
|
|
2571
|
+
const recoverError = !current.suppressErrorNotice && normalizeNullableString(current.errorMessage) === null && incomingErrorMessage !== null;
|
|
1867
2572
|
const updateTerminalSequence = incoming.status !== "streaming" && (incomingSeq === void 0 ? current.seq !== void 0 : current.seq === void 0 || incomingSeq > current.seq);
|
|
1868
|
-
|
|
2573
|
+
const suppressError = incoming.suppressErrorNotice === true && !current.suppressErrorNotice;
|
|
2574
|
+
if (!acceptFinal && !recoverError && !updateTerminalSequence && !suppressError) return state;
|
|
1869
2575
|
const firstFinalIdentity = readSessionProjectionFinalMessageIdentity(current.message);
|
|
1870
2576
|
const previousFinalIdentities = current.acceptedFinalMessageIdentities ?? (firstFinalIdentity ? [firstFinalIdentity] : []);
|
|
1871
2577
|
return {
|
|
@@ -1874,6 +2580,10 @@ function updateRun(state, incoming) {
|
|
|
1874
2580
|
...state.runs,
|
|
1875
2581
|
[incoming.runId]: {
|
|
1876
2582
|
...current,
|
|
2583
|
+
...suppressError ? {
|
|
2584
|
+
suppressErrorNotice: true,
|
|
2585
|
+
errorMessage: void 0
|
|
2586
|
+
} : {},
|
|
1877
2587
|
...updateTerminalSequence ? { seq: incomingSeq } : {},
|
|
1878
2588
|
...recoverMessage ? { message: incoming.message } : {},
|
|
1879
2589
|
...acceptFinal && incomingFinalIdentity ? { acceptedFinalMessageIdentities: [...previousFinalIdentities, incomingFinalIdentity].slice(-32) } : {},
|
|
@@ -1888,17 +2598,18 @@ function updateRun(state, incoming) {
|
|
|
1888
2598
|
const resumedState = resumesErrorProjection ? withEntries(state, state.entries.filter((entry) => !((entry.identity?.runId === incoming.runId || entry.message === current.message) && (asNullableRecord(entry.message)?.stopReason === "error" || entry.message === current.message) && isSessionProjectionErrorMessage(entry.message, current.errorMessage)))) : state;
|
|
1889
2599
|
const previousRuns = current && current.status === "streaming" && incoming.status !== "streaming" ? Object.fromEntries(Object.entries(state.runs).filter(([runId]) => runId !== incoming.runId)) : state.runs;
|
|
1890
2600
|
const acceptedFinalIdentity = incoming.status === "completed" || incoming.status === "yielded" ? readSessionProjectionFinalMessageIdentity(incoming.message) : null;
|
|
2601
|
+
const runs = {
|
|
2602
|
+
...previousRuns,
|
|
2603
|
+
[incoming.runId]: {
|
|
2604
|
+
...resumesErrorProjection ? {} : current,
|
|
2605
|
+
...normalizedIncoming,
|
|
2606
|
+
...acceptedFinalIdentity ? { acceptedFinalMessageIdentities: [acceptedFinalIdentity] } : {},
|
|
2607
|
+
...!resumesErrorProjection && incoming.message === void 0 && current?.message !== void 0 ? { message: current.message } : {}
|
|
2608
|
+
}
|
|
2609
|
+
};
|
|
1891
2610
|
return {
|
|
1892
2611
|
...resumedState,
|
|
1893
|
-
runs: retainSessionProjectionRuns(
|
|
1894
|
-
...previousRuns,
|
|
1895
|
-
[incoming.runId]: {
|
|
1896
|
-
...resumesErrorProjection ? {} : current,
|
|
1897
|
-
...normalizedIncoming,
|
|
1898
|
-
...acceptedFinalIdentity ? { acceptedFinalMessageIdentities: [acceptedFinalIdentity] } : {},
|
|
1899
|
-
...!resumesErrorProjection && incoming.message === void 0 && current?.message !== void 0 ? { message: current.message } : {}
|
|
1900
|
-
}
|
|
1901
|
-
})
|
|
2612
|
+
runs: current?.status === incoming.status ? runs : retainSessionProjectionRuns(runs)
|
|
1902
2613
|
};
|
|
1903
2614
|
}
|
|
1904
2615
|
/** Reduces durable events, snapshots, and transport lifecycle without client-specific policy. */
|
|
@@ -1965,6 +2676,7 @@ function reduceSessionProjection(state, event) {
|
|
|
1965
2676
|
...event.message === void 0 ? {} : { message: event.message },
|
|
1966
2677
|
...event.stopReason === void 0 ? {} : { stopReason: event.stopReason },
|
|
1967
2678
|
...event.errorKind === void 0 ? {} : { errorKind: event.errorKind },
|
|
2679
|
+
...event.suppressErrorNotice === void 0 ? {} : { suppressErrorNotice: event.suppressErrorNotice },
|
|
1968
2680
|
...event.errorMessage === void 0 ? {} : { errorMessage: event.errorMessage }
|
|
1969
2681
|
});
|
|
1970
2682
|
case "transportGap": return state.hasTransportGap ? state : {
|
|
@@ -2008,11 +2720,6 @@ function normalizeAgentIdStrict(value) {
|
|
|
2008
2720
|
//#endregion
|
|
2009
2721
|
//#region packages/normalization-core/src/uuid.ts
|
|
2010
2722
|
let warnedWeakCrypto = false;
|
|
2011
|
-
function warnWeakCryptoOnce() {
|
|
2012
|
-
if (warnedWeakCrypto) return;
|
|
2013
|
-
warnedWeakCrypto = true;
|
|
2014
|
-
console.warn("[uuid] crypto API missing; refusing insecure UUID generation");
|
|
2015
|
-
}
|
|
2016
2723
|
function generateUUID(cryptoLike = globalThis.crypto) {
|
|
2017
2724
|
if (cryptoLike && typeof cryptoLike.randomUUID === "function") return cryptoLike.randomUUID();
|
|
2018
2725
|
if (cryptoLike && typeof cryptoLike.getRandomValues === "function") {
|
|
@@ -2024,7 +2731,10 @@ function generateUUID(cryptoLike = globalThis.crypto) {
|
|
|
2024
2731
|
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
2025
2732
|
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
2026
2733
|
}
|
|
2027
|
-
|
|
2734
|
+
if (!warnedWeakCrypto) {
|
|
2735
|
+
warnedWeakCrypto = true;
|
|
2736
|
+
console.warn("[uuid] crypto API missing; refusing insecure UUID generation");
|
|
2737
|
+
}
|
|
2028
2738
|
throw new Error("Web Crypto is required for UUID generation");
|
|
2029
2739
|
}
|
|
2030
2740
|
//#endregion
|
|
@@ -2074,7 +2784,25 @@ var GatewaySessionMessageSubscriptionCoordinator = class {
|
|
|
2074
2784
|
await (provisional.plainFallback ?? provisional.ready).catch(() => void 0);
|
|
2075
2785
|
continue;
|
|
2076
2786
|
}
|
|
2077
|
-
entry =
|
|
2787
|
+
entry = {
|
|
2788
|
+
subscriptionId: generateUUID(),
|
|
2789
|
+
key: normalizedKey,
|
|
2790
|
+
requestedKeys: /* @__PURE__ */ new Set([normalizedKey]),
|
|
2791
|
+
agentId,
|
|
2792
|
+
scopeAgentId: normalizedAgentScope(agentId),
|
|
2793
|
+
ownerAgentId: null,
|
|
2794
|
+
ready: Promise.resolve({ key: normalizedKey }),
|
|
2795
|
+
approvalRequest: null,
|
|
2796
|
+
plainFallback: null,
|
|
2797
|
+
wireRequest: null,
|
|
2798
|
+
includeApprovals: false,
|
|
2799
|
+
canonicalSettled: false,
|
|
2800
|
+
handles: /* @__PURE__ */ new Set(),
|
|
2801
|
+
pendingOwners: 0,
|
|
2802
|
+
pendingFullOwners: 0,
|
|
2803
|
+
release: null
|
|
2804
|
+
};
|
|
2805
|
+
this.#entries.add(entry);
|
|
2078
2806
|
created = true;
|
|
2079
2807
|
break;
|
|
2080
2808
|
}
|
|
@@ -2089,16 +2817,22 @@ var GatewaySessionMessageSubscriptionCoordinator = class {
|
|
|
2089
2817
|
if (!narration) entry.pendingFullOwners += 1;
|
|
2090
2818
|
try {
|
|
2091
2819
|
if (created) {
|
|
2092
|
-
entry.ready = this.#requestSubscribe(entry, includeApprovals);
|
|
2820
|
+
entry.ready = this.#requestSubscribe(entry, includeApprovals, void 0, options.initialHistory);
|
|
2093
2821
|
if (includeApprovals) entry.ready = this.#trackApprovalRequest(entry, entry.ready);
|
|
2094
2822
|
entry.ready.catch(() => void 0);
|
|
2095
2823
|
}
|
|
2096
2824
|
const result = await this.#acquireCapability(entry, includeApprovals);
|
|
2825
|
+
if (created && result.initialHistory) {
|
|
2826
|
+
const { initialHistory: _initialHistory, ...subscriptionResult } = result;
|
|
2827
|
+
entry.ready = Promise.resolve(subscriptionResult);
|
|
2828
|
+
entry.plainFallback = null;
|
|
2829
|
+
}
|
|
2097
2830
|
if (!narration && entry.mode === "narration") await this.#requestSubscribe(entry, false, "full");
|
|
2098
2831
|
if (this.#retired) throw new Error("Session message subscription completed on a replaced Gateway connection");
|
|
2099
2832
|
const subscription = {
|
|
2100
2833
|
key: result.key,
|
|
2101
2834
|
agentId,
|
|
2835
|
+
...created && result.initialHistory ? { initialHistory: result.initialHistory } : {},
|
|
2102
2836
|
...narration ? { mode: "narration" } : {},
|
|
2103
2837
|
...includeApprovals ? {
|
|
2104
2838
|
includeApprovals: true,
|
|
@@ -2157,28 +2891,6 @@ var GatewaySessionMessageSubscriptionCoordinator = class {
|
|
|
2157
2891
|
}
|
|
2158
2892
|
this.#entries.clear();
|
|
2159
2893
|
}
|
|
2160
|
-
#createEntry(key, agentId) {
|
|
2161
|
-
const entry = {
|
|
2162
|
-
subscriptionId: generateUUID(),
|
|
2163
|
-
key,
|
|
2164
|
-
requestedKeys: /* @__PURE__ */ new Set([key]),
|
|
2165
|
-
agentId,
|
|
2166
|
-
scopeAgentId: normalizedAgentScope(agentId),
|
|
2167
|
-
ownerAgentId: null,
|
|
2168
|
-
ready: Promise.resolve({ key }),
|
|
2169
|
-
approvalRequest: null,
|
|
2170
|
-
plainFallback: null,
|
|
2171
|
-
wireRequest: null,
|
|
2172
|
-
includeApprovals: false,
|
|
2173
|
-
canonicalSettled: false,
|
|
2174
|
-
handles: /* @__PURE__ */ new Set(),
|
|
2175
|
-
pendingOwners: 0,
|
|
2176
|
-
pendingFullOwners: 0,
|
|
2177
|
-
release: null
|
|
2178
|
-
};
|
|
2179
|
-
this.#entries.add(entry);
|
|
2180
|
-
return entry;
|
|
2181
|
-
}
|
|
2182
2894
|
#acquireCapability(entry, includeApprovals) {
|
|
2183
2895
|
if (!includeApprovals) {
|
|
2184
2896
|
if (entry.approvalRequest === entry.ready) {
|
|
@@ -2206,8 +2918,30 @@ var GatewaySessionMessageSubscriptionCoordinator = class {
|
|
|
2206
2918
|
entry.approvalRequest = tracked;
|
|
2207
2919
|
return tracked;
|
|
2208
2920
|
}
|
|
2209
|
-
#requestSubscribe(entry,
|
|
2210
|
-
const send = () =>
|
|
2921
|
+
#requestSubscribe(entry, requestedApprovals, requestedMode, initialHistory) {
|
|
2922
|
+
const send = async () => {
|
|
2923
|
+
if (this.#retired) throw new Error("Session message subscription belongs to a replaced Gateway connection");
|
|
2924
|
+
if (requestedMode === "full" && entry.mode !== "narration") return { key: entry.key };
|
|
2925
|
+
const includeApprovals = requestedApprovals || requestedMode !== void 0 && entry.includeApprovals;
|
|
2926
|
+
const mode = requestedMode === "narration" || requestedMode !== "full" && entry.pendingFullOwners === 0 && [...entry.handles].every((handle) => handle.mode === "narration") ? "narration" : void 0;
|
|
2927
|
+
const response = await this.#requestMessages(entry, {
|
|
2928
|
+
mode,
|
|
2929
|
+
includeApprovals,
|
|
2930
|
+
initialHistory
|
|
2931
|
+
}) ?? null;
|
|
2932
|
+
const responseKey = response && "key" in response ? response.key : void 0;
|
|
2933
|
+
entry.key = typeof responseKey === "string" && responseKey.trim() ? responseKey.trim() : entry.key;
|
|
2934
|
+
entry.canonicalSettled = true;
|
|
2935
|
+
const responseAgentId = response && "agentId" in response ? response.agentId : void 0;
|
|
2936
|
+
entry.ownerAgentId = normalizedAgentScope((typeof responseAgentId === "string" ? responseAgentId : null) ?? entry.ownerAgentId ?? entry.scopeAgentId);
|
|
2937
|
+
entry.mode = mode;
|
|
2938
|
+
entry.includeApprovals = includeApprovals;
|
|
2939
|
+
return {
|
|
2940
|
+
key: entry.key,
|
|
2941
|
+
...response && "approvalReplay" in response ? { approvalReplay: response.approvalReplay } : {},
|
|
2942
|
+
...response?.initialHistory ? { initialHistory: response.initialHistory } : {}
|
|
2943
|
+
};
|
|
2944
|
+
};
|
|
2211
2945
|
const tracked = (entry.wireRequest ? entry.wireRequest.then(send, send) : send()).finally(() => {
|
|
2212
2946
|
if (entry.wireRequest === tracked) entry.wireRequest = null;
|
|
2213
2947
|
});
|
|
@@ -2221,31 +2955,10 @@ var GatewaySessionMessageSubscriptionCoordinator = class {
|
|
|
2221
2955
|
key: entry.key,
|
|
2222
2956
|
...agentId ? { agentId } : {},
|
|
2223
2957
|
...subscription?.mode ? { mode: subscription.mode } : {},
|
|
2224
|
-
...subscription?.includeApprovals ? { includeApprovals: true } : {}
|
|
2958
|
+
...subscription?.includeApprovals ? { includeApprovals: true } : {},
|
|
2959
|
+
...subscription?.initialHistory ? { initialHistory: subscription.initialHistory } : {}
|
|
2225
2960
|
}, { timeoutMs: DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS });
|
|
2226
2961
|
}
|
|
2227
|
-
async #sendSubscribe(entry, requestedApprovals, requestedMode) {
|
|
2228
|
-
if (this.#retired) throw new Error("Session message subscription belongs to a replaced Gateway connection");
|
|
2229
|
-
if (requestedMode === "full" && entry.mode !== "narration") return { key: entry.key };
|
|
2230
|
-
const includeApprovals = requestedApprovals || requestedMode !== void 0 && entry.includeApprovals;
|
|
2231
|
-
const mode = requestedMode === "narration" || requestedMode !== "full" && entry.pendingFullOwners === 0 && [...entry.handles].every((handle) => handle.mode === "narration") ? "narration" : void 0;
|
|
2232
|
-
const result = await this.#requestMessages(entry, {
|
|
2233
|
-
mode,
|
|
2234
|
-
includeApprovals
|
|
2235
|
-
});
|
|
2236
|
-
const response = result && typeof result === "object" ? result : null;
|
|
2237
|
-
const responseKey = response && "key" in response ? response.key : void 0;
|
|
2238
|
-
entry.key = typeof responseKey === "string" && responseKey.trim() ? responseKey.trim() : entry.key;
|
|
2239
|
-
entry.canonicalSettled = true;
|
|
2240
|
-
const responseAgentId = response && "agentId" in response ? response.agentId : void 0;
|
|
2241
|
-
entry.ownerAgentId = normalizedAgentScope((typeof responseAgentId === "string" ? responseAgentId : null) ?? entry.ownerAgentId ?? entry.scopeAgentId);
|
|
2242
|
-
entry.mode = mode;
|
|
2243
|
-
entry.includeApprovals = includeApprovals;
|
|
2244
|
-
return {
|
|
2245
|
-
key: entry.key,
|
|
2246
|
-
...response && "approvalReplay" in response ? { approvalReplay: response.approvalReplay } : {}
|
|
2247
|
-
};
|
|
2248
|
-
}
|
|
2249
2962
|
#finishRelease(subscription, owner, removeEntry = false) {
|
|
2250
2963
|
if (sessionMessageSubscriptionOwners.get(subscription) !== owner) return;
|
|
2251
2964
|
sessionMessageSubscriptionOwners.delete(subscription);
|
|
@@ -2278,4 +2991,4 @@ function releaseGatewaySessionMessageSubscription(subscription) {
|
|
|
2278
2991
|
return sessionMessageSubscriptionOwners.get(subscription)?.coordinator.release(subscription) ?? Promise.resolve();
|
|
2279
2992
|
}
|
|
2280
2993
|
//#endregion
|
|
2281
|
-
export {
|
|
2994
|
+
export { GatewayBrowserDeviceAuthLifecycle as A, buildDeviceAuthPayload as B, isGatewayProtocolResponseError as C, resolveModelCatalogConnect as D, toStringifiedError as E, mergeChatStreamMessage as F, normalizeDeviceMetadataForAuth as H, asNullableRecord as I, asOptionalRecord as L, resolveGatewayConnectScopes as M, selectGatewayConnectAuth as N, gatewayCredentialScope as O, shouldRetryGatewayWithDeviceToken as P, asRecord as R, GatewayProtocolRequestTimeoutError as S, raceWithTimeout as T, buildDeviceAuthPayloadV3 as V, isSessionProjectionErrorMessage as _, createSessionProjection as a, GatewayProtocolClient as b, reduceSessionProjection as c, readSessionProjectionFinalMessageIdentity as d, isLocallyOptimisticSessionMessage as f, readSessionMessageSequence as g, readSessionMessageIdentity as h, resetGatewaySessionMessageSubscriptionCoordinator as i, buildGatewayConnectAuth as j, gatewayOriginScope as k, reduceSessionProjectionRunEvent as l, readAssistantStreamSegmentIdentity as m, getGatewaySessionMessageSubscriptionCoordinator as n, projectLiveSessionMessage as o, normalizeSessionProjectionRunId as p, releaseGatewaySessionMessageSubscription as r, reconcileSessionProjectionSnapshot as s, GatewaySessionMessageSubscriptionCoordinator as t, hasSessionProjectionAcceptedFinal as u, projectSessionTerminalReplyMessage as v, createAbortError as w, GatewayProtocolRequestError as x, shouldPauseGatewayReconnect as y, isRecord as z };
|