@asiyst/sdk 0.1.29 → 0.1.30
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 +5 -2
- package/dist/index.cjs +574 -593
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -1
- package/dist/index.d.ts +7 -1
- package/dist/index.js +574 -593
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -75,7 +75,7 @@ var ALL_ACTION_KINDS = [
|
|
|
75
75
|
// src/core/constants.ts
|
|
76
76
|
function resolveSdkVersion() {
|
|
77
77
|
{
|
|
78
|
-
return "0.1.
|
|
78
|
+
return "0.1.29";
|
|
79
79
|
}
|
|
80
80
|
}
|
|
81
81
|
var SDK_VERSION = resolveSdkVersion();
|
|
@@ -94,7 +94,7 @@ var AVATAR_TARGET_GAP = 16;
|
|
|
94
94
|
var WEBSITE_MAP_TEXT_LIMIT = 80;
|
|
95
95
|
var CONFIG_CACHE_TTL_MS = 1e3 * 30;
|
|
96
96
|
var CONFIG_REVALIDATION_INTERVAL_MS = 3e4;
|
|
97
|
-
var HEARTBEAT_INTERVAL_MS =
|
|
97
|
+
var HEARTBEAT_INTERVAL_MS = 3e5;
|
|
98
98
|
|
|
99
99
|
// src/security/selectors.ts
|
|
100
100
|
var DANGEROUS_SELECTOR = /javascript:|expression\(|@import|url\s*\(|behavior:|binding:|<script/i;
|
|
@@ -356,7 +356,8 @@ function parseAnimations(value) {
|
|
|
356
356
|
clipName: typeof item.clipName === "string" ? sanitizeText(item.clipName, 64) : void 0,
|
|
357
357
|
loopMode: typeof item.loopMode === "string" ? sanitizeText(item.loopMode, 32) : void 0,
|
|
358
358
|
durationMs: typeof item.durationMs === "number" ? item.durationMs : void 0,
|
|
359
|
-
assetUrl: typeof item.assetUrl === "string" ? item.assetUrl : null
|
|
359
|
+
assetUrl: typeof item.assetUrl === "string" ? item.assetUrl : null,
|
|
360
|
+
integrity: typeof item.integrity === "string" ? item.integrity : void 0
|
|
360
361
|
});
|
|
361
362
|
}
|
|
362
363
|
}
|
|
@@ -383,6 +384,8 @@ function normalizeProjectConfig(raw) {
|
|
|
383
384
|
) || void 0;
|
|
384
385
|
const assetUrl = typeof raw.assetUrl === "string" && raw.assetUrl ? raw.assetUrl : typeof rawAvatarRecord?.assetUrl === "string" && rawAvatarRecord.assetUrl ? rawAvatarRecord.assetUrl : typeof rawAvatarRecord?.modelUrl === "string" && rawAvatarRecord.modelUrl ? rawAvatarRecord.modelUrl : typeof rawConfigRecord?.assetUrl === "string" && rawConfigRecord.assetUrl ? rawConfigRecord.assetUrl : typeof rawManifestRecord?.assetUrl === "string" && rawManifestRecord.assetUrl ? rawManifestRecord.assetUrl : typeof rawManifestRecord?.modelUrl === "string" && rawManifestRecord.modelUrl ? rawManifestRecord.modelUrl : void 0;
|
|
385
386
|
const thumbnailUrl = typeof raw.thumbnailUrl === "string" ? raw.thumbnailUrl : typeof rawAvatarRecord?.thumbnailUrl === "string" ? rawAvatarRecord.thumbnailUrl : typeof rawConfigRecord?.thumbnailUrl === "string" ? rawConfigRecord.thumbnailUrl : typeof rawManifestRecord?.thumbnailUrl === "string" ? rawManifestRecord.thumbnailUrl : rawAvatarRecord?.thumbnailUrl === null ? null : void 0;
|
|
387
|
+
const rawModelFormat = raw.modelFormat ?? rawAvatarRecord?.modelFormat ?? rawConfigRecord?.modelFormat ?? rawManifestRecord?.modelFormat;
|
|
388
|
+
const modelFormat = rawModelFormat === "fbx" || rawModelFormat === "glb" ? rawModelFormat : void 0;
|
|
386
389
|
const publishedVersion = typeof raw.publishedVersion === "string" ? raw.publishedVersion : typeof rawAvatarRecord?.version === "string" ? rawAvatarRecord.version : typeof rawManifestRecord?.version === "string" ? rawManifestRecord.version : void 0;
|
|
387
390
|
const animations = parseAnimations(
|
|
388
391
|
raw.animations ?? rawAvatarRecord?.animations ?? rawConfigRecord?.animations
|
|
@@ -402,6 +405,8 @@ function normalizeProjectConfig(raw) {
|
|
|
402
405
|
avatar,
|
|
403
406
|
avatarId,
|
|
404
407
|
assetUrl,
|
|
408
|
+
modelFormat,
|
|
409
|
+
assetIntegrity: typeof raw.assetIntegrity === "string" ? raw.assetIntegrity : typeof rawAvatarRecord?.assetIntegrity === "string" ? rawAvatarRecord.assetIntegrity : void 0,
|
|
405
410
|
thumbnailUrl,
|
|
406
411
|
publishedVersion,
|
|
407
412
|
animations,
|
|
@@ -420,7 +425,8 @@ function normalizeProjectConfig(raw) {
|
|
|
420
425
|
blockedRoutes: parseStringList(raw.blockedRoutes ?? raw.blocked_routes),
|
|
421
426
|
rules: parseRules(raw.rules ?? raw.avatarRules),
|
|
422
427
|
dataSources: parseDataSources(raw.dataSources ?? raw.enabledDataSources),
|
|
423
|
-
elementSelectors: parseElementSelectors(raw.elementSelectors)
|
|
428
|
+
elementSelectors: parseElementSelectors(raw.elementSelectors),
|
|
429
|
+
maxMessageChars: asNumber(raw.maxMessageChars, 4e3, 1, 4e3)
|
|
424
430
|
};
|
|
425
431
|
}
|
|
426
432
|
function validateInitOptions(options) {
|
|
@@ -504,7 +510,7 @@ var HttpTransport = class {
|
|
|
504
510
|
return this.options.avatarId;
|
|
505
511
|
}
|
|
506
512
|
async request(req) {
|
|
507
|
-
const url = `${this.options.apiBaseUrl.replace(/\/$/, "")}${req.path}`;
|
|
513
|
+
const url = /^https?:\/\//i.test(req.path) ? req.path : `${this.options.apiBaseUrl.replace(/\/$/, "")}${req.path}`;
|
|
508
514
|
const requestId = req.requestId || generateRequestId();
|
|
509
515
|
const timeoutMs = req.timeoutMs ?? this.options.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
510
516
|
const isSafeOrIdempotent = req.method === "GET" || Boolean(req.idempotent);
|
|
@@ -532,36 +538,30 @@ var HttpTransport = class {
|
|
|
532
538
|
}
|
|
533
539
|
try {
|
|
534
540
|
let response;
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
});
|
|
553
|
-
} finally {
|
|
554
|
-
clearTimeout(timeoutId);
|
|
555
|
-
if (req.signal) {
|
|
556
|
-
req.signal.removeEventListener("abort", onExternalAbort);
|
|
557
|
-
}
|
|
558
|
-
}
|
|
541
|
+
response = await fetch(url, {
|
|
542
|
+
method: req.method,
|
|
543
|
+
headers: req.headers ?? {
|
|
544
|
+
Accept: "application/json",
|
|
545
|
+
"Content-Type": "application/json",
|
|
546
|
+
"X-Asiyst-Project-Id": this.options.projectId,
|
|
547
|
+
"X-Asiyst-Public-Key": this.options.publicKey,
|
|
548
|
+
...this.options.avatarId ? { "X-Asiyst-Avatar-Id": this.options.avatarId } : {},
|
|
549
|
+
"X-Asiyst-SDK-Version": SDK_VERSION,
|
|
550
|
+
"X-Asiyst-Request-Id": requestId,
|
|
551
|
+
...req.sessionId ? { "X-Asiyst-Session-Id": req.sessionId } : {},
|
|
552
|
+
...req.conversationId ? { "X-Asiyst-Conversation-Id": req.conversationId } : {},
|
|
553
|
+
...req.authorizationToken ? { Authorization: `Bearer ${req.authorizationToken}` } : {}
|
|
554
|
+
},
|
|
555
|
+
body: req.body === void 0 ? void 0 : JSON.stringify(req.body),
|
|
556
|
+
signal: controller.signal
|
|
557
|
+
});
|
|
559
558
|
if (isSafeOrIdempotent && attempt < maxRetries && [502, 503, 504].includes(response.status)) {
|
|
560
559
|
continue;
|
|
561
560
|
}
|
|
562
561
|
if (response.status === 429 && isSafeOrIdempotent && attempt < maxRetries) {
|
|
563
562
|
const retryAfterHeader = response.headers.get("retry-after");
|
|
564
563
|
const retryAfterMs = retryAfterHeader ? Math.min(Number(retryAfterHeader) * 1e3 || 200, 1e3) : 100;
|
|
564
|
+
clearTimeout(timeoutId);
|
|
565
565
|
await new Promise((resolve) => setTimeout(resolve, retryAfterMs));
|
|
566
566
|
continue;
|
|
567
567
|
}
|
|
@@ -571,33 +571,87 @@ var HttpTransport = class {
|
|
|
571
571
|
try {
|
|
572
572
|
data = await response.json();
|
|
573
573
|
} catch {
|
|
574
|
+
if (timedOut) {
|
|
575
|
+
throw new NetworkError("Asiyst Cloud request timed out");
|
|
576
|
+
}
|
|
577
|
+
if (req.signal?.aborted) {
|
|
578
|
+
throw new NetworkError("Asiyst Cloud request was aborted");
|
|
579
|
+
}
|
|
574
580
|
data = null;
|
|
575
581
|
}
|
|
576
582
|
}
|
|
577
583
|
if (!response.ok) {
|
|
578
|
-
return { ok: false, status: response.status, data };
|
|
584
|
+
return { ok: false, status: response.status, data, headers: response.headers };
|
|
579
585
|
}
|
|
580
|
-
return { ok: true, status: response.status, data };
|
|
586
|
+
return { ok: true, status: response.status, data, headers: response.headers };
|
|
581
587
|
} catch (err) {
|
|
582
|
-
clearTimeout(timeoutId);
|
|
583
|
-
if (req.signal) {
|
|
584
|
-
req.signal.removeEventListener("abort", onExternalAbort);
|
|
585
|
-
}
|
|
586
588
|
if (timedOut) {
|
|
587
589
|
throw new NetworkError("Asiyst Cloud request timed out");
|
|
588
590
|
}
|
|
591
|
+
if (req.signal?.aborted) {
|
|
592
|
+
throw new NetworkError("Asiyst Cloud request was aborted");
|
|
593
|
+
}
|
|
589
594
|
lastError = err;
|
|
590
595
|
if (isSafeOrIdempotent && attempt < maxRetries) {
|
|
591
596
|
continue;
|
|
592
597
|
}
|
|
593
598
|
throw new NetworkError("Asiyst Cloud is unreachable");
|
|
599
|
+
} finally {
|
|
600
|
+
clearTimeout(timeoutId);
|
|
601
|
+
if (req.signal) {
|
|
602
|
+
req.signal.removeEventListener("abort", onExternalAbort);
|
|
603
|
+
}
|
|
594
604
|
}
|
|
595
605
|
}
|
|
596
606
|
throw lastError instanceof Error ? lastError : new NetworkError("Asiyst Cloud is unreachable");
|
|
597
607
|
}
|
|
598
608
|
};
|
|
599
609
|
|
|
610
|
+
// ../api-contract.ts
|
|
611
|
+
var API_V1_BASE_PATH = "/api/v1";
|
|
612
|
+
var API_ROUTES = {
|
|
613
|
+
runtimeAvatar: "/runtime/avatar",
|
|
614
|
+
runtimeToken: "/sdk/runtime/token",
|
|
615
|
+
installationRegister: "/sdk/installations/register",
|
|
616
|
+
runtimeHeartbeat: "/sdk/heartbeat",
|
|
617
|
+
chat: "/conversations/messages",
|
|
618
|
+
projectApiKeyVerify: (projectId) => `/projects/${encodeURIComponent(projectId)}/api-key/verify`,
|
|
619
|
+
sdkInstallationVerify: "/sdk/installations/verify"
|
|
620
|
+
};
|
|
621
|
+
var API_LIMITS = {
|
|
622
|
+
configStaleIfErrorMs: 0,
|
|
623
|
+
maxMessageChars: 12e3,
|
|
624
|
+
pageUrlMaxChars: 2048};
|
|
625
|
+
function apiV1Path(route) {
|
|
626
|
+
return `${API_V1_BASE_PATH}${route.startsWith("/") ? route : `/${route}`}`;
|
|
627
|
+
}
|
|
628
|
+
function contractApiBaseUrl(configuredApiBaseUrl) {
|
|
629
|
+
const parsed = new URL(configuredApiBaseUrl);
|
|
630
|
+
if (parsed.pathname.replace(/\/+$/, "").endsWith("/functions/v1/api")) {
|
|
631
|
+
return "https://asiyst.com";
|
|
632
|
+
}
|
|
633
|
+
return parsed.origin;
|
|
634
|
+
}
|
|
635
|
+
function contractApiUrl(configuredApiBaseUrl, route) {
|
|
636
|
+
return `${contractApiBaseUrl(configuredApiBaseUrl).replace(/\/+$/, "")}${apiV1Path(route)}`;
|
|
637
|
+
}
|
|
638
|
+
|
|
600
639
|
// src/communication/CloudClient.ts
|
|
640
|
+
function newRequestId() {
|
|
641
|
+
const cryptoApi = globalThis.crypto;
|
|
642
|
+
if (typeof cryptoApi?.randomUUID === "function") return cryptoApi.randomUUID();
|
|
643
|
+
if (typeof cryptoApi?.getRandomValues === "function") {
|
|
644
|
+
const bytes = cryptoApi.getRandomValues(new Uint8Array(16));
|
|
645
|
+
bytes[6] = (bytes[6] ?? 0) & 15 | 64;
|
|
646
|
+
bytes[8] = (bytes[8] ?? 0) & 63 | 128;
|
|
647
|
+
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
648
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
649
|
+
}
|
|
650
|
+
throw new ConfigurationError("Secure request identifiers are unavailable in this browser.");
|
|
651
|
+
}
|
|
652
|
+
function isUuid(value) {
|
|
653
|
+
return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
|
|
654
|
+
}
|
|
601
655
|
var CloudClient = class {
|
|
602
656
|
constructor(transport, projectId, publicKey = "", runtimeAuth, sessionId, avatarId) {
|
|
603
657
|
this.transport = transport;
|
|
@@ -605,6 +659,7 @@ var CloudClient = class {
|
|
|
605
659
|
this.publicKey = publicKey;
|
|
606
660
|
this.runtimeAuth = runtimeAuth;
|
|
607
661
|
this.avatarId = avatarId;
|
|
662
|
+
this.configMetadata = {};
|
|
608
663
|
this.inFlightConversations = /* @__PURE__ */ new Map();
|
|
609
664
|
this.sessionId = sessionId;
|
|
610
665
|
if (!this.avatarId && typeof transport.getAvatarId === "function") {
|
|
@@ -635,243 +690,152 @@ var CloudClient = class {
|
|
|
635
690
|
}
|
|
636
691
|
return DEFAULT_API_BASE_URL;
|
|
637
692
|
}
|
|
638
|
-
async getAuthToken(
|
|
693
|
+
async getAuthToken() {
|
|
639
694
|
if (!this.runtimeAuth) return void 0;
|
|
640
695
|
if (this.tokenRefreshPromise) return this.tokenRefreshPromise;
|
|
641
|
-
|
|
642
|
-
this.
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
}
|
|
649
|
-
return this.inFlightToken;
|
|
696
|
+
this.tokenRefreshPromise = this.runtimeAuth.getToken().then((token) => {
|
|
697
|
+
this.activeToken = token;
|
|
698
|
+
return token;
|
|
699
|
+
}).finally(() => {
|
|
700
|
+
this.tokenRefreshPromise = void 0;
|
|
701
|
+
});
|
|
702
|
+
return this.tokenRefreshPromise;
|
|
650
703
|
}
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
const
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
704
|
+
getConfigMetadata() {
|
|
705
|
+
return this.configMetadata;
|
|
706
|
+
}
|
|
707
|
+
async fetchConfig(etag, cachedConfig) {
|
|
708
|
+
const response = await this.transport.request({
|
|
709
|
+
path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.runtimeAvatar),
|
|
710
|
+
method: "GET",
|
|
711
|
+
idempotent: true,
|
|
712
|
+
retries: 2,
|
|
713
|
+
headers: {
|
|
714
|
+
Accept: "application/json",
|
|
715
|
+
"X-Asiyst-Public-Key": this.publicKey,
|
|
716
|
+
"X-Asiyst-Project-Id": this.projectId,
|
|
717
|
+
...this.avatarId ? { "X-Asiyst-Avatar-Id": this.avatarId } : {},
|
|
718
|
+
...etag ? { "If-None-Match": etag } : {}
|
|
664
719
|
}
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
720
|
+
});
|
|
721
|
+
if (response.status === 304 && cachedConfig) {
|
|
722
|
+
this.configMetadata = {
|
|
723
|
+
etag: response.headers?.get("etag") ?? etag,
|
|
724
|
+
maxAgeMs: 0,
|
|
725
|
+
staleIfErrorMs: 0
|
|
670
726
|
};
|
|
671
|
-
|
|
672
|
-
const av = { ...raw.avatar };
|
|
673
|
-
av.assetUrl = toAbsolute(av.assetUrl);
|
|
674
|
-
av.thumbnailUrl = toAbsolute(av.thumbnailUrl);
|
|
675
|
-
av.modelUrl = toAbsolute(av.modelUrl);
|
|
676
|
-
av.manifestUrl = toAbsolute(av.manifestUrl);
|
|
677
|
-
if (Array.isArray(av.animations)) {
|
|
678
|
-
av.animations = av.animations.map((item) => {
|
|
679
|
-
if (item && typeof item === "object") {
|
|
680
|
-
const animObj = item;
|
|
681
|
-
return { ...animObj, assetUrl: toAbsolute(animObj.assetUrl) };
|
|
682
|
-
}
|
|
683
|
-
return item;
|
|
684
|
-
});
|
|
685
|
-
}
|
|
686
|
-
raw.avatar = av;
|
|
687
|
-
}
|
|
688
|
-
if (raw.config && typeof raw.config === "object" && !Array.isArray(raw.config)) {
|
|
689
|
-
const cfg = { ...raw.config };
|
|
690
|
-
cfg.assetUrl = toAbsolute(cfg.assetUrl);
|
|
691
|
-
cfg.thumbnailUrl = toAbsolute(cfg.thumbnailUrl);
|
|
692
|
-
cfg.manifestUrl = toAbsolute(cfg.manifestUrl);
|
|
693
|
-
raw.config = cfg;
|
|
694
|
-
}
|
|
695
|
-
if (raw.manifest && typeof raw.manifest === "object" && !Array.isArray(raw.manifest)) {
|
|
696
|
-
const mf = { ...raw.manifest };
|
|
697
|
-
mf.assetUrl = toAbsolute(mf.assetUrl);
|
|
698
|
-
mf.thumbnailUrl = toAbsolute(mf.thumbnailUrl);
|
|
699
|
-
mf.modelUrl = toAbsolute(mf.modelUrl);
|
|
700
|
-
raw.manifest = mf;
|
|
701
|
-
}
|
|
702
|
-
raw.assetUrl = toAbsolute(raw.assetUrl);
|
|
703
|
-
raw.thumbnailUrl = toAbsolute(raw.thumbnailUrl);
|
|
704
|
-
raw.manifestUrl = toAbsolute(raw.manifestUrl);
|
|
705
|
-
if (raw.branding && typeof raw.branding === "object" && !Array.isArray(raw.branding)) {
|
|
706
|
-
const br = { ...raw.branding };
|
|
707
|
-
br.siteLogoUrl = toAbsolute(br.siteLogoUrl);
|
|
708
|
-
raw.branding = br;
|
|
709
|
-
}
|
|
710
|
-
return raw;
|
|
711
|
-
};
|
|
712
|
-
let lastError;
|
|
713
|
-
try {
|
|
714
|
-
const response = await this.runtimeRequest({
|
|
715
|
-
path: `/projects/${encodeURIComponent(this.projectId)}/avatar${avatarParam}`,
|
|
716
|
-
method: "GET",
|
|
717
|
-
idempotent: true
|
|
718
|
-
});
|
|
719
|
-
if (response.ok && response.data) {
|
|
720
|
-
const fullData = response.data && typeof response.data === "object" && !Array.isArray(response.data) ? {
|
|
721
|
-
...response.data,
|
|
722
|
-
...response.data.config && typeof response.data.config === "object" ? response.data.config : {}
|
|
723
|
-
} : {};
|
|
724
|
-
return normalizeProjectConfig(resolveAssetUrls(fullData));
|
|
725
|
-
}
|
|
726
|
-
if (response.status === 404) {
|
|
727
|
-
lastError = new ConfigurationError(`Project ${this.projectId} or avatar configuration not found`);
|
|
728
|
-
}
|
|
729
|
-
} catch (err) {
|
|
730
|
-
if (err instanceof Error) lastError = err;
|
|
727
|
+
return cachedConfig;
|
|
731
728
|
}
|
|
732
|
-
|
|
733
|
-
const
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
});
|
|
738
|
-
if (runtimeResponse.ok && runtimeResponse.data) {
|
|
739
|
-
return normalizeProjectConfig(resolveAssetUrls(runtimeResponse.data));
|
|
740
|
-
}
|
|
741
|
-
if (runtimeResponse.status === 404) {
|
|
742
|
-
lastError = new ConfigurationError(`Avatar ${this.avatarId ?? "active"} not found for project ${this.projectId}`);
|
|
729
|
+
if (!response.ok || !response.data) {
|
|
730
|
+
const body = response.data;
|
|
731
|
+
const code = body?.error?.code ?? `HTTP_${response.status}`;
|
|
732
|
+
if (response.status === 401 || response.status === 403) {
|
|
733
|
+
throw new AuthenticationError(body?.error?.message ?? `Asiyst runtime avatar configuration was rejected (${code}).`);
|
|
743
734
|
}
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
});
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
}
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
}
|
|
780
|
-
|
|
781
|
-
throw lastError;
|
|
782
|
-
}
|
|
783
|
-
throw new ConfigurationError(`Failed to resolve avatar configuration for project ${this.projectId}`);
|
|
735
|
+
throw new NetworkError(body?.error?.message ?? `Asiyst runtime avatar configuration is unavailable (${code}).`);
|
|
736
|
+
}
|
|
737
|
+
const data = response.data;
|
|
738
|
+
if (data.success !== true || data.projectId !== this.projectId || typeof data.avatarId !== "string" || !data.config || typeof data.config !== "object" || Array.isArray(data.config)) {
|
|
739
|
+
throw new ConfigurationError("Asiyst returned an invalid runtime configuration response.");
|
|
740
|
+
}
|
|
741
|
+
const rawConfig = data.config;
|
|
742
|
+
const rawAvatar = data.avatar && typeof data.avatar === "object" ? data.avatar : {};
|
|
743
|
+
const manifest = data.manifest && typeof data.manifest === "object" ? data.manifest : {};
|
|
744
|
+
const modelFormat = [data.format, data.modelFormat, rawConfig.modelFormat, rawAvatar.modelFormat].find((format) => typeof format === "string");
|
|
745
|
+
if (modelFormat && modelFormat !== "fbx" && modelFormat !== "glb") {
|
|
746
|
+
throw new ConfigurationError(`Asiyst returned an unsupported avatar format: ${modelFormat}.`);
|
|
747
|
+
}
|
|
748
|
+
const assetUrl = typeof rawConfig.assetUrl === "string" ? rawConfig.assetUrl : typeof rawAvatar.assetUrl === "string" ? rawAvatar.assetUrl : typeof rawAvatar.modelUrl === "string" ? rawAvatar.modelUrl : typeof manifest.assetUrl === "string" ? manifest.assetUrl : void 0;
|
|
749
|
+
const animations = Array.isArray(rawConfig.animations) ? rawConfig.animations : Array.isArray(data.animations) ? data.animations : Array.isArray(rawAvatar.animations) ? rawAvatar.animations : [];
|
|
750
|
+
const revision = typeof data.configRevision === "string" ? data.configRevision : typeof data.publishedVersionId === "string" ? data.publishedVersionId : "0";
|
|
751
|
+
const version = Number.parseInt(revision, 10);
|
|
752
|
+
const config = normalizeProjectConfig({
|
|
753
|
+
...rawConfig,
|
|
754
|
+
avatarId: data.avatarId,
|
|
755
|
+
avatarName: typeof rawAvatar.name === "string" ? rawAvatar.name : rawConfig.avatarName,
|
|
756
|
+
assetUrl,
|
|
757
|
+
modelFormat,
|
|
758
|
+
publishedVersion: typeof data.publishedVersionId === "string" ? data.publishedVersionId : revision,
|
|
759
|
+
version: Number.isFinite(version) ? version : 0,
|
|
760
|
+
animations,
|
|
761
|
+
theme: rawConfig.theme ?? rawAvatar.theme,
|
|
762
|
+
personality: rawConfig.personality,
|
|
763
|
+
behavior: rawConfig.behavior ?? rawAvatar.behavior,
|
|
764
|
+
maxMessageChars: API_LIMITS.maxMessageChars
|
|
765
|
+
});
|
|
766
|
+
this.configMetadata = {
|
|
767
|
+
etag: response.headers?.get("etag") ?? void 0,
|
|
768
|
+
maxAgeMs: 0,
|
|
769
|
+
staleIfErrorMs: 0
|
|
770
|
+
};
|
|
771
|
+
return config;
|
|
784
772
|
}
|
|
785
773
|
async heartbeat(metadata) {
|
|
786
|
-
|
|
787
|
-
path:
|
|
774
|
+
const response = await this.runtimeRequest({
|
|
775
|
+
path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.runtimeHeartbeat),
|
|
788
776
|
method: "POST",
|
|
789
|
-
|
|
777
|
+
canonical: true,
|
|
790
778
|
body: {
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
environment: metadata.environment,
|
|
796
|
-
timestamp: metadata.timestamp
|
|
779
|
+
projectId: this.projectId,
|
|
780
|
+
publicKey: this.publicKey,
|
|
781
|
+
sdkVersion: metadata.sdkVersion,
|
|
782
|
+
environment: metadata.environment
|
|
797
783
|
}
|
|
798
784
|
}, "assistant:heartbeat");
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
path: "/api/v1/sdk/heartbeat",
|
|
802
|
-
method: "POST",
|
|
803
|
-
idempotent: true,
|
|
804
|
-
body: {
|
|
805
|
-
project_id: this.projectId,
|
|
806
|
-
public_key: this.publicKey,
|
|
807
|
-
sdk_version: SDK_VERSION,
|
|
808
|
-
origin: metadata.origin,
|
|
809
|
-
environment: metadata.environment,
|
|
810
|
-
timestamp: metadata.timestamp
|
|
811
|
-
}
|
|
812
|
-
}, "assistant:heartbeat");
|
|
813
|
-
}
|
|
814
|
-
const body = response.data && typeof response.data === "object" && !Array.isArray(response.data) ? response.data : void 0;
|
|
815
|
-
const rawStatus = body?.status ?? body?.connectionStatus ?? body?.verificationStatus ?? (body?.verified === true ? "verified" : void 0);
|
|
816
|
-
const verificationStatus = rawStatus === "connected" || rawStatus === "verified" || rawStatus === "inactive" || rawStatus === "not_detected" || rawStatus === "error" ? rawStatus : void 0;
|
|
817
|
-
const versionOutdated = body?.versionOutdated === true || body?.sdkVersionOutdated === true || rawStatus === "outdated";
|
|
785
|
+
const body = response.data;
|
|
786
|
+
const validResponse = body?.success === true && body.data?.connected === true && body.data.projectId === this.projectId && typeof body.data.versionOutdated === "boolean";
|
|
818
787
|
return {
|
|
819
|
-
ok: response.ok &&
|
|
820
|
-
status: response.status
|
|
821
|
-
verificationStatus,
|
|
822
|
-
versionOutdated
|
|
788
|
+
ok: response.ok && response.status === 202 && validResponse,
|
|
789
|
+
status: response.status
|
|
823
790
|
};
|
|
824
791
|
}
|
|
825
792
|
async registerInstallation(registration) {
|
|
826
|
-
|
|
827
|
-
path:
|
|
793
|
+
const response = await this.transport.request({
|
|
794
|
+
path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.installationRegister),
|
|
828
795
|
method: "POST",
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
796
|
+
headers: {
|
|
797
|
+
Accept: "application/json",
|
|
798
|
+
"Content-Type": "application/json",
|
|
799
|
+
"X-Asiyst-SDK-Version": registration.sdkVersion
|
|
800
|
+
},
|
|
801
|
+
body: {
|
|
802
|
+
projectId: registration.projectId,
|
|
803
|
+
publicKey: registration.publicKey,
|
|
804
|
+
installationId: registration.installationId,
|
|
805
|
+
origin: registration.origin,
|
|
806
|
+
environment: registration.environment,
|
|
807
|
+
sdkVersion: registration.sdkVersion
|
|
808
|
+
}
|
|
832
809
|
});
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
});
|
|
841
|
-
}
|
|
842
|
-
if (!response.ok) {
|
|
843
|
-
throw new NetworkError(`SDK installation registration failed (${response.status}).`);
|
|
810
|
+
const body = response.data;
|
|
811
|
+
if (!response.ok || body?.success !== true || body.data?.registered !== true || typeof body.data.installationId !== "string" || body.data.projectId !== registration.projectId || body.data.status === "revoked") {
|
|
812
|
+
const error = response.data && typeof response.data === "object" ? response.data.error : void 0;
|
|
813
|
+
if (response.status === 403 || body?.data?.status === "revoked") {
|
|
814
|
+
throw new AuthenticationError(error?.message ?? `SDK installation is not authorized (${error?.code ?? response.status}).`);
|
|
815
|
+
}
|
|
816
|
+
throw new NetworkError(error?.message ?? `SDK installation registration failed (${response.status}).`);
|
|
844
817
|
}
|
|
845
|
-
return
|
|
818
|
+
return body;
|
|
846
819
|
}
|
|
847
820
|
async requestTask(userText, pageUrl) {
|
|
848
|
-
|
|
849
|
-
path: "/tasks",
|
|
850
|
-
method: "POST",
|
|
851
|
-
body: {
|
|
852
|
-
projectId: this.projectId,
|
|
853
|
-
text: userText,
|
|
854
|
-
pageUrl
|
|
855
|
-
}
|
|
856
|
-
}, "assistant:conversation");
|
|
857
|
-
if (!response.ok || !response.data?.task?.id || !Array.isArray(response.data.task.steps)) {
|
|
858
|
-
throw new NetworkError("Task planning is unavailable");
|
|
859
|
-
}
|
|
860
|
-
return response.data.task;
|
|
821
|
+
throw new ConfigurationError("Cloud task planning is not defined by the approved SDK API contract.");
|
|
861
822
|
}
|
|
862
823
|
async fetchWorkflow(workflowId) {
|
|
863
|
-
|
|
864
|
-
path: `/workflows/${encodeURIComponent(workflowId)}`,
|
|
865
|
-
method: "GET",
|
|
866
|
-
idempotent: true
|
|
867
|
-
}, "assistant:conversation");
|
|
868
|
-
if (!response.ok || !response.data?.workflow?.id || !Array.isArray(response.data.workflow.steps)) {
|
|
869
|
-
throw new NetworkError("Workflow is unavailable");
|
|
870
|
-
}
|
|
871
|
-
return response.data.workflow;
|
|
824
|
+
throw new ConfigurationError("Cloud workflows are not defined by the approved SDK API contract.");
|
|
872
825
|
}
|
|
873
|
-
async sendConversationMessage(text, pageUrl) {
|
|
826
|
+
async sendConversationMessage(text, pageUrl, maxMessageChars = API_LIMITS.maxMessageChars) {
|
|
874
827
|
const trimmed = text.trim();
|
|
828
|
+
if (!trimmed) throw new ConfigurationError("Message cannot be empty.");
|
|
829
|
+
if (trimmed.length > maxMessageChars) {
|
|
830
|
+
throw new ConfigurationError(`Message exceeds the ${maxMessageChars}-character limit.`);
|
|
831
|
+
}
|
|
832
|
+
if (pageUrl.length > API_LIMITS.pageUrlMaxChars) {
|
|
833
|
+
throw new ConfigurationError("Page URL exceeds the supported length.");
|
|
834
|
+
}
|
|
835
|
+
const sessionId = this.sessionId ?? newRequestId();
|
|
836
|
+
if (sessionId.length < 16 || sessionId.length > 128 || !/^[A-Za-z0-9_-]+$/.test(sessionId)) {
|
|
837
|
+
throw new ConfigurationError("Visitor session ID must be an opaque 16-128 character identifier.");
|
|
838
|
+
}
|
|
875
839
|
const dedupeKey2 = `${this.conversationId ?? ""}:${trimmed}:${pageUrl}`;
|
|
876
840
|
const existing = this.inFlightConversations.get(dedupeKey2);
|
|
877
841
|
if (existing) {
|
|
@@ -879,19 +843,72 @@ var CloudClient = class {
|
|
|
879
843
|
}
|
|
880
844
|
const conversationPromise = (async () => {
|
|
881
845
|
try {
|
|
846
|
+
const requestConversationId = this.conversationId && isUuid(this.conversationId) ? this.conversationId : void 0;
|
|
882
847
|
const response = await this.runtimeRequest({
|
|
883
|
-
path:
|
|
848
|
+
path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.chat),
|
|
884
849
|
method: "POST",
|
|
885
|
-
body: {
|
|
886
|
-
|
|
850
|
+
body: {
|
|
851
|
+
projectId: this.projectId,
|
|
852
|
+
text: trimmed,
|
|
853
|
+
...requestConversationId ? { conversationId: requestConversationId } : {},
|
|
854
|
+
sessionId,
|
|
855
|
+
pageUrl
|
|
856
|
+
}
|
|
887
857
|
}, "assistant:conversation");
|
|
888
|
-
if (
|
|
889
|
-
|
|
890
|
-
|
|
858
|
+
if (response.ok && response.data?.success === true) {
|
|
859
|
+
const body = response.data;
|
|
860
|
+
const message = body.message && typeof body.message === "object" ? body.message : void 0;
|
|
861
|
+
const conversationId = body.conversationId;
|
|
862
|
+
const messageText = message?.text ?? body.response ?? body.answer;
|
|
863
|
+
if (body.success !== true || typeof conversationId !== "string" || typeof messageText !== "string" || !messageText.trim() || message && message.role !== "assistant") {
|
|
864
|
+
throw new NetworkError("Asiyst returned an unsupported conversation response.");
|
|
891
865
|
}
|
|
892
|
-
|
|
866
|
+
this.conversationId = conversationId;
|
|
867
|
+
const rawCitations = Array.isArray(body.sources) ? body.sources : [];
|
|
868
|
+
return {
|
|
869
|
+
requestId: typeof body.requestId === "string" ? body.requestId : void 0,
|
|
870
|
+
conversationId,
|
|
871
|
+
message: {
|
|
872
|
+
...typeof message?.id === "string" ? { id: message.id } : {},
|
|
873
|
+
role: "assistant",
|
|
874
|
+
text: messageText
|
|
875
|
+
},
|
|
876
|
+
citations: rawCitations.flatMap((citation) => {
|
|
877
|
+
if (!citation || typeof citation !== "object") return [];
|
|
878
|
+
const item = citation;
|
|
879
|
+
const sourceId = item.source_id ?? item.id;
|
|
880
|
+
if (typeof sourceId !== "string" || typeof item.title !== "string") return [];
|
|
881
|
+
return [{
|
|
882
|
+
sourceId,
|
|
883
|
+
title: item.title,
|
|
884
|
+
...typeof item.url === "string" ? { url: item.url } : {}
|
|
885
|
+
}];
|
|
886
|
+
}),
|
|
887
|
+
finishReason: void 0,
|
|
888
|
+
createdAt: void 0
|
|
889
|
+
};
|
|
890
|
+
}
|
|
891
|
+
const errorRecord = response.data && typeof response.data === "object" ? response.data.error : void 0;
|
|
892
|
+
const errorBody = errorRecord && typeof errorRecord === "object" ? errorRecord : void 0;
|
|
893
|
+
const code = typeof errorBody?.code === "string" ? errorBody.code : typeof errorRecord === "string" ? errorRecord : `HTTP_${response.status}`;
|
|
894
|
+
if (response.status === 401 || response.status === 403) {
|
|
895
|
+
throw new AuthenticationError("Asiyst runtime authorization was rejected.");
|
|
896
|
+
}
|
|
897
|
+
if (response.status === 429) {
|
|
898
|
+
throw new NetworkError("The assistant is rate limited. Wait before sending another message.");
|
|
893
899
|
}
|
|
894
|
-
|
|
900
|
+
if (response.status === 409) {
|
|
901
|
+
throw new NetworkError(`The conversation request conflicted (${code}); it was not retried.`);
|
|
902
|
+
}
|
|
903
|
+
if (response.status === 504 || code === "AI_PROVIDER_TIMEOUT") {
|
|
904
|
+
throw new NetworkError("The assistant timed out. The request was not retried to avoid duplicate work.");
|
|
905
|
+
}
|
|
906
|
+
if (code === "assistant_unavailable") {
|
|
907
|
+
throw new NetworkError("The assistant is temporarily unavailable.");
|
|
908
|
+
}
|
|
909
|
+
throw new NetworkError(
|
|
910
|
+
typeof errorBody?.message === "string" ? errorBody.message : typeof response.data?.message === "string" ? response.data.message : "Conversation service is unavailable."
|
|
911
|
+
);
|
|
895
912
|
} finally {
|
|
896
913
|
this.inFlightConversations.delete(dedupeKey2);
|
|
897
914
|
}
|
|
@@ -900,63 +917,16 @@ var CloudClient = class {
|
|
|
900
917
|
return conversationPromise;
|
|
901
918
|
}
|
|
902
919
|
async sendWebsiteMap(snapshot) {
|
|
903
|
-
|
|
920
|
+
throw new ConfigurationError("Website-map upload is not defined by the approved SDK API contract.");
|
|
904
921
|
}
|
|
905
922
|
async sendAnalytics(events) {
|
|
906
|
-
|
|
923
|
+
throw new ConfigurationError("Analytics upload is not defined by the approved SDK API contract.");
|
|
907
924
|
}
|
|
908
925
|
async sendTelemetryEvent(eventType, metadata = {}) {
|
|
909
|
-
|
|
910
|
-
const origin = typeof window !== "undefined" ? window.location.origin : void 0;
|
|
911
|
-
const installationId = this.runtimeAuth ? this.runtimeAuth.options?.installationId : void 0;
|
|
912
|
-
const sanitizedMeta = {
|
|
913
|
-
sdkVersion: SDK_VERSION
|
|
914
|
-
};
|
|
915
|
-
for (const [key, val] of Object.entries(metadata)) {
|
|
916
|
-
if (/(token|secret|cookie|session|api.?key|password|bearer|authorization)/i.test(key)) {
|
|
917
|
-
continue;
|
|
918
|
-
}
|
|
919
|
-
if (typeof val === "string") {
|
|
920
|
-
sanitizedMeta[key] = sanitizeText(val, 512);
|
|
921
|
-
} else if (typeof val === "number" || typeof val === "boolean") {
|
|
922
|
-
sanitizedMeta[key] = val;
|
|
923
|
-
} else if (val && typeof val === "object" && !Array.isArray(val)) {
|
|
924
|
-
sanitizedMeta[key] = val;
|
|
925
|
-
}
|
|
926
|
-
}
|
|
927
|
-
const payload = {
|
|
928
|
-
projectId: this.projectId,
|
|
929
|
-
publicKey: this.publicKey,
|
|
930
|
-
eventType,
|
|
931
|
-
installationId,
|
|
932
|
-
origin,
|
|
933
|
-
metadata: sanitizedMeta
|
|
934
|
-
};
|
|
935
|
-
const baseUrl = this.getApiBaseUrl();
|
|
936
|
-
const targetUrl = baseUrl.includes("localhost") || baseUrl.includes("127.0.0.1") ? `${baseUrl.replace(/\/functions\/v1.*$/, "").replace(/\/api\/v1.*$/, "")}/api/v1/events` : "https://asiyst.com/api/v1/events";
|
|
937
|
-
await fetch(targetUrl, {
|
|
938
|
-
method: "POST",
|
|
939
|
-
headers: {
|
|
940
|
-
"Content-Type": "application/json",
|
|
941
|
-
Accept: "application/json",
|
|
942
|
-
"x-asiyst-public-key": this.publicKey
|
|
943
|
-
},
|
|
944
|
-
body: JSON.stringify(payload)
|
|
945
|
-
});
|
|
946
|
-
} catch {
|
|
947
|
-
}
|
|
926
|
+
throw new ConfigurationError("Telemetry upload is not defined by the approved SDK API contract.");
|
|
948
927
|
}
|
|
949
928
|
async sendTaskUpdate(taskId, status, stepId) {
|
|
950
|
-
|
|
951
|
-
status,
|
|
952
|
-
stepId
|
|
953
|
-
});
|
|
954
|
-
}
|
|
955
|
-
async safePost(path, body) {
|
|
956
|
-
try {
|
|
957
|
-
await this.runtimeRequest({ path, method: "POST", body, idempotent: true }, "assistant:telemetry");
|
|
958
|
-
} catch {
|
|
959
|
-
}
|
|
929
|
+
throw new ConfigurationError("Cloud task updates are not defined by the approved SDK API contract.");
|
|
960
930
|
}
|
|
961
931
|
async runtimeRequest(request, capability = "assistant:config") {
|
|
962
932
|
const fullRequest = {
|
|
@@ -965,14 +935,32 @@ var CloudClient = class {
|
|
|
965
935
|
conversationId: request.conversationId ?? this.conversationId
|
|
966
936
|
};
|
|
967
937
|
if (!this.runtimeAuth) {
|
|
938
|
+
if (capability === "assistant:conversation" || capability === "assistant:heartbeat") {
|
|
939
|
+
throw new AuthenticationError("AI request authorization failed because no runtime token is available.");
|
|
940
|
+
}
|
|
968
941
|
return this.transport.request(fullRequest);
|
|
969
942
|
}
|
|
970
|
-
let token = await this.getAuthToken(
|
|
971
|
-
|
|
943
|
+
let token = await this.getAuthToken();
|
|
944
|
+
const withToken = (value) => {
|
|
945
|
+
const headers = new Headers({
|
|
946
|
+
Accept: "application/json",
|
|
947
|
+
"Content-Type": "application/json"
|
|
948
|
+
});
|
|
949
|
+
if (fullRequest.headers) {
|
|
950
|
+
new Headers(fullRequest.headers).forEach((headerValue, key) => headers.set(key, headerValue));
|
|
951
|
+
}
|
|
952
|
+
if (value) headers.set("Authorization", `Bearer ${value}`);
|
|
953
|
+
return this.transport.request({
|
|
954
|
+
...fullRequest,
|
|
955
|
+
headers,
|
|
956
|
+
canonical: true
|
|
957
|
+
});
|
|
958
|
+
};
|
|
959
|
+
let response = await withToken(token);
|
|
972
960
|
if (response.status === 401) {
|
|
973
961
|
if (!this.tokenRefreshPromise) {
|
|
974
962
|
this.runtimeAuth.invalidate();
|
|
975
|
-
this.tokenRefreshPromise = this.runtimeAuth.getToken(
|
|
963
|
+
this.tokenRefreshPromise = this.runtimeAuth.getToken().then((newToken) => {
|
|
976
964
|
this.activeToken = newToken;
|
|
977
965
|
return newToken;
|
|
978
966
|
}).finally(() => {
|
|
@@ -982,7 +970,7 @@ var CloudClient = class {
|
|
|
982
970
|
});
|
|
983
971
|
}
|
|
984
972
|
token = await this.tokenRefreshPromise ?? this.activeToken;
|
|
985
|
-
response = await
|
|
973
|
+
response = await withToken(token);
|
|
986
974
|
}
|
|
987
975
|
return response;
|
|
988
976
|
}
|
|
@@ -1049,7 +1037,8 @@ var ConfigCache = class {
|
|
|
1049
1037
|
if (parsed.schemaVersion !== CONFIG_SCHEMA_VERSION || parsed.projectId !== projectId) {
|
|
1050
1038
|
return null;
|
|
1051
1039
|
}
|
|
1052
|
-
|
|
1040
|
+
const maxAgeMs = parsed.maxAgeMs ?? CONFIG_CACHE_TTL_MS;
|
|
1041
|
+
if (!ignoreTtl && Date.now() - parsed.fetchedAt > maxAgeMs) {
|
|
1053
1042
|
return null;
|
|
1054
1043
|
}
|
|
1055
1044
|
return normalizeProjectConfig(parsed.config);
|
|
@@ -1079,6 +1068,8 @@ var ConfigCache = class {
|
|
|
1079
1068
|
fetchedAt: Date.now(),
|
|
1080
1069
|
etag: meta?.etag,
|
|
1081
1070
|
revision: meta?.revision ?? config.version,
|
|
1071
|
+
maxAgeMs: meta?.maxAgeMs,
|
|
1072
|
+
staleIfErrorMs: meta?.staleIfErrorMs,
|
|
1082
1073
|
config
|
|
1083
1074
|
};
|
|
1084
1075
|
this.storage.write("config", JSON.stringify(envelope));
|
|
@@ -1120,19 +1111,26 @@ var ConfigManager = class {
|
|
|
1120
1111
|
async executeRefresh(_options) {
|
|
1121
1112
|
const prev = this.current;
|
|
1122
1113
|
try {
|
|
1123
|
-
const
|
|
1124
|
-
const normalized = normalizeProjectConfig(
|
|
1114
|
+
const cached = this.cache.getEnvelope(this.options.projectId);
|
|
1115
|
+
const normalized = normalizeProjectConfig(await this.cloud.fetchConfig(cached?.etag, cached?.config));
|
|
1116
|
+
const receivedMetadata = this.cloud.getConfigMetadata?.() ?? {};
|
|
1117
|
+
const metadata = {
|
|
1118
|
+
...receivedMetadata,
|
|
1119
|
+
maxAgeMs: receivedMetadata.maxAgeMs ?? cached?.maxAgeMs,
|
|
1120
|
+
staleIfErrorMs: receivedMetadata.staleIfErrorMs ?? cached?.staleIfErrorMs
|
|
1121
|
+
};
|
|
1125
1122
|
this.current = normalized;
|
|
1126
|
-
this.cache.write(this.options.projectId, normalized);
|
|
1123
|
+
this.cache.write(this.options.projectId, normalized, metadata);
|
|
1127
1124
|
const hasChanged = prev.version !== normalized.version || prev.avatarName !== normalized.avatarName || prev.position !== normalized.position || prev.size !== normalized.size || prev.assetUrl !== normalized.assetUrl || prev.thumbnailUrl !== normalized.thumbnailUrl || JSON.stringify(prev.theme) !== JSON.stringify(normalized.theme) || JSON.stringify(prev.animations) !== JSON.stringify(normalized.animations);
|
|
1128
1125
|
if (hasChanged && this.onConfigUpdated) {
|
|
1129
1126
|
this.onConfigUpdated(normalized, prev);
|
|
1130
1127
|
}
|
|
1131
1128
|
return this.current;
|
|
1132
1129
|
} catch (error) {
|
|
1133
|
-
const
|
|
1134
|
-
|
|
1135
|
-
|
|
1130
|
+
const cached = this.cache.getEnvelope(this.options.projectId);
|
|
1131
|
+
const staleIfErrorMs = cached?.staleIfErrorMs ?? API_LIMITS.configStaleIfErrorMs;
|
|
1132
|
+
if (cached && staleIfErrorMs > 0 && Date.now() - cached.fetchedAt <= staleIfErrorMs) {
|
|
1133
|
+
this.current = normalizeProjectConfig(cached.config);
|
|
1136
1134
|
}
|
|
1137
1135
|
this.events.emit("asiyst:error", {
|
|
1138
1136
|
code: "config_refresh_failed",
|
|
@@ -1809,7 +1807,7 @@ var CHUNK_TYPE_JSON = 1313821514;
|
|
|
1809
1807
|
var CHUNK_TYPE_BIN = 5130562;
|
|
1810
1808
|
var AssetLoader = class {
|
|
1811
1809
|
constructor() {
|
|
1812
|
-
this.
|
|
1810
|
+
this.inFlightControllers = /* @__PURE__ */ new Set();
|
|
1813
1811
|
this.createdObjectUrls = [];
|
|
1814
1812
|
this.inFlightLoads = /* @__PURE__ */ new Map();
|
|
1815
1813
|
this.cachedAssets = /* @__PURE__ */ new Map();
|
|
@@ -1819,31 +1817,42 @@ var AssetLoader = class {
|
|
|
1819
1817
|
if (!sanitizedUrl) {
|
|
1820
1818
|
throw new Error("Asset URL is required");
|
|
1821
1819
|
}
|
|
1822
|
-
|
|
1820
|
+
let parsedUrl;
|
|
1821
|
+
try {
|
|
1822
|
+
parsedUrl = new URL(sanitizedUrl, typeof location === "undefined" ? void 0 : location.href);
|
|
1823
|
+
} catch {
|
|
1824
|
+
throw new Error("Avatar asset URL is invalid");
|
|
1825
|
+
}
|
|
1826
|
+
if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:" || parsedUrl.username || parsedUrl.password) {
|
|
1827
|
+
throw new Error("Avatar asset URL must use HTTP or HTTPS without embedded credentials");
|
|
1828
|
+
}
|
|
1829
|
+
const cacheKey = `${sanitizedUrl}\0${options?.integrity ?? ""}\0${options?.expectedFormat ?? ""}`;
|
|
1830
|
+
const cached = this.cachedAssets.get(cacheKey);
|
|
1823
1831
|
if (cached) {
|
|
1824
1832
|
return cached;
|
|
1825
1833
|
}
|
|
1826
|
-
const inFlight = this.inFlightLoads.get(
|
|
1834
|
+
const inFlight = this.inFlightLoads.get(cacheKey);
|
|
1827
1835
|
if (inFlight) {
|
|
1828
1836
|
return inFlight;
|
|
1829
1837
|
}
|
|
1830
1838
|
const loadPromise = this.performLoad(sanitizedUrl, options);
|
|
1831
|
-
this.inFlightLoads.set(
|
|
1839
|
+
this.inFlightLoads.set(cacheKey, loadPromise);
|
|
1832
1840
|
try {
|
|
1833
1841
|
const asset = await loadPromise;
|
|
1834
|
-
this.cachedAssets.set(
|
|
1842
|
+
this.cachedAssets.set(cacheKey, asset);
|
|
1835
1843
|
return asset;
|
|
1836
1844
|
} finally {
|
|
1837
|
-
this.inFlightLoads.delete(
|
|
1845
|
+
this.inFlightLoads.delete(cacheKey);
|
|
1838
1846
|
}
|
|
1839
1847
|
}
|
|
1840
1848
|
async performLoad(sanitizedUrl, options) {
|
|
1841
1849
|
const startTime = Date.now();
|
|
1842
|
-
|
|
1843
|
-
|
|
1850
|
+
const controller = new AbortController();
|
|
1851
|
+
this.inFlightControllers.add(controller);
|
|
1852
|
+
const abortSignal = options?.signal ? anySignal([controller.signal, options.signal]) : controller.signal;
|
|
1844
1853
|
const timeoutMs = options?.timeoutMs ?? 6e4;
|
|
1845
1854
|
const timeoutId = setTimeout(() => {
|
|
1846
|
-
|
|
1855
|
+
controller.abort();
|
|
1847
1856
|
}, timeoutMs);
|
|
1848
1857
|
try {
|
|
1849
1858
|
const cleanPath = (sanitizedUrl.split("?")[0] ?? "").toLowerCase();
|
|
@@ -1917,12 +1926,25 @@ var AssetLoader = class {
|
|
|
1917
1926
|
if (arrayBuffer.byteLength < 12) {
|
|
1918
1927
|
throw new Error("Avatar asset payload is too small to be a valid 3D container");
|
|
1919
1928
|
}
|
|
1929
|
+
if (options?.integrity) {
|
|
1930
|
+
await verifyIntegrity(arrayBuffer, options.integrity);
|
|
1931
|
+
}
|
|
1920
1932
|
const headerBytes = new Uint8Array(arrayBuffer, 0, Math.min(256, arrayBuffer.byteLength));
|
|
1921
1933
|
const headerStr = new TextDecoder("utf-8", { fatal: false }).decode(headerBytes).trim();
|
|
1922
1934
|
if (/^<!DOCTYPE\s+html/i.test(headerStr) || /^<html/i.test(headerStr)) {
|
|
1923
1935
|
throw new Error(`Avatar asset payload contains HTML error page instead of binary 3D container from ${sanitizedUrl}`);
|
|
1924
1936
|
}
|
|
1925
|
-
|
|
1937
|
+
const hasFbxSignature = this.isFbxBuffer(arrayBuffer);
|
|
1938
|
+
const hasGlbSignature = this.isGlbBuffer(arrayBuffer);
|
|
1939
|
+
const isFbx = hasFbxSignature || !hasGlbSignature && isFbxExtension;
|
|
1940
|
+
const isGlb = hasGlbSignature || !hasFbxSignature && isGlbExtension;
|
|
1941
|
+
if (isFbx && isGlb) {
|
|
1942
|
+
throw new Error("Avatar asset format is ambiguous");
|
|
1943
|
+
}
|
|
1944
|
+
if (isFbx) {
|
|
1945
|
+
if (options?.expectedFormat && options.expectedFormat !== "fbx") {
|
|
1946
|
+
throw new Error(`Avatar asset format mismatch: expected ${options.expectedFormat}, received fbx`);
|
|
1947
|
+
}
|
|
1926
1948
|
const fbxHeader = this.parseFbxHeader(arrayBuffer);
|
|
1927
1949
|
const resourcePath = sanitizedUrl.includes("/") ? sanitizedUrl.substring(0, sanitizedUrl.lastIndexOf("/") + 1) : "";
|
|
1928
1950
|
return {
|
|
@@ -1935,6 +1957,12 @@ var AssetLoader = class {
|
|
|
1935
1957
|
durationMs: Date.now() - startTime
|
|
1936
1958
|
};
|
|
1937
1959
|
}
|
|
1960
|
+
if (!isGlb) {
|
|
1961
|
+
throw new Error("Avatar asset format is unsupported; expected FBX or GLB");
|
|
1962
|
+
}
|
|
1963
|
+
if (options?.expectedFormat && options.expectedFormat !== "glb") {
|
|
1964
|
+
throw new Error(`Avatar asset format mismatch: expected ${options.expectedFormat}, received glb`);
|
|
1965
|
+
}
|
|
1938
1966
|
const parsedGlb = this.parseGlb(arrayBuffer);
|
|
1939
1967
|
return {
|
|
1940
1968
|
format: "glb",
|
|
@@ -1947,7 +1975,7 @@ var AssetLoader = class {
|
|
|
1947
1975
|
};
|
|
1948
1976
|
} finally {
|
|
1949
1977
|
clearTimeout(timeoutId);
|
|
1950
|
-
this.
|
|
1978
|
+
this.inFlightControllers.delete(controller);
|
|
1951
1979
|
}
|
|
1952
1980
|
}
|
|
1953
1981
|
isFbxBuffer(buffer) {
|
|
@@ -2163,10 +2191,8 @@ var AssetLoader = class {
|
|
|
2163
2191
|
};
|
|
2164
2192
|
}
|
|
2165
2193
|
destroy() {
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
this.inFlightController = null;
|
|
2169
|
-
}
|
|
2194
|
+
for (const controller of this.inFlightControllers) controller.abort();
|
|
2195
|
+
this.inFlightControllers.clear();
|
|
2170
2196
|
this.inFlightLoads.clear();
|
|
2171
2197
|
this.cachedAssets.clear();
|
|
2172
2198
|
if (typeof URL !== "undefined" && typeof URL.revokeObjectURL === "function") {
|
|
@@ -2180,6 +2206,20 @@ var AssetLoader = class {
|
|
|
2180
2206
|
this.createdObjectUrls.length = 0;
|
|
2181
2207
|
}
|
|
2182
2208
|
};
|
|
2209
|
+
async function verifyIntegrity(buffer, integrity) {
|
|
2210
|
+
const [algorithm, expected] = integrity.split("-", 2);
|
|
2211
|
+
if (algorithm !== "sha256" || !expected) {
|
|
2212
|
+
throw new Error("Avatar asset integrity metadata is invalid");
|
|
2213
|
+
}
|
|
2214
|
+
const cryptoApi = globalThis.crypto;
|
|
2215
|
+
if (!cryptoApi?.subtle) return;
|
|
2216
|
+
const digest = new Uint8Array(await cryptoApi.subtle.digest("SHA-256", buffer));
|
|
2217
|
+
let binary = "";
|
|
2218
|
+
for (const byte of digest) binary += String.fromCharCode(byte);
|
|
2219
|
+
if (btoa(binary) !== expected) {
|
|
2220
|
+
throw new Error("Avatar asset integrity verification failed");
|
|
2221
|
+
}
|
|
2222
|
+
}
|
|
2183
2223
|
function anySignal(signals) {
|
|
2184
2224
|
const controller = new AbortController();
|
|
2185
2225
|
for (const sig of signals) {
|
|
@@ -2420,47 +2460,6 @@ var FbxRenderer = class {
|
|
|
2420
2460
|
if (this.playAnimation(pose)) {
|
|
2421
2461
|
return;
|
|
2422
2462
|
}
|
|
2423
|
-
if (this.mixer && this.allAnimations.length > 0) {
|
|
2424
|
-
let targetClip;
|
|
2425
|
-
if (pose === "speak") {
|
|
2426
|
-
targetClip = this.allAnimations.find(
|
|
2427
|
-
(c) => c.name.toLowerCase().includes("talk") || c.name.toLowerCase().includes("speak")
|
|
2428
|
-
);
|
|
2429
|
-
} else if (pose === "think") {
|
|
2430
|
-
targetClip = this.allAnimations.find(
|
|
2431
|
-
(c) => c.name.toLowerCase().includes("think")
|
|
2432
|
-
);
|
|
2433
|
-
} else if (pose === "walk") {
|
|
2434
|
-
targetClip = this.allAnimations.find(
|
|
2435
|
-
(c) => c.name.toLowerCase().includes("walk") || c.name.toLowerCase().includes("run")
|
|
2436
|
-
);
|
|
2437
|
-
} else if (pose === "point") {
|
|
2438
|
-
targetClip = this.allAnimations.find(
|
|
2439
|
-
(c) => c.name.toLowerCase().includes("point")
|
|
2440
|
-
);
|
|
2441
|
-
} else if (pose === "celebrate") {
|
|
2442
|
-
targetClip = this.allAnimations.find(
|
|
2443
|
-
(c) => c.name.toLowerCase().includes("celebrat") || c.name.toLowerCase().includes("wave") || c.name.toLowerCase().includes("cheer") || c.name.toLowerCase().includes("jump")
|
|
2444
|
-
);
|
|
2445
|
-
} else {
|
|
2446
|
-
targetClip = this.allAnimations.find((c) => c.name.toLowerCase().includes("idle")) || this.animationMetadataList[0]?.clip || this.allAnimations[0];
|
|
2447
|
-
}
|
|
2448
|
-
if (targetClip) {
|
|
2449
|
-
const newAction = this.mixer.clipAction(targetClip);
|
|
2450
|
-
if (newAction !== this.currentAction) {
|
|
2451
|
-
newAction.reset().fadeIn(0.25).play();
|
|
2452
|
-
if (this.currentAction) {
|
|
2453
|
-
this.currentAction.fadeOut(0.25);
|
|
2454
|
-
}
|
|
2455
|
-
this.currentAction = newAction;
|
|
2456
|
-
return;
|
|
2457
|
-
} else if (!this.currentAction?.isRunning()) {
|
|
2458
|
-
this.currentAction?.play();
|
|
2459
|
-
return;
|
|
2460
|
-
}
|
|
2461
|
-
return;
|
|
2462
|
-
}
|
|
2463
|
-
}
|
|
2464
2463
|
if (!this.modelRoot) return;
|
|
2465
2464
|
this.modelRoot.scale.setScalar(this.baseScale);
|
|
2466
2465
|
switch (pose) {
|
|
@@ -2505,13 +2504,13 @@ var FbxRenderer = class {
|
|
|
2505
2504
|
return true;
|
|
2506
2505
|
}
|
|
2507
2506
|
const idleByName = this.animationMetadataList.find(
|
|
2508
|
-
(m) => m.name.toLowerCase()
|
|
2507
|
+
(m) => m.name.toLowerCase() === "idle" || m.clipName?.toLowerCase() === "idle"
|
|
2509
2508
|
);
|
|
2510
2509
|
if (idleByName && this.playAnimation(idleByName.id || idleByName.name)) {
|
|
2511
2510
|
return true;
|
|
2512
2511
|
}
|
|
2513
2512
|
const embeddedIdle = this.allAnimations.find(
|
|
2514
|
-
(c) => c.name.toLowerCase()
|
|
2513
|
+
(c) => c.name.toLowerCase() === "idle"
|
|
2515
2514
|
);
|
|
2516
2515
|
if (embeddedIdle) {
|
|
2517
2516
|
const action = this.mixer.clipAction(embeddedIdle);
|
|
@@ -2522,22 +2521,6 @@ var FbxRenderer = class {
|
|
|
2522
2521
|
}
|
|
2523
2522
|
return true;
|
|
2524
2523
|
}
|
|
2525
|
-
if (this.animationMetadataList.length > 0) {
|
|
2526
|
-
const firstMeta = this.animationMetadataList[0];
|
|
2527
|
-
if (this.playAnimation(firstMeta.id || firstMeta.name)) {
|
|
2528
|
-
return true;
|
|
2529
|
-
}
|
|
2530
|
-
}
|
|
2531
|
-
if (this.allAnimations.length > 0) {
|
|
2532
|
-
const firstClip = this.allAnimations[0];
|
|
2533
|
-
const action = this.mixer.clipAction(firstClip);
|
|
2534
|
-
if (this.currentAction !== action) {
|
|
2535
|
-
action.reset().fadeIn(0.25).play();
|
|
2536
|
-
if (this.currentAction) this.currentAction.fadeOut(0.25);
|
|
2537
|
-
this.currentAction = action;
|
|
2538
|
-
}
|
|
2539
|
-
return true;
|
|
2540
|
-
}
|
|
2541
2524
|
return false;
|
|
2542
2525
|
}
|
|
2543
2526
|
async loadExternalAnimations(animations, targetAnimationName) {
|
|
@@ -2555,7 +2538,7 @@ var FbxRenderer = class {
|
|
|
2555
2538
|
await Promise.allSettled(
|
|
2556
2539
|
pending.map(async (anim) => {
|
|
2557
2540
|
try {
|
|
2558
|
-
const loaded = await this.assetLoader.load(anim.assetUrl);
|
|
2541
|
+
const loaded = await this.assetLoader.load(anim.assetUrl, { integrity: anim.integrity });
|
|
2559
2542
|
let extractedClips = [];
|
|
2560
2543
|
if (loaded.format === "fbx") {
|
|
2561
2544
|
const loader = new FBXLoader();
|
|
@@ -2681,13 +2664,13 @@ var FbxRenderer = class {
|
|
|
2681
2664
|
clip = this.allAnimations.find((c) => c.name.toLowerCase() === query);
|
|
2682
2665
|
}
|
|
2683
2666
|
if (!clip) {
|
|
2684
|
-
clip = this.allAnimations.find((c) => c.name.toLowerCase()
|
|
2667
|
+
clip = this.allAnimations.find((c) => c.name.toLowerCase() === query);
|
|
2685
2668
|
}
|
|
2686
2669
|
if (!clip) {
|
|
2687
2670
|
return false;
|
|
2688
2671
|
}
|
|
2689
2672
|
const action = this.mixer.clipAction(clip);
|
|
2690
|
-
const effectiveLoop = loopMode || matched?.loopMode || "
|
|
2673
|
+
const effectiveLoop = (loopMode || matched?.loopMode || "loop").toLowerCase();
|
|
2691
2674
|
if (effectiveLoop === "once") {
|
|
2692
2675
|
action.setLoop(THREE.LoopOnce, 1);
|
|
2693
2676
|
action.clampWhenFinished = true;
|
|
@@ -3260,7 +3243,11 @@ var CssAvatarRenderer = class {
|
|
|
3260
3243
|
}
|
|
3261
3244
|
try {
|
|
3262
3245
|
this.metricsTracker?.record("assetRequestStart");
|
|
3263
|
-
const asset = await this.assetLoader.load(assetUrl, {
|
|
3246
|
+
const asset = await this.assetLoader.load(assetUrl, {
|
|
3247
|
+
timeoutMs: 6e4,
|
|
3248
|
+
integrity: config.assetIntegrity,
|
|
3249
|
+
expectedFormat: config.assetUrl ? config.modelFormat : void 0
|
|
3250
|
+
});
|
|
3264
3251
|
this.metricsTracker?.record("assetDownloadComplete");
|
|
3265
3252
|
const byteSize = asset.buffer?.byteLength ?? asset.bin?.byteLength ?? asset.size;
|
|
3266
3253
|
this.metricsTracker?.setAssetInfo({
|
|
@@ -3361,7 +3348,10 @@ var CssAvatarRenderer = class {
|
|
|
3361
3348
|
const thumb = typeof asset.manifest.thumbnailUrl === "string" ? asset.manifest.thumbnailUrl : void 0;
|
|
3362
3349
|
const modelUrl = typeof asset.manifest.assetUrl === "string" ? asset.manifest.assetUrl : typeof asset.manifest.modelUrl === "string" ? asset.manifest.modelUrl : void 0;
|
|
3363
3350
|
if (modelUrl) {
|
|
3364
|
-
const subAsset = await this.assetLoader.load(modelUrl, {
|
|
3351
|
+
const subAsset = await this.assetLoader.load(modelUrl, {
|
|
3352
|
+
timeoutMs: 6e4,
|
|
3353
|
+
expectedFormat: config.modelFormat
|
|
3354
|
+
});
|
|
3365
3355
|
await this.renderLoadedAsset(subAsset, config);
|
|
3366
3356
|
} else if (thumb) {
|
|
3367
3357
|
this.viewport.replaceChildren();
|
|
@@ -4155,11 +4145,10 @@ function transition(from, to) {
|
|
|
4155
4145
|
|
|
4156
4146
|
// src/task/TaskEngine.ts
|
|
4157
4147
|
var TaskEngine = class {
|
|
4158
|
-
constructor(interaction, events, analytics
|
|
4148
|
+
constructor(interaction, events, analytics) {
|
|
4159
4149
|
this.interaction = interaction;
|
|
4160
4150
|
this.events = events;
|
|
4161
4151
|
this.analytics = analytics;
|
|
4162
|
-
this.cloud = cloud;
|
|
4163
4152
|
this.status = TaskStatus.Idle;
|
|
4164
4153
|
this.abort = false;
|
|
4165
4154
|
}
|
|
@@ -4175,7 +4164,6 @@ var TaskEngine = class {
|
|
|
4175
4164
|
this.events.emit("asiyst:task:started", { taskId: task.id });
|
|
4176
4165
|
this.analytics.track("task_started", { taskId: task.id });
|
|
4177
4166
|
this.analytics.track("guide_started", { taskId: task.id });
|
|
4178
|
-
void this.cloud.sendTaskUpdate(task.id, this.status);
|
|
4179
4167
|
try {
|
|
4180
4168
|
for (const [index, step] of task.steps.entries()) {
|
|
4181
4169
|
if (this.abort) {
|
|
@@ -4210,13 +4198,11 @@ var TaskEngine = class {
|
|
|
4210
4198
|
}
|
|
4211
4199
|
this.move(TaskStatus.StepCompleted);
|
|
4212
4200
|
this.events.emit("asiyst:task:step-completed", { taskId: task.id, stepId: step.id });
|
|
4213
|
-
void this.cloud.sendTaskUpdate(task.id, this.status, step.id);
|
|
4214
4201
|
}
|
|
4215
4202
|
this.move(TaskStatus.TaskCompleted);
|
|
4216
4203
|
this.events.emit("asiyst:task:completed", { taskId: task.id });
|
|
4217
4204
|
this.analytics.track("task_completed", { taskId: task.id });
|
|
4218
4205
|
this.analytics.track("guide_completed", { taskId: task.id });
|
|
4219
|
-
void this.cloud.sendTaskUpdate(task.id, this.status);
|
|
4220
4206
|
this.move(TaskStatus.Idle);
|
|
4221
4207
|
return TaskStatus.TaskCompleted;
|
|
4222
4208
|
} catch (error) {
|
|
@@ -4291,6 +4277,7 @@ var ConversationPanel = class {
|
|
|
4291
4277
|
this.onToggle = onToggle;
|
|
4292
4278
|
this.conversationId = "";
|
|
4293
4279
|
this.openState = false;
|
|
4280
|
+
this.submitting = false;
|
|
4294
4281
|
const doc = root.ownerDocument;
|
|
4295
4282
|
this.style = doc.createElement("style");
|
|
4296
4283
|
this.style.textContent = `
|
|
@@ -4388,6 +4375,9 @@ var ConversationPanel = class {
|
|
|
4388
4375
|
getConversationId() {
|
|
4389
4376
|
return this.conversationId;
|
|
4390
4377
|
}
|
|
4378
|
+
setConversationId(conversationId) {
|
|
4379
|
+
this.conversationId = conversationId;
|
|
4380
|
+
}
|
|
4391
4381
|
open() {
|
|
4392
4382
|
if (!this.conversationId) {
|
|
4393
4383
|
this.conversationId = `conv_${Date.now().toString(36)}`;
|
|
@@ -4402,22 +4392,51 @@ var ConversationPanel = class {
|
|
|
4402
4392
|
this.panel.hidden = true;
|
|
4403
4393
|
this.onToggle(false);
|
|
4404
4394
|
}
|
|
4405
|
-
append(role, text) {
|
|
4395
|
+
append(role, text, citations = []) {
|
|
4406
4396
|
const item = this.log.ownerDocument.createElement("div");
|
|
4407
4397
|
item.className = "asiyst-msg";
|
|
4408
4398
|
item.setAttribute("data-role", role);
|
|
4409
4399
|
renderSafeText(item, text);
|
|
4400
|
+
for (const citation of citations) {
|
|
4401
|
+
if (!citation.url) continue;
|
|
4402
|
+
let url;
|
|
4403
|
+
try {
|
|
4404
|
+
url = new URL(citation.url);
|
|
4405
|
+
} catch {
|
|
4406
|
+
continue;
|
|
4407
|
+
}
|
|
4408
|
+
if (url.protocol !== "https:") continue;
|
|
4409
|
+
const link = this.log.ownerDocument.createElement("a");
|
|
4410
|
+
link.href = url.href;
|
|
4411
|
+
link.rel = "noopener noreferrer";
|
|
4412
|
+
link.target = "_blank";
|
|
4413
|
+
link.textContent = sanitizeText(citation.title, 160);
|
|
4414
|
+
const wrapper = this.log.ownerDocument.createElement("div");
|
|
4415
|
+
wrapper.appendChild(link);
|
|
4416
|
+
item.appendChild(wrapper);
|
|
4417
|
+
}
|
|
4410
4418
|
this.log.appendChild(item);
|
|
4411
4419
|
this.log.scrollTop = this.log.scrollHeight;
|
|
4412
4420
|
}
|
|
4413
4421
|
async submit() {
|
|
4422
|
+
if (this.submitting) return;
|
|
4414
4423
|
const text = sanitizeText(this.input.value);
|
|
4415
4424
|
if (!text) {
|
|
4416
4425
|
return;
|
|
4417
4426
|
}
|
|
4427
|
+
this.submitting = true;
|
|
4428
|
+
this.input.disabled = true;
|
|
4429
|
+
this.form.querySelector("button")?.setAttribute("disabled", "true");
|
|
4418
4430
|
this.input.value = "";
|
|
4419
4431
|
this.append("user", text);
|
|
4420
|
-
|
|
4432
|
+
try {
|
|
4433
|
+
await this.onSubmit(text);
|
|
4434
|
+
} finally {
|
|
4435
|
+
this.submitting = false;
|
|
4436
|
+
this.input.disabled = false;
|
|
4437
|
+
this.form.querySelector("button")?.removeAttribute("disabled");
|
|
4438
|
+
this.input.focus();
|
|
4439
|
+
}
|
|
4421
4440
|
}
|
|
4422
4441
|
destroy() {
|
|
4423
4442
|
if (this.keydownListener) {
|
|
@@ -4480,19 +4499,15 @@ function loadOrCreateInstallationId(projectId) {
|
|
|
4480
4499
|
}
|
|
4481
4500
|
|
|
4482
4501
|
// src/communication/RuntimeAuth.ts
|
|
4483
|
-
var RUNTIME_AUDIENCE = "asiyst-sdk-runtime";
|
|
4484
|
-
var RUNTIME_CAPABILITIES = [
|
|
4485
|
-
"assistant:config",
|
|
4486
|
-
"assistant:conversation",
|
|
4487
|
-
"assistant:telemetry",
|
|
4488
|
-
"assistant:heartbeat"
|
|
4489
|
-
];
|
|
4490
4502
|
var RuntimeAuth = class {
|
|
4491
4503
|
constructor(options) {
|
|
4492
4504
|
this.options = options;
|
|
4493
4505
|
}
|
|
4494
|
-
|
|
4495
|
-
|
|
4506
|
+
setInstallationId(installationId) {
|
|
4507
|
+
this.options.installationId = installationId;
|
|
4508
|
+
}
|
|
4509
|
+
async getToken() {
|
|
4510
|
+
if (this.token && this.isUsable(this.token) && Date.now() < this.token.refreshAfter) {
|
|
4496
4511
|
return this.token.value;
|
|
4497
4512
|
}
|
|
4498
4513
|
if (!this.requestInFlight) {
|
|
@@ -4501,33 +4516,38 @@ var RuntimeAuth = class {
|
|
|
4501
4516
|
});
|
|
4502
4517
|
}
|
|
4503
4518
|
const token = await this.requestInFlight;
|
|
4504
|
-
if (!token.capabilities.has(capability)) {
|
|
4505
|
-
throw new AuthenticationError("ASIYST runtime authorization does not allow this operation.");
|
|
4506
|
-
}
|
|
4507
4519
|
return token.value;
|
|
4508
4520
|
}
|
|
4509
4521
|
invalidate() {
|
|
4510
4522
|
this.token = void 0;
|
|
4511
4523
|
}
|
|
4512
4524
|
isUsable(token) {
|
|
4513
|
-
return token.expiresAt
|
|
4525
|
+
return token.expiresAt > Date.now();
|
|
4514
4526
|
}
|
|
4515
4527
|
async issueToken() {
|
|
4528
|
+
const installationId = this.options.installationId;
|
|
4529
|
+
if (!installationId) {
|
|
4530
|
+
throw new AuthenticationError("ASIYST installation has not been verified.");
|
|
4531
|
+
}
|
|
4516
4532
|
const controller = new AbortController();
|
|
4517
|
-
|
|
4533
|
+
let timedOut = false;
|
|
4534
|
+
const timeout = setTimeout(() => {
|
|
4535
|
+
timedOut = true;
|
|
4536
|
+
controller.abort();
|
|
4537
|
+
}, 1e4);
|
|
4518
4538
|
let response;
|
|
4519
4539
|
try {
|
|
4520
4540
|
const baseUrl = this.options.apiBaseUrl.replace(/\/$/, "");
|
|
4521
4541
|
const payload = JSON.stringify({
|
|
4522
4542
|
projectId: this.options.projectId,
|
|
4523
4543
|
publicKey: this.options.publicKey,
|
|
4524
|
-
installationId
|
|
4544
|
+
installationId,
|
|
4525
4545
|
origin: this.options.origin,
|
|
4526
|
-
environment: this.options.environment,
|
|
4527
4546
|
sdkVersion: SDK_VERSION,
|
|
4528
|
-
|
|
4547
|
+
environment: this.options.environment,
|
|
4548
|
+
capabilities: ["assistant:config", "assistant:conversation", "assistant:heartbeat"]
|
|
4529
4549
|
});
|
|
4530
|
-
response = await fetch(
|
|
4550
|
+
response = await fetch(contractApiUrl(baseUrl, API_ROUTES.runtimeToken), {
|
|
4531
4551
|
method: "POST",
|
|
4532
4552
|
headers: {
|
|
4533
4553
|
Accept: "application/json",
|
|
@@ -4536,19 +4556,8 @@ var RuntimeAuth = class {
|
|
|
4536
4556
|
body: payload,
|
|
4537
4557
|
signal: controller.signal
|
|
4538
4558
|
});
|
|
4539
|
-
if (response.status === 404) {
|
|
4540
|
-
response = await fetch(`${baseUrl}/api/v1/sdk/runtime/token`, {
|
|
4541
|
-
method: "POST",
|
|
4542
|
-
headers: {
|
|
4543
|
-
Accept: "application/json",
|
|
4544
|
-
"Content-Type": "application/json"
|
|
4545
|
-
},
|
|
4546
|
-
body: payload,
|
|
4547
|
-
signal: controller.signal
|
|
4548
|
-
});
|
|
4549
|
-
}
|
|
4550
4559
|
} catch {
|
|
4551
|
-
throw new NetworkError("ASIYST runtime authentication is unavailable.");
|
|
4560
|
+
throw new NetworkError(timedOut ? "ASIYST runtime authentication request timed out." : "ASIYST runtime authentication is unavailable.");
|
|
4552
4561
|
} finally {
|
|
4553
4562
|
clearTimeout(timeout);
|
|
4554
4563
|
}
|
|
@@ -4565,10 +4574,13 @@ var RuntimeAuth = class {
|
|
|
4565
4574
|
if (response.status === 429) {
|
|
4566
4575
|
throw new NetworkError("ASIYST runtime authentication is rate limited.");
|
|
4567
4576
|
}
|
|
4577
|
+
if (response.status === 503) {
|
|
4578
|
+
throw new NetworkError("ASIYST runtime authentication is unavailable.");
|
|
4579
|
+
}
|
|
4568
4580
|
throw new NetworkError("ASIYST runtime authentication is unavailable.");
|
|
4569
4581
|
}
|
|
4570
4582
|
const data = body?.data;
|
|
4571
|
-
if (
|
|
4583
|
+
if (body?.success !== true || !data || typeof data.token !== "string" || data.token.length < 20 || data.tokenType !== "Bearer" || data.audience !== "asiyst-sdk-runtime" || typeof data.expiresAt !== "string" || data.expiresIn !== 300 || !Array.isArray(data.capabilities) || !data.capabilities.includes("assistant:config") || !data.capabilities.includes("assistant:conversation") || !data.capabilities.includes("assistant:heartbeat")) {
|
|
4572
4584
|
throw new AuthenticationError("ASIYST returned an invalid runtime authorization response.");
|
|
4573
4585
|
}
|
|
4574
4586
|
const expiresAt = Date.parse(data.expiresAt);
|
|
@@ -4578,7 +4590,7 @@ var RuntimeAuth = class {
|
|
|
4578
4590
|
const token = {
|
|
4579
4591
|
value: data.token,
|
|
4580
4592
|
expiresAt,
|
|
4581
|
-
|
|
4593
|
+
refreshAfter: expiresAt
|
|
4582
4594
|
};
|
|
4583
4595
|
this.token = token;
|
|
4584
4596
|
return token;
|
|
@@ -4744,6 +4756,7 @@ var AsiystRuntime = class {
|
|
|
4744
4756
|
this.rescanDebounced = debounce(() => this.rescan(), DOM_SCAN_DEBOUNCE_MS);
|
|
4745
4757
|
this.isHeartbeatInFlight = false;
|
|
4746
4758
|
this.lastHeartbeatTime = 0;
|
|
4759
|
+
this.nextHeartbeatAfterMs = HEARTBEAT_INTERVAL_MS;
|
|
4747
4760
|
this.registrationSucceeded = false;
|
|
4748
4761
|
if (!doc.body) {
|
|
4749
4762
|
throw new InitializationError("document.body is not available");
|
|
@@ -4763,10 +4776,11 @@ var AsiystRuntime = class {
|
|
|
4763
4776
|
apiBaseUrl: options.apiBaseUrl ?? DEFAULT_API_BASE_URL,
|
|
4764
4777
|
projectId: options.projectId,
|
|
4765
4778
|
publicKey: options.publicKey,
|
|
4766
|
-
installationId:
|
|
4779
|
+
installationId: void 0,
|
|
4767
4780
|
origin: win.location.origin,
|
|
4768
4781
|
environment: this.environment
|
|
4769
4782
|
}) : void 0;
|
|
4783
|
+
this.runtimeAuth = runtimeAuth;
|
|
4770
4784
|
this.cloud = new CloudClient(transport, options.projectId, options.publicKey, runtimeAuth, this.visitorSessionId, options.avatarId);
|
|
4771
4785
|
this.config = new ConfigManager(options, this.cloud, this.events);
|
|
4772
4786
|
this.config.onConfigUpdated = (newConfig, prevConfig) => {
|
|
@@ -4798,21 +4812,19 @@ var AsiystRuntime = class {
|
|
|
4798
4812
|
() => this.config.get()
|
|
4799
4813
|
);
|
|
4800
4814
|
const interaction = new InteractionEngine(this.avatar, this.resolver, () => this.config.get(), win);
|
|
4801
|
-
this.tasks = new TaskEngine(interaction, this.events, this.analytics
|
|
4815
|
+
this.tasks = new TaskEngine(interaction, this.events, this.analytics);
|
|
4802
4816
|
this.workflows = new WorkflowEngine(this.cloud, this.tasks);
|
|
4803
4817
|
this.panel = new ConversationPanel(
|
|
4804
4818
|
this.host.chrome,
|
|
4805
4819
|
(text) => this.handleUserMessage(text, doc),
|
|
4806
4820
|
(open) => {
|
|
4807
|
-
const convId = this.panel.getConversationId();
|
|
4808
|
-
this.cloud.setConversationId(convId);
|
|
4809
4821
|
this.renderer.setPanelOpen(open);
|
|
4810
4822
|
if (open) {
|
|
4811
4823
|
this.analytics.track("assistant_opened");
|
|
4812
|
-
this.events.emit("asiyst:conversation:started", { conversationId: convId });
|
|
4813
4824
|
} else {
|
|
4814
4825
|
this.analytics.track("assistant_closed");
|
|
4815
|
-
this.
|
|
4826
|
+
const conversationId = this.panel.getConversationId();
|
|
4827
|
+
if (conversationId) this.events.emit("asiyst:conversation:closed", { conversationId });
|
|
4816
4828
|
}
|
|
4817
4829
|
}
|
|
4818
4830
|
);
|
|
@@ -4821,22 +4833,35 @@ var AsiystRuntime = class {
|
|
|
4821
4833
|
this.observer.start(doc.documentElement);
|
|
4822
4834
|
this.highlights.start();
|
|
4823
4835
|
this.movement.start();
|
|
4824
|
-
this.analytics.start();
|
|
4825
4836
|
this.rescan();
|
|
4826
4837
|
const figure = this.renderer.getFigure();
|
|
4827
4838
|
if (figure) {
|
|
4828
4839
|
this.figureClickListener = () => this.open();
|
|
4829
4840
|
figure.addEventListener("click", this.figureClickListener);
|
|
4830
4841
|
}
|
|
4831
|
-
this.pagehideListener = () => {
|
|
4832
|
-
void this.analytics.flush();
|
|
4833
|
-
};
|
|
4834
|
-
win.addEventListener("pagehide", this.pagehideListener);
|
|
4835
4842
|
}
|
|
4836
4843
|
async start() {
|
|
4837
4844
|
this.events.emit("asiyst:initialized", { projectId: this.options.projectId });
|
|
4838
4845
|
this.avatar.show();
|
|
4839
4846
|
this.movement.goToAnchor();
|
|
4847
|
+
this.lifecycle.emit("sdk.verification_started", {
|
|
4848
|
+
projectId: this.options.projectId,
|
|
4849
|
+
origin: window.location.origin,
|
|
4850
|
+
environment: this.environment,
|
|
4851
|
+
installationId: this.installationId,
|
|
4852
|
+
sdkVersion: SDK_VERSION
|
|
4853
|
+
});
|
|
4854
|
+
try {
|
|
4855
|
+
await this.registerInstallation();
|
|
4856
|
+
} catch (error) {
|
|
4857
|
+
this.connectionStatus = "offline";
|
|
4858
|
+
this.verificationStatus = "error";
|
|
4859
|
+
this.events.emit("asiyst:error", {
|
|
4860
|
+
code: "runtime_connection_failed",
|
|
4861
|
+
message: error instanceof Error ? error.message : "Asiyst runtime connection failed."
|
|
4862
|
+
});
|
|
4863
|
+
return;
|
|
4864
|
+
}
|
|
4840
4865
|
const cfg = await isolateAsync(() => this.config.refresh(), this.config.get());
|
|
4841
4866
|
this.metricsTracker.record("configRetrieved");
|
|
4842
4867
|
const domainCheck = validateWebsiteDomain(cfg, window.location.href);
|
|
@@ -4851,28 +4876,7 @@ var AsiystRuntime = class {
|
|
|
4851
4876
|
}
|
|
4852
4877
|
this.avatar.applyConfig(cfg);
|
|
4853
4878
|
this.movement.goToAnchor();
|
|
4854
|
-
this.lifecycle.emit("sdk.verification_started", {
|
|
4855
|
-
projectId: this.options.projectId,
|
|
4856
|
-
origin: window.location.origin,
|
|
4857
|
-
environment: this.environment,
|
|
4858
|
-
installationId: this.installationId,
|
|
4859
|
-
sdkVersion: SDK_VERSION
|
|
4860
|
-
});
|
|
4861
|
-
void (async () => {
|
|
4862
|
-
try {
|
|
4863
|
-
await this.registerInstallation();
|
|
4864
|
-
await this.sendHeartbeat();
|
|
4865
|
-
const doc = this.host.host.ownerDocument;
|
|
4866
|
-
this.startHeartbeatScheduler(doc);
|
|
4867
|
-
} catch {
|
|
4868
|
-
}
|
|
4869
|
-
})();
|
|
4870
4879
|
this.events.emit("asiyst:ready", { projectId: this.options.projectId, configVersion: cfg.version });
|
|
4871
|
-
void this.cloud.sendTelemetryEvent("avatar_runtime_initialized", {
|
|
4872
|
-
avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
|
|
4873
|
-
avatarName: cfg.avatarName,
|
|
4874
|
-
publishedVersion: cfg.publishedVersion
|
|
4875
|
-
});
|
|
4876
4880
|
const assetTarget = cfg.assetUrl ?? cfg.thumbnailUrl;
|
|
4877
4881
|
if (assetTarget) {
|
|
4878
4882
|
try {
|
|
@@ -4885,6 +4889,16 @@ var AsiystRuntime = class {
|
|
|
4885
4889
|
this.avatar.show();
|
|
4886
4890
|
this.movement.goToAnchor();
|
|
4887
4891
|
}
|
|
4892
|
+
try {
|
|
4893
|
+
await this.sendHeartbeat();
|
|
4894
|
+
} catch (error) {
|
|
4895
|
+
this.connectionStatus = "offline";
|
|
4896
|
+
this.verificationStatus = "error";
|
|
4897
|
+
this.events.emit("asiyst:error", {
|
|
4898
|
+
code: "runtime_connection_failed",
|
|
4899
|
+
message: error instanceof Error ? error.message : "Asiyst runtime connection failed."
|
|
4900
|
+
});
|
|
4901
|
+
}
|
|
4888
4902
|
this.startConfigRevalidationScheduler();
|
|
4889
4903
|
}
|
|
4890
4904
|
async loadAvatarAsset(cfg, assetTarget) {
|
|
@@ -4892,10 +4906,6 @@ var AsiystRuntime = class {
|
|
|
4892
4906
|
avatarId: this.options.avatarId ?? cfg.avatarId,
|
|
4893
4907
|
assetUrl: assetTarget
|
|
4894
4908
|
});
|
|
4895
|
-
void this.cloud.sendTelemetryEvent("avatar_asset_loading_started", {
|
|
4896
|
-
avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
|
|
4897
|
-
assetUrl: assetTarget
|
|
4898
|
-
});
|
|
4899
4909
|
try {
|
|
4900
4910
|
const loaded = await this.renderer.loadAsset(cfg, this.metricsTracker);
|
|
4901
4911
|
if (loaded) {
|
|
@@ -4908,13 +4918,6 @@ var AsiystRuntime = class {
|
|
|
4908
4918
|
assetUrl,
|
|
4909
4919
|
format
|
|
4910
4920
|
});
|
|
4911
|
-
void this.cloud.sendTelemetryEvent("avatar_asset_loaded", {
|
|
4912
|
-
avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
|
|
4913
|
-
avatarName: cfg.avatarName,
|
|
4914
|
-
assetUrl,
|
|
4915
|
-
format,
|
|
4916
|
-
publishedVersion: cfg.publishedVersion
|
|
4917
|
-
});
|
|
4918
4921
|
if (isRendered) {
|
|
4919
4922
|
const metrics = this.metricsTracker.getMetrics();
|
|
4920
4923
|
const durationMs = metrics?.durations.timeToFirstVisibleMs;
|
|
@@ -4923,13 +4926,6 @@ var AsiystRuntime = class {
|
|
|
4923
4926
|
format,
|
|
4924
4927
|
durationMs
|
|
4925
4928
|
});
|
|
4926
|
-
void this.cloud.sendTelemetryEvent("avatar_rendered", {
|
|
4927
|
-
avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
|
|
4928
|
-
avatarName: cfg.avatarName,
|
|
4929
|
-
format,
|
|
4930
|
-
publishedVersion: cfg.publishedVersion,
|
|
4931
|
-
durationMs
|
|
4932
|
-
});
|
|
4933
4929
|
}
|
|
4934
4930
|
return true;
|
|
4935
4931
|
} else {
|
|
@@ -4939,11 +4935,6 @@ var AsiystRuntime = class {
|
|
|
4939
4935
|
error: err,
|
|
4940
4936
|
stage: "renderer_init"
|
|
4941
4937
|
});
|
|
4942
|
-
void this.cloud.sendTelemetryEvent("avatar_render_failed", {
|
|
4943
|
-
avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
|
|
4944
|
-
error: err,
|
|
4945
|
-
stage: "renderer_init"
|
|
4946
|
-
});
|
|
4947
4938
|
return false;
|
|
4948
4939
|
}
|
|
4949
4940
|
} catch (error) {
|
|
@@ -4953,11 +4944,6 @@ var AsiystRuntime = class {
|
|
|
4953
4944
|
error: err,
|
|
4954
4945
|
stage: "asset_fetch"
|
|
4955
4946
|
});
|
|
4956
|
-
void this.cloud.sendTelemetryEvent("avatar_render_failed", {
|
|
4957
|
-
avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
|
|
4958
|
-
error: err,
|
|
4959
|
-
stage: "asset_fetch"
|
|
4960
|
-
});
|
|
4961
4947
|
return false;
|
|
4962
4948
|
}
|
|
4963
4949
|
}
|
|
@@ -5004,6 +4990,7 @@ var AsiystRuntime = class {
|
|
|
5004
4990
|
config: newConfig,
|
|
5005
4991
|
previousVersion: prevConfig?.version
|
|
5006
4992
|
});
|
|
4993
|
+
void this.sendHeartbeat();
|
|
5007
4994
|
}
|
|
5008
4995
|
async reloadConfig() {
|
|
5009
4996
|
const updated = await this.config.refresh({ force: true });
|
|
@@ -5093,15 +5080,11 @@ var AsiystRuntime = class {
|
|
|
5093
5080
|
clearInterval(this.configRevalidationTimer);
|
|
5094
5081
|
this.configRevalidationTimer = void 0;
|
|
5095
5082
|
}
|
|
5096
|
-
|
|
5097
|
-
|
|
5098
|
-
|
|
5099
|
-
this.visibilityListener = void 0;
|
|
5083
|
+
if (this.heartbeatTimer) {
|
|
5084
|
+
clearTimeout(this.heartbeatTimer);
|
|
5085
|
+
this.heartbeatTimer = void 0;
|
|
5100
5086
|
}
|
|
5101
5087
|
this.isHeartbeatInFlight = false;
|
|
5102
|
-
if (this.pagehideListener) {
|
|
5103
|
-
win.removeEventListener("pagehide", this.pagehideListener);
|
|
5104
|
-
}
|
|
5105
5088
|
const figure = this.renderer.getFigure();
|
|
5106
5089
|
if (figure && this.figureClickListener) {
|
|
5107
5090
|
figure.removeEventListener("click", this.figureClickListener);
|
|
@@ -5118,26 +5101,20 @@ var AsiystRuntime = class {
|
|
|
5118
5101
|
this.events.removeAll();
|
|
5119
5102
|
await this.analytics.destroy();
|
|
5120
5103
|
}
|
|
5121
|
-
|
|
5122
|
-
if (this.
|
|
5123
|
-
|
|
5104
|
+
async sendHeartbeat() {
|
|
5105
|
+
if (this.destroyed || this.isHeartbeatInFlight || !this.registrationSucceeded || !this.installationId) {
|
|
5106
|
+
return false;
|
|
5124
5107
|
}
|
|
5125
|
-
|
|
5126
|
-
|
|
5127
|
-
|
|
5108
|
+
const state = this.renderer.getRenderState() === "error" ? "degraded" : "ready";
|
|
5109
|
+
if (this.lastReportedState === state) return true;
|
|
5110
|
+
const elapsed = Date.now() - this.lastHeartbeatTime;
|
|
5111
|
+
if (this.lastHeartbeatTime && elapsed < this.nextHeartbeatAfterMs) {
|
|
5112
|
+
if (!this.heartbeatTimer) {
|
|
5113
|
+
this.heartbeatTimer = setTimeout(() => {
|
|
5114
|
+
this.heartbeatTimer = void 0;
|
|
5115
|
+
void this.sendHeartbeat();
|
|
5116
|
+
}, this.nextHeartbeatAfterMs - elapsed);
|
|
5128
5117
|
}
|
|
5129
|
-
}, HEARTBEAT_INTERVAL_MS);
|
|
5130
|
-
if (doc && typeof doc.addEventListener === "function") {
|
|
5131
|
-
this.visibilityListener = () => {
|
|
5132
|
-
if (!this.destroyed && doc.visibilityState === "visible" && Date.now() - this.lastHeartbeatTime > 3e4) {
|
|
5133
|
-
void this.sendHeartbeat(true);
|
|
5134
|
-
}
|
|
5135
|
-
};
|
|
5136
|
-
doc.addEventListener("visibilitychange", this.visibilityListener);
|
|
5137
|
-
}
|
|
5138
|
-
}
|
|
5139
|
-
async sendHeartbeat(_isPeriodic = false) {
|
|
5140
|
-
if (this.destroyed || this.isHeartbeatInFlight) {
|
|
5141
5118
|
return false;
|
|
5142
5119
|
}
|
|
5143
5120
|
this.isHeartbeatInFlight = true;
|
|
@@ -5146,17 +5123,23 @@ var AsiystRuntime = class {
|
|
|
5146
5123
|
const environment = this.environment;
|
|
5147
5124
|
const installationId = this.installationId;
|
|
5148
5125
|
try {
|
|
5149
|
-
if (!this.registrationSucceeded && installationId) {
|
|
5150
|
-
await this.registerInstallation();
|
|
5151
|
-
}
|
|
5152
5126
|
const heartbeat = await this.cloud.heartbeat({
|
|
5153
|
-
|
|
5154
|
-
|
|
5155
|
-
|
|
5127
|
+
installationId: this.installationId,
|
|
5128
|
+
sdkVersion: SDK_VERSION,
|
|
5129
|
+
state,
|
|
5130
|
+
avatarReady: this.renderer.getRenderState() === "ready",
|
|
5131
|
+
textChatReady: true,
|
|
5132
|
+
environment: this.environment,
|
|
5133
|
+
...state === "degraded" ? { failureReason: "asset_load_failed" } : {}
|
|
5156
5134
|
});
|
|
5157
5135
|
this.lastHeartbeatTime = Date.now();
|
|
5136
|
+
if (heartbeat.ok) this.lastReportedState = state;
|
|
5137
|
+
this.nextHeartbeatAfterMs = Math.max(
|
|
5138
|
+
HEARTBEAT_INTERVAL_MS,
|
|
5139
|
+
heartbeat.nextHeartbeatAfterMs ?? heartbeat.retryAfterMs ?? HEARTBEAT_INTERVAL_MS
|
|
5140
|
+
);
|
|
5158
5141
|
this.connectionStatus = heartbeat.ok ? "connected" : "disconnected";
|
|
5159
|
-
this.verificationStatus = heartbeat.
|
|
5142
|
+
this.verificationStatus = heartbeat.ok ? "connected" : "not_detected";
|
|
5160
5143
|
if (heartbeat.ok) {
|
|
5161
5144
|
if (!previousConnection) {
|
|
5162
5145
|
this.events.emit("asiyst:runtime:connected", {
|
|
@@ -5173,32 +5156,21 @@ var AsiystRuntime = class {
|
|
|
5173
5156
|
sdkVersion: SDK_VERSION
|
|
5174
5157
|
});
|
|
5175
5158
|
}
|
|
5176
|
-
|
|
5177
|
-
this.
|
|
5178
|
-
|
|
5179
|
-
|
|
5180
|
-
|
|
5181
|
-
|
|
5182
|
-
|
|
5183
|
-
});
|
|
5184
|
-
}
|
|
5185
|
-
if (heartbeat.versionOutdated) {
|
|
5186
|
-
this.lifecycle.emit("sdk.version_outdated", {
|
|
5187
|
-
projectId: this.options.projectId,
|
|
5188
|
-
origin,
|
|
5189
|
-
environment,
|
|
5190
|
-
installationId,
|
|
5191
|
-
sdkVersion: SDK_VERSION
|
|
5192
|
-
});
|
|
5193
|
-
}
|
|
5159
|
+
this.lifecycle.emit("sdk.verified", {
|
|
5160
|
+
projectId: this.options.projectId,
|
|
5161
|
+
origin,
|
|
5162
|
+
environment,
|
|
5163
|
+
installationId,
|
|
5164
|
+
sdkVersion: SDK_VERSION
|
|
5165
|
+
});
|
|
5194
5166
|
return true;
|
|
5195
5167
|
} else {
|
|
5196
|
-
|
|
5168
|
+
this.lastReportedState = void 0;
|
|
5197
5169
|
this.lifecycle.emit("sdk.verification_failed", {
|
|
5198
5170
|
projectId: this.options.projectId,
|
|
5199
5171
|
origin,
|
|
5200
5172
|
environment,
|
|
5201
|
-
status:
|
|
5173
|
+
status: "heartbeat_failed",
|
|
5202
5174
|
reason: "heartbeat_failed"
|
|
5203
5175
|
});
|
|
5204
5176
|
if (previousConnection) {
|
|
@@ -5212,12 +5184,15 @@ var AsiystRuntime = class {
|
|
|
5212
5184
|
environment,
|
|
5213
5185
|
installationId,
|
|
5214
5186
|
reason: "heartbeat_failed",
|
|
5215
|
-
status:
|
|
5187
|
+
status: "heartbeat_failed"
|
|
5216
5188
|
});
|
|
5217
5189
|
}
|
|
5190
|
+
this.scheduleHeartbeatRetry();
|
|
5218
5191
|
return false;
|
|
5219
5192
|
}
|
|
5220
5193
|
} catch (error) {
|
|
5194
|
+
this.lastHeartbeatTime = Date.now();
|
|
5195
|
+
this.lastReportedState = void 0;
|
|
5221
5196
|
this.connectionStatus = "offline";
|
|
5222
5197
|
this.verificationStatus = "error";
|
|
5223
5198
|
this.lifecycle.emit("sdk.verification_failed", {
|
|
@@ -5228,6 +5203,10 @@ var AsiystRuntime = class {
|
|
|
5228
5203
|
reason: "heartbeat_failed",
|
|
5229
5204
|
category: error instanceof AuthenticationError ? "authorization" : "network"
|
|
5230
5205
|
});
|
|
5206
|
+
this.events.emit("asiyst:error", {
|
|
5207
|
+
code: "runtime_heartbeat_failed",
|
|
5208
|
+
message: error instanceof Error ? error.message : "Asiyst heartbeat failed."
|
|
5209
|
+
});
|
|
5231
5210
|
if (previousConnection) {
|
|
5232
5211
|
this.events.emit("asiyst:runtime:disconnected", {
|
|
5233
5212
|
projectId: this.options.projectId,
|
|
@@ -5247,73 +5226,72 @@ var AsiystRuntime = class {
|
|
|
5247
5226
|
this.isHeartbeatInFlight = false;
|
|
5248
5227
|
}
|
|
5249
5228
|
}
|
|
5229
|
+
scheduleHeartbeatRetry() {
|
|
5230
|
+
if (this.destroyed || this.heartbeatTimer) return;
|
|
5231
|
+
const remaining = Math.max(0, this.nextHeartbeatAfterMs - (Date.now() - this.lastHeartbeatTime));
|
|
5232
|
+
this.heartbeatTimer = setTimeout(() => {
|
|
5233
|
+
this.heartbeatTimer = void 0;
|
|
5234
|
+
void this.sendHeartbeat();
|
|
5235
|
+
}, remaining);
|
|
5236
|
+
}
|
|
5250
5237
|
async registerInstallation() {
|
|
5251
5238
|
const origin = window.location.origin;
|
|
5252
5239
|
const environment = this.environment;
|
|
5253
5240
|
const installationId = this.installationId;
|
|
5254
5241
|
if (!installationId) {
|
|
5255
|
-
|
|
5256
|
-
console.debug("[asiyst] SDK installation identity is unavailable; registration skipped.");
|
|
5257
|
-
}
|
|
5258
|
-
return;
|
|
5242
|
+
throw new InitializationError("Asiyst could not establish a secure installation identity.");
|
|
5259
5243
|
}
|
|
5260
|
-
|
|
5261
|
-
|
|
5262
|
-
|
|
5263
|
-
|
|
5264
|
-
|
|
5265
|
-
|
|
5266
|
-
|
|
5267
|
-
|
|
5268
|
-
|
|
5269
|
-
|
|
5270
|
-
|
|
5271
|
-
this.registrationSucceeded = true;
|
|
5272
|
-
return;
|
|
5273
|
-
} catch (error) {
|
|
5274
|
-
lastError = error;
|
|
5275
|
-
if (attempt === 1) {
|
|
5276
|
-
if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
|
|
5277
|
-
console.debug("[asiyst] SDK installation registration failed.", error);
|
|
5278
|
-
}
|
|
5279
|
-
this.lifecycle.emit("sdk.verification_failed", {
|
|
5280
|
-
projectId: this.options.projectId,
|
|
5281
|
-
origin,
|
|
5282
|
-
environment,
|
|
5283
|
-
installationId,
|
|
5284
|
-
reason: "registration_failed",
|
|
5285
|
-
category: error instanceof AuthenticationError ? "authorization" : "network"
|
|
5286
|
-
});
|
|
5287
|
-
return;
|
|
5288
|
-
}
|
|
5289
|
-
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
5244
|
+
try {
|
|
5245
|
+
const verified = await this.cloud.registerInstallation({
|
|
5246
|
+
projectId: this.options.projectId,
|
|
5247
|
+
publicKey: this.options.publicKey,
|
|
5248
|
+
installationId,
|
|
5249
|
+
origin,
|
|
5250
|
+
environment,
|
|
5251
|
+
sdkVersion: SDK_VERSION
|
|
5252
|
+
});
|
|
5253
|
+
if (!verified.data.installationId) {
|
|
5254
|
+
throw new InitializationError("Asiyst returned no verified installation identifier.");
|
|
5290
5255
|
}
|
|
5256
|
+
this.installationId = verified.data.installationId;
|
|
5257
|
+
this.runtimeAuth?.setInstallationId(verified.data.installationId);
|
|
5258
|
+
this.registrationSucceeded = true;
|
|
5259
|
+
} catch (error) {
|
|
5260
|
+
if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
|
|
5261
|
+
console.debug("[asiyst] SDK installation verification failed.", error);
|
|
5262
|
+
}
|
|
5263
|
+
this.lifecycle.emit("sdk.verification_failed", {
|
|
5264
|
+
projectId: this.options.projectId,
|
|
5265
|
+
origin,
|
|
5266
|
+
environment,
|
|
5267
|
+
installationId,
|
|
5268
|
+
reason: "registration_failed",
|
|
5269
|
+
category: error instanceof AuthenticationError ? "authorization" : "network"
|
|
5270
|
+
});
|
|
5271
|
+
throw error;
|
|
5291
5272
|
}
|
|
5292
|
-
this.lifecycle.emit("sdk.verification_failed", {
|
|
5293
|
-
projectId: this.options.projectId,
|
|
5294
|
-
origin,
|
|
5295
|
-
environment,
|
|
5296
|
-
installationId,
|
|
5297
|
-
reason: "registration_failed",
|
|
5298
|
-
category: lastError instanceof AuthenticationError ? "authorization" : "network"
|
|
5299
|
-
});
|
|
5300
5273
|
}
|
|
5301
5274
|
rescan() {
|
|
5302
5275
|
withIsolation(() => {
|
|
5303
5276
|
const doc = this.host.host.ownerDocument;
|
|
5304
5277
|
this.map.replace(inspectDocument(doc));
|
|
5305
|
-
void this.cloud.sendWebsiteMap(this.map.snapshot(doc));
|
|
5306
5278
|
});
|
|
5307
5279
|
}
|
|
5308
5280
|
async handleUserMessage(text, doc) {
|
|
5309
5281
|
this.events.emit("asiyst:conversation:message", { role: "user", text });
|
|
5310
5282
|
this.avatar.think();
|
|
5311
5283
|
try {
|
|
5312
|
-
const reply = await this.cloud.sendConversationMessage(
|
|
5313
|
-
|
|
5284
|
+
const reply = await this.cloud.sendConversationMessage(
|
|
5285
|
+
text,
|
|
5286
|
+
doc.location.href,
|
|
5287
|
+
this.config.get().maxMessageChars
|
|
5288
|
+
);
|
|
5289
|
+
this.panel.setConversationId(reply.conversationId);
|
|
5290
|
+
this.cloud.setConversationId(reply.conversationId);
|
|
5291
|
+
this.events.emit("asiyst:conversation:started", { conversationId: reply.conversationId });
|
|
5292
|
+
this.panel.append("assistant", reply.message.text, reply.citations);
|
|
5314
5293
|
this.avatar.speak(reply.message.text);
|
|
5315
5294
|
this.events.emit("asiyst:conversation:message", { role: "assistant", text: reply.message.text });
|
|
5316
|
-
await this.startTaskFromText(text, doc);
|
|
5317
5295
|
} catch (error) {
|
|
5318
5296
|
const message = error instanceof Error ? error.message : "Asiyst Cloud is unavailable";
|
|
5319
5297
|
this.panel.append("assistant", message);
|
|
@@ -5337,6 +5315,9 @@ var Asiyst = {
|
|
|
5337
5315
|
if (runtime) {
|
|
5338
5316
|
throw new InitializationError("Asiyst is already initialized");
|
|
5339
5317
|
}
|
|
5318
|
+
if (typeof document === "undefined" || typeof window === "undefined") {
|
|
5319
|
+
throw new InitializationError("Asiyst SDK can only be initialized in a browser environment.");
|
|
5320
|
+
}
|
|
5340
5321
|
const credentials = validateInitOptions(options);
|
|
5341
5322
|
const doc = document;
|
|
5342
5323
|
const win = window;
|