@asiyst/sdk 0.1.28 → 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/dist/index.cjs CHANGED
@@ -97,7 +97,7 @@ var ALL_ACTION_KINDS = [
97
97
  // src/core/constants.ts
98
98
  function resolveSdkVersion() {
99
99
  {
100
- return "0.1.28";
100
+ return "0.1.29";
101
101
  }
102
102
  }
103
103
  var SDK_VERSION = resolveSdkVersion();
@@ -116,7 +116,7 @@ var AVATAR_TARGET_GAP = 16;
116
116
  var WEBSITE_MAP_TEXT_LIMIT = 80;
117
117
  var CONFIG_CACHE_TTL_MS = 1e3 * 30;
118
118
  var CONFIG_REVALIDATION_INTERVAL_MS = 3e4;
119
- var HEARTBEAT_INTERVAL_MS = 45e3;
119
+ var HEARTBEAT_INTERVAL_MS = 3e5;
120
120
 
121
121
  // src/security/selectors.ts
122
122
  var DANGEROUS_SELECTOR = /javascript:|expression\(|@import|url\s*\(|behavior:|binding:|<script/i;
@@ -378,7 +378,8 @@ function parseAnimations(value) {
378
378
  clipName: typeof item.clipName === "string" ? sanitizeText(item.clipName, 64) : void 0,
379
379
  loopMode: typeof item.loopMode === "string" ? sanitizeText(item.loopMode, 32) : void 0,
380
380
  durationMs: typeof item.durationMs === "number" ? item.durationMs : void 0,
381
- assetUrl: typeof item.assetUrl === "string" ? item.assetUrl : null
381
+ assetUrl: typeof item.assetUrl === "string" ? item.assetUrl : null,
382
+ integrity: typeof item.integrity === "string" ? item.integrity : void 0
382
383
  });
383
384
  }
384
385
  }
@@ -405,6 +406,8 @@ function normalizeProjectConfig(raw) {
405
406
  ) || void 0;
406
407
  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;
407
408
  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;
409
+ const rawModelFormat = raw.modelFormat ?? rawAvatarRecord?.modelFormat ?? rawConfigRecord?.modelFormat ?? rawManifestRecord?.modelFormat;
410
+ const modelFormat = rawModelFormat === "fbx" || rawModelFormat === "glb" ? rawModelFormat : void 0;
408
411
  const publishedVersion = typeof raw.publishedVersion === "string" ? raw.publishedVersion : typeof rawAvatarRecord?.version === "string" ? rawAvatarRecord.version : typeof rawManifestRecord?.version === "string" ? rawManifestRecord.version : void 0;
409
412
  const animations = parseAnimations(
410
413
  raw.animations ?? rawAvatarRecord?.animations ?? rawConfigRecord?.animations
@@ -424,6 +427,8 @@ function normalizeProjectConfig(raw) {
424
427
  avatar,
425
428
  avatarId,
426
429
  assetUrl,
430
+ modelFormat,
431
+ assetIntegrity: typeof raw.assetIntegrity === "string" ? raw.assetIntegrity : typeof rawAvatarRecord?.assetIntegrity === "string" ? rawAvatarRecord.assetIntegrity : void 0,
427
432
  thumbnailUrl,
428
433
  publishedVersion,
429
434
  animations,
@@ -442,7 +447,8 @@ function normalizeProjectConfig(raw) {
442
447
  blockedRoutes: parseStringList(raw.blockedRoutes ?? raw.blocked_routes),
443
448
  rules: parseRules(raw.rules ?? raw.avatarRules),
444
449
  dataSources: parseDataSources(raw.dataSources ?? raw.enabledDataSources),
445
- elementSelectors: parseElementSelectors(raw.elementSelectors)
450
+ elementSelectors: parseElementSelectors(raw.elementSelectors),
451
+ maxMessageChars: asNumber(raw.maxMessageChars, 4e3, 1, 4e3)
446
452
  };
447
453
  }
448
454
  function validateInitOptions(options) {
@@ -526,7 +532,7 @@ var HttpTransport = class {
526
532
  return this.options.avatarId;
527
533
  }
528
534
  async request(req) {
529
- const url = `${this.options.apiBaseUrl.replace(/\/$/, "")}${req.path}`;
535
+ const url = /^https?:\/\//i.test(req.path) ? req.path : `${this.options.apiBaseUrl.replace(/\/$/, "")}${req.path}`;
530
536
  const requestId = req.requestId || generateRequestId();
531
537
  const timeoutMs = req.timeoutMs ?? this.options.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS;
532
538
  const isSafeOrIdempotent = req.method === "GET" || Boolean(req.idempotent);
@@ -554,36 +560,30 @@ var HttpTransport = class {
554
560
  }
555
561
  try {
556
562
  let response;
557
- try {
558
- response = await fetch(url, {
559
- method: req.method,
560
- headers: {
561
- Accept: "application/json",
562
- "Content-Type": "application/json",
563
- "X-Asiyst-Project-Id": this.options.projectId,
564
- "X-Asiyst-Public-Key": this.options.publicKey,
565
- ...this.options.avatarId ? { "X-Asiyst-Avatar-Id": this.options.avatarId } : {},
566
- "X-Asiyst-SDK-Version": SDK_VERSION,
567
- "X-Asiyst-Request-Id": requestId,
568
- ...req.sessionId ? { "X-Asiyst-Session-Id": req.sessionId } : {},
569
- ...req.conversationId ? { "X-Asiyst-Conversation-Id": req.conversationId } : {},
570
- ...req.authorizationToken ? { Authorization: `Bearer ${req.authorizationToken}` } : {}
571
- },
572
- body: req.body === void 0 ? void 0 : JSON.stringify(req.body),
573
- signal: controller.signal
574
- });
575
- } finally {
576
- clearTimeout(timeoutId);
577
- if (req.signal) {
578
- req.signal.removeEventListener("abort", onExternalAbort);
579
- }
580
- }
563
+ response = await fetch(url, {
564
+ method: req.method,
565
+ headers: req.headers ?? {
566
+ Accept: "application/json",
567
+ "Content-Type": "application/json",
568
+ "X-Asiyst-Project-Id": this.options.projectId,
569
+ "X-Asiyst-Public-Key": this.options.publicKey,
570
+ ...this.options.avatarId ? { "X-Asiyst-Avatar-Id": this.options.avatarId } : {},
571
+ "X-Asiyst-SDK-Version": SDK_VERSION,
572
+ "X-Asiyst-Request-Id": requestId,
573
+ ...req.sessionId ? { "X-Asiyst-Session-Id": req.sessionId } : {},
574
+ ...req.conversationId ? { "X-Asiyst-Conversation-Id": req.conversationId } : {},
575
+ ...req.authorizationToken ? { Authorization: `Bearer ${req.authorizationToken}` } : {}
576
+ },
577
+ body: req.body === void 0 ? void 0 : JSON.stringify(req.body),
578
+ signal: controller.signal
579
+ });
581
580
  if (isSafeOrIdempotent && attempt < maxRetries && [502, 503, 504].includes(response.status)) {
582
581
  continue;
583
582
  }
584
583
  if (response.status === 429 && isSafeOrIdempotent && attempt < maxRetries) {
585
584
  const retryAfterHeader = response.headers.get("retry-after");
586
585
  const retryAfterMs = retryAfterHeader ? Math.min(Number(retryAfterHeader) * 1e3 || 200, 1e3) : 100;
586
+ clearTimeout(timeoutId);
587
587
  await new Promise((resolve) => setTimeout(resolve, retryAfterMs));
588
588
  continue;
589
589
  }
@@ -593,33 +593,87 @@ var HttpTransport = class {
593
593
  try {
594
594
  data = await response.json();
595
595
  } catch {
596
+ if (timedOut) {
597
+ throw new NetworkError("Asiyst Cloud request timed out");
598
+ }
599
+ if (req.signal?.aborted) {
600
+ throw new NetworkError("Asiyst Cloud request was aborted");
601
+ }
596
602
  data = null;
597
603
  }
598
604
  }
599
605
  if (!response.ok) {
600
- return { ok: false, status: response.status, data };
606
+ return { ok: false, status: response.status, data, headers: response.headers };
601
607
  }
602
- return { ok: true, status: response.status, data };
608
+ return { ok: true, status: response.status, data, headers: response.headers };
603
609
  } catch (err) {
604
- clearTimeout(timeoutId);
605
- if (req.signal) {
606
- req.signal.removeEventListener("abort", onExternalAbort);
607
- }
608
610
  if (timedOut) {
609
611
  throw new NetworkError("Asiyst Cloud request timed out");
610
612
  }
613
+ if (req.signal?.aborted) {
614
+ throw new NetworkError("Asiyst Cloud request was aborted");
615
+ }
611
616
  lastError = err;
612
617
  if (isSafeOrIdempotent && attempt < maxRetries) {
613
618
  continue;
614
619
  }
615
620
  throw new NetworkError("Asiyst Cloud is unreachable");
621
+ } finally {
622
+ clearTimeout(timeoutId);
623
+ if (req.signal) {
624
+ req.signal.removeEventListener("abort", onExternalAbort);
625
+ }
616
626
  }
617
627
  }
618
628
  throw lastError instanceof Error ? lastError : new NetworkError("Asiyst Cloud is unreachable");
619
629
  }
620
630
  };
621
631
 
632
+ // ../api-contract.ts
633
+ var API_V1_BASE_PATH = "/api/v1";
634
+ var API_ROUTES = {
635
+ runtimeAvatar: "/runtime/avatar",
636
+ runtimeToken: "/sdk/runtime/token",
637
+ installationRegister: "/sdk/installations/register",
638
+ runtimeHeartbeat: "/sdk/heartbeat",
639
+ chat: "/conversations/messages",
640
+ projectApiKeyVerify: (projectId) => `/projects/${encodeURIComponent(projectId)}/api-key/verify`,
641
+ sdkInstallationVerify: "/sdk/installations/verify"
642
+ };
643
+ var API_LIMITS = {
644
+ configStaleIfErrorMs: 0,
645
+ maxMessageChars: 12e3,
646
+ pageUrlMaxChars: 2048};
647
+ function apiV1Path(route) {
648
+ return `${API_V1_BASE_PATH}${route.startsWith("/") ? route : `/${route}`}`;
649
+ }
650
+ function contractApiBaseUrl(configuredApiBaseUrl) {
651
+ const parsed = new URL(configuredApiBaseUrl);
652
+ if (parsed.pathname.replace(/\/+$/, "").endsWith("/functions/v1/api")) {
653
+ return "https://asiyst.com";
654
+ }
655
+ return parsed.origin;
656
+ }
657
+ function contractApiUrl(configuredApiBaseUrl, route) {
658
+ return `${contractApiBaseUrl(configuredApiBaseUrl).replace(/\/+$/, "")}${apiV1Path(route)}`;
659
+ }
660
+
622
661
  // src/communication/CloudClient.ts
662
+ function newRequestId() {
663
+ const cryptoApi = globalThis.crypto;
664
+ if (typeof cryptoApi?.randomUUID === "function") return cryptoApi.randomUUID();
665
+ if (typeof cryptoApi?.getRandomValues === "function") {
666
+ const bytes = cryptoApi.getRandomValues(new Uint8Array(16));
667
+ bytes[6] = (bytes[6] ?? 0) & 15 | 64;
668
+ bytes[8] = (bytes[8] ?? 0) & 63 | 128;
669
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
670
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
671
+ }
672
+ throw new ConfigurationError("Secure request identifiers are unavailable in this browser.");
673
+ }
674
+ function isUuid(value) {
675
+ 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);
676
+ }
623
677
  var CloudClient = class {
624
678
  constructor(transport, projectId, publicKey = "", runtimeAuth, sessionId, avatarId) {
625
679
  this.transport = transport;
@@ -627,6 +681,7 @@ var CloudClient = class {
627
681
  this.publicKey = publicKey;
628
682
  this.runtimeAuth = runtimeAuth;
629
683
  this.avatarId = avatarId;
684
+ this.configMetadata = {};
630
685
  this.inFlightConversations = /* @__PURE__ */ new Map();
631
686
  this.sessionId = sessionId;
632
687
  if (!this.avatarId && typeof transport.getAvatarId === "function") {
@@ -657,243 +712,152 @@ var CloudClient = class {
657
712
  }
658
713
  return DEFAULT_API_BASE_URL;
659
714
  }
660
- async getAuthToken(capability) {
715
+ async getAuthToken() {
661
716
  if (!this.runtimeAuth) return void 0;
662
717
  if (this.tokenRefreshPromise) return this.tokenRefreshPromise;
663
- if (!this.inFlightToken) {
664
- this.inFlightToken = this.runtimeAuth.getToken(capability).then((token) => {
665
- this.activeToken = token;
666
- return token;
667
- }).finally(() => {
668
- this.inFlightToken = void 0;
669
- });
670
- }
671
- return this.inFlightToken;
718
+ this.tokenRefreshPromise = this.runtimeAuth.getToken().then((token) => {
719
+ this.activeToken = token;
720
+ return token;
721
+ }).finally(() => {
722
+ this.tokenRefreshPromise = void 0;
723
+ });
724
+ return this.tokenRefreshPromise;
672
725
  }
673
- async fetchConfig() {
674
- const avatarParam = this.avatarId ? `?avatarId=${encodeURIComponent(this.avatarId)}` : "";
675
- const avatarAndKeyParams = `?projectId=${encodeURIComponent(this.projectId)}&publicKey=${encodeURIComponent(this.publicKey)}${this.avatarId ? `&avatarId=${encodeURIComponent(this.avatarId)}` : ""}`;
676
- const baseUrl = this.getApiBaseUrl();
677
- const resolveAssetUrls = (raw) => {
678
- let canonicalBase = "https://asiyst.com";
679
- try {
680
- if (baseUrl) {
681
- const u = new URL(baseUrl);
682
- canonicalBase = u.origin;
683
- }
684
- } catch {
685
- canonicalBase = "https://asiyst.com";
726
+ getConfigMetadata() {
727
+ return this.configMetadata;
728
+ }
729
+ async fetchConfig(etag, cachedConfig) {
730
+ const response = await this.transport.request({
731
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.runtimeAvatar),
732
+ method: "GET",
733
+ idempotent: true,
734
+ retries: 2,
735
+ headers: {
736
+ Accept: "application/json",
737
+ "X-Asiyst-Public-Key": this.publicKey,
738
+ "X-Asiyst-Project-Id": this.projectId,
739
+ ...this.avatarId ? { "X-Asiyst-Avatar-Id": this.avatarId } : {},
740
+ ...etag ? { "If-None-Match": etag } : {}
686
741
  }
687
- const toAbsolute = (url) => {
688
- if (typeof url === "string" && url.startsWith("/")) {
689
- return new URL(url, canonicalBase).href;
690
- }
691
- return url;
742
+ });
743
+ if (response.status === 304 && cachedConfig) {
744
+ this.configMetadata = {
745
+ etag: response.headers?.get("etag") ?? etag,
746
+ maxAgeMs: 0,
747
+ staleIfErrorMs: 0
692
748
  };
693
- if (raw.avatar && typeof raw.avatar === "object" && !Array.isArray(raw.avatar)) {
694
- const av = { ...raw.avatar };
695
- av.assetUrl = toAbsolute(av.assetUrl);
696
- av.thumbnailUrl = toAbsolute(av.thumbnailUrl);
697
- av.modelUrl = toAbsolute(av.modelUrl);
698
- av.manifestUrl = toAbsolute(av.manifestUrl);
699
- if (Array.isArray(av.animations)) {
700
- av.animations = av.animations.map((item) => {
701
- if (item && typeof item === "object") {
702
- const animObj = item;
703
- return { ...animObj, assetUrl: toAbsolute(animObj.assetUrl) };
704
- }
705
- return item;
706
- });
707
- }
708
- raw.avatar = av;
709
- }
710
- if (raw.config && typeof raw.config === "object" && !Array.isArray(raw.config)) {
711
- const cfg = { ...raw.config };
712
- cfg.assetUrl = toAbsolute(cfg.assetUrl);
713
- cfg.thumbnailUrl = toAbsolute(cfg.thumbnailUrl);
714
- cfg.manifestUrl = toAbsolute(cfg.manifestUrl);
715
- raw.config = cfg;
716
- }
717
- if (raw.manifest && typeof raw.manifest === "object" && !Array.isArray(raw.manifest)) {
718
- const mf = { ...raw.manifest };
719
- mf.assetUrl = toAbsolute(mf.assetUrl);
720
- mf.thumbnailUrl = toAbsolute(mf.thumbnailUrl);
721
- mf.modelUrl = toAbsolute(mf.modelUrl);
722
- raw.manifest = mf;
723
- }
724
- raw.assetUrl = toAbsolute(raw.assetUrl);
725
- raw.thumbnailUrl = toAbsolute(raw.thumbnailUrl);
726
- raw.manifestUrl = toAbsolute(raw.manifestUrl);
727
- if (raw.branding && typeof raw.branding === "object" && !Array.isArray(raw.branding)) {
728
- const br = { ...raw.branding };
729
- br.siteLogoUrl = toAbsolute(br.siteLogoUrl);
730
- raw.branding = br;
731
- }
732
- return raw;
733
- };
734
- let lastError;
735
- try {
736
- const response = await this.runtimeRequest({
737
- path: `/projects/${encodeURIComponent(this.projectId)}/avatar${avatarParam}`,
738
- method: "GET",
739
- idempotent: true
740
- });
741
- if (response.ok && response.data) {
742
- const fullData = response.data && typeof response.data === "object" && !Array.isArray(response.data) ? {
743
- ...response.data,
744
- ...response.data.config && typeof response.data.config === "object" ? response.data.config : {}
745
- } : {};
746
- return normalizeProjectConfig(resolveAssetUrls(fullData));
747
- }
748
- if (response.status === 404) {
749
- lastError = new ConfigurationError(`Project ${this.projectId} or avatar configuration not found`);
750
- }
751
- } catch (err) {
752
- if (err instanceof Error) lastError = err;
749
+ return cachedConfig;
753
750
  }
754
- try {
755
- const runtimeResponse = await this.runtimeRequest({
756
- path: `/api/v1/runtime/avatar${avatarAndKeyParams}`,
757
- method: "GET",
758
- idempotent: true
759
- });
760
- if (runtimeResponse.ok && runtimeResponse.data) {
761
- return normalizeProjectConfig(resolveAssetUrls(runtimeResponse.data));
762
- }
763
- if (runtimeResponse.status === 404) {
764
- lastError = new ConfigurationError(`Avatar ${this.avatarId ?? "active"} not found for project ${this.projectId}`);
765
- }
766
- } catch (err) {
767
- if (err instanceof Error) lastError = err;
768
- }
769
- try {
770
- const webBase = baseUrl.includes("localhost") || baseUrl.includes("127.0.0.1") ? baseUrl.replace(/\/functions\/v1.*$/, "").replace(/\/api\/v1.*$/, "") : "https://asiyst.com";
771
- const fullUrl = `${webBase.replace(/\/$/, "")}/api/v1/runtime/avatar${avatarAndKeyParams}`;
772
- const res = await fetch(fullUrl, {
773
- headers: {
774
- Accept: "application/json",
775
- "x-asiyst-public-key": this.publicKey
776
- }
777
- });
778
- if (res.ok) {
779
- const body = await res.json();
780
- if (body && typeof body === "object") {
781
- return normalizeProjectConfig(resolveAssetUrls(body));
782
- }
783
- } else {
784
- const errorBody = await res.json().catch(() => ({}));
785
- const errObj = errorBody?.error ?? errorBody;
786
- const code = String(errObj?.code ?? "");
787
- const message = String(errObj?.message ?? `HTTP ${res.status}`);
788
- if (res.status === 404) {
789
- throw new ConfigurationError(code === "AVATAR_NOT_FOUND" ? `Requested avatar not found for project ${this.projectId}` : `Project ${this.projectId} not found`);
790
- } else if (res.status === 401 || res.status === 403) {
791
- throw new AuthenticationError("Asiyst credentials unauthorized for this avatar configuration");
792
- } else if (res.status >= 500) {
793
- throw new NetworkError(`Asiyst Cloud avatar service error (${res.status}): ${message}`);
794
- }
795
- }
796
- } catch (err) {
797
- if (err instanceof ConfigurationError || err instanceof AuthenticationError || err instanceof NetworkError) {
798
- throw err;
751
+ if (!response.ok || !response.data) {
752
+ const body = response.data;
753
+ const code = body?.error?.code ?? `HTTP_${response.status}`;
754
+ if (response.status === 401 || response.status === 403) {
755
+ throw new AuthenticationError(body?.error?.message ?? `Asiyst runtime avatar configuration was rejected (${code}).`);
799
756
  }
800
- if (err instanceof Error) lastError = err;
801
- }
802
- if (lastError) {
803
- throw lastError;
804
- }
805
- throw new ConfigurationError(`Failed to resolve avatar configuration for project ${this.projectId}`);
757
+ throw new NetworkError(body?.error?.message ?? `Asiyst runtime avatar configuration is unavailable (${code}).`);
758
+ }
759
+ const data = response.data;
760
+ if (data.success !== true || data.projectId !== this.projectId || typeof data.avatarId !== "string" || !data.config || typeof data.config !== "object" || Array.isArray(data.config)) {
761
+ throw new ConfigurationError("Asiyst returned an invalid runtime configuration response.");
762
+ }
763
+ const rawConfig = data.config;
764
+ const rawAvatar = data.avatar && typeof data.avatar === "object" ? data.avatar : {};
765
+ const manifest = data.manifest && typeof data.manifest === "object" ? data.manifest : {};
766
+ const modelFormat = [data.format, data.modelFormat, rawConfig.modelFormat, rawAvatar.modelFormat].find((format) => typeof format === "string");
767
+ if (modelFormat && modelFormat !== "fbx" && modelFormat !== "glb") {
768
+ throw new ConfigurationError(`Asiyst returned an unsupported avatar format: ${modelFormat}.`);
769
+ }
770
+ 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;
771
+ const animations = Array.isArray(rawConfig.animations) ? rawConfig.animations : Array.isArray(data.animations) ? data.animations : Array.isArray(rawAvatar.animations) ? rawAvatar.animations : [];
772
+ const revision = typeof data.configRevision === "string" ? data.configRevision : typeof data.publishedVersionId === "string" ? data.publishedVersionId : "0";
773
+ const version = Number.parseInt(revision, 10);
774
+ const config = normalizeProjectConfig({
775
+ ...rawConfig,
776
+ avatarId: data.avatarId,
777
+ avatarName: typeof rawAvatar.name === "string" ? rawAvatar.name : rawConfig.avatarName,
778
+ assetUrl,
779
+ modelFormat,
780
+ publishedVersion: typeof data.publishedVersionId === "string" ? data.publishedVersionId : revision,
781
+ version: Number.isFinite(version) ? version : 0,
782
+ animations,
783
+ theme: rawConfig.theme ?? rawAvatar.theme,
784
+ personality: rawConfig.personality,
785
+ behavior: rawConfig.behavior ?? rawAvatar.behavior,
786
+ maxMessageChars: API_LIMITS.maxMessageChars
787
+ });
788
+ this.configMetadata = {
789
+ etag: response.headers?.get("etag") ?? void 0,
790
+ maxAgeMs: 0,
791
+ staleIfErrorMs: 0
792
+ };
793
+ return config;
806
794
  }
807
795
  async heartbeat(metadata) {
808
- let response = await this.runtimeRequest({
809
- path: "/sdk/heartbeat",
796
+ const response = await this.runtimeRequest({
797
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.runtimeHeartbeat),
810
798
  method: "POST",
811
- idempotent: true,
799
+ canonical: true,
812
800
  body: {
813
- project_id: this.projectId,
814
- public_key: this.publicKey,
815
- sdk_version: SDK_VERSION,
816
- origin: metadata.origin,
817
- environment: metadata.environment,
818
- timestamp: metadata.timestamp
801
+ projectId: this.projectId,
802
+ publicKey: this.publicKey,
803
+ sdkVersion: metadata.sdkVersion,
804
+ environment: metadata.environment
819
805
  }
820
806
  }, "assistant:heartbeat");
821
- if (response.status === 404) {
822
- response = await this.runtimeRequest({
823
- path: "/api/v1/sdk/heartbeat",
824
- method: "POST",
825
- idempotent: true,
826
- body: {
827
- project_id: this.projectId,
828
- public_key: this.publicKey,
829
- sdk_version: SDK_VERSION,
830
- origin: metadata.origin,
831
- environment: metadata.environment,
832
- timestamp: metadata.timestamp
833
- }
834
- }, "assistant:heartbeat");
835
- }
836
- const body = response.data && typeof response.data === "object" && !Array.isArray(response.data) ? response.data : void 0;
837
- const rawStatus = body?.status ?? body?.connectionStatus ?? body?.verificationStatus ?? (body?.verified === true ? "verified" : void 0);
838
- const verificationStatus = rawStatus === "connected" || rawStatus === "verified" || rawStatus === "inactive" || rawStatus === "not_detected" || rawStatus === "error" ? rawStatus : void 0;
839
- const versionOutdated = body?.versionOutdated === true || body?.sdkVersionOutdated === true || rawStatus === "outdated";
807
+ const body = response.data;
808
+ const validResponse = body?.success === true && body.data?.connected === true && body.data.projectId === this.projectId && typeof body.data.versionOutdated === "boolean";
840
809
  return {
841
- ok: response.ok && (verificationStatus === void 0 || verificationStatus === "connected" || verificationStatus === "verified"),
842
- status: response.status,
843
- verificationStatus,
844
- versionOutdated
810
+ ok: response.ok && response.status === 202 && validResponse,
811
+ status: response.status
845
812
  };
846
813
  }
847
814
  async registerInstallation(registration) {
848
- let response = await this.transport.request({
849
- path: "/sdk/installations/register",
815
+ const response = await this.transport.request({
816
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.installationRegister),
850
817
  method: "POST",
851
- body: registration,
852
- idempotent: true,
853
- sessionId: this.sessionId
818
+ headers: {
819
+ Accept: "application/json",
820
+ "Content-Type": "application/json",
821
+ "X-Asiyst-SDK-Version": registration.sdkVersion
822
+ },
823
+ body: {
824
+ projectId: registration.projectId,
825
+ publicKey: registration.publicKey,
826
+ installationId: registration.installationId,
827
+ origin: registration.origin,
828
+ environment: registration.environment,
829
+ sdkVersion: registration.sdkVersion
830
+ }
854
831
  });
855
- if (response.status === 404) {
856
- response = await this.transport.request({
857
- path: "/api/v1/sdk/installations/register",
858
- method: "POST",
859
- body: registration,
860
- idempotent: true,
861
- sessionId: this.sessionId
862
- });
863
- }
864
- if (!response.ok) {
865
- throw new NetworkError(`SDK installation registration failed (${response.status}).`);
832
+ const body = response.data;
833
+ if (!response.ok || body?.success !== true || body.data?.registered !== true || typeof body.data.installationId !== "string" || body.data.projectId !== registration.projectId || body.data.status === "revoked") {
834
+ const error = response.data && typeof response.data === "object" ? response.data.error : void 0;
835
+ if (response.status === 403 || body?.data?.status === "revoked") {
836
+ throw new AuthenticationError(error?.message ?? `SDK installation is not authorized (${error?.code ?? response.status}).`);
837
+ }
838
+ throw new NetworkError(error?.message ?? `SDK installation registration failed (${response.status}).`);
866
839
  }
867
- return response.data ?? {};
840
+ return body;
868
841
  }
869
842
  async requestTask(userText, pageUrl) {
870
- const response = await this.runtimeRequest({
871
- path: "/tasks",
872
- method: "POST",
873
- body: {
874
- projectId: this.projectId,
875
- text: userText,
876
- pageUrl
877
- }
878
- }, "assistant:conversation");
879
- if (!response.ok || !response.data?.task?.id || !Array.isArray(response.data.task.steps)) {
880
- throw new NetworkError("Task planning is unavailable");
881
- }
882
- return response.data.task;
843
+ throw new ConfigurationError("Cloud task planning is not defined by the approved SDK API contract.");
883
844
  }
884
845
  async fetchWorkflow(workflowId) {
885
- const response = await this.runtimeRequest({
886
- path: `/workflows/${encodeURIComponent(workflowId)}`,
887
- method: "GET",
888
- idempotent: true
889
- }, "assistant:conversation");
890
- if (!response.ok || !response.data?.workflow?.id || !Array.isArray(response.data.workflow.steps)) {
891
- throw new NetworkError("Workflow is unavailable");
892
- }
893
- return response.data.workflow;
846
+ throw new ConfigurationError("Cloud workflows are not defined by the approved SDK API contract.");
894
847
  }
895
- async sendConversationMessage(text, pageUrl) {
848
+ async sendConversationMessage(text, pageUrl, maxMessageChars = API_LIMITS.maxMessageChars) {
896
849
  const trimmed = text.trim();
850
+ if (!trimmed) throw new ConfigurationError("Message cannot be empty.");
851
+ if (trimmed.length > maxMessageChars) {
852
+ throw new ConfigurationError(`Message exceeds the ${maxMessageChars}-character limit.`);
853
+ }
854
+ if (pageUrl.length > API_LIMITS.pageUrlMaxChars) {
855
+ throw new ConfigurationError("Page URL exceeds the supported length.");
856
+ }
857
+ const sessionId = this.sessionId ?? newRequestId();
858
+ if (sessionId.length < 16 || sessionId.length > 128 || !/^[A-Za-z0-9_-]+$/.test(sessionId)) {
859
+ throw new ConfigurationError("Visitor session ID must be an opaque 16-128 character identifier.");
860
+ }
897
861
  const dedupeKey2 = `${this.conversationId ?? ""}:${trimmed}:${pageUrl}`;
898
862
  const existing = this.inFlightConversations.get(dedupeKey2);
899
863
  if (existing) {
@@ -901,19 +865,72 @@ var CloudClient = class {
901
865
  }
902
866
  const conversationPromise = (async () => {
903
867
  try {
868
+ const requestConversationId = this.conversationId && isUuid(this.conversationId) ? this.conversationId : void 0;
904
869
  const response = await this.runtimeRequest({
905
- path: "/conversations/messages",
870
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.chat),
906
871
  method: "POST",
907
- body: { projectId: this.projectId, text: trimmed, pageUrl },
908
- conversationId: this.conversationId
872
+ body: {
873
+ projectId: this.projectId,
874
+ text: trimmed,
875
+ ...requestConversationId ? { conversationId: requestConversationId } : {},
876
+ sessionId,
877
+ pageUrl
878
+ }
909
879
  }, "assistant:conversation");
910
- if (!response.ok || !response.data?.message?.text) {
911
- if (response.status === 401 || response.status === 403) {
912
- throw new NetworkError("AI request authorization failed. The project credentials may be inactive, revoked, or inaccessible.");
880
+ if (response.ok && response.data?.success === true) {
881
+ const body = response.data;
882
+ const message = body.message && typeof body.message === "object" ? body.message : void 0;
883
+ const conversationId = body.conversationId;
884
+ const messageText = message?.text ?? body.response ?? body.answer;
885
+ if (body.success !== true || typeof conversationId !== "string" || typeof messageText !== "string" || !messageText.trim() || message && message.role !== "assistant") {
886
+ throw new NetworkError("Asiyst returned an unsupported conversation response.");
913
887
  }
914
- throw new NetworkError("Conversation service is unavailable");
888
+ this.conversationId = conversationId;
889
+ const rawCitations = Array.isArray(body.sources) ? body.sources : [];
890
+ return {
891
+ requestId: typeof body.requestId === "string" ? body.requestId : void 0,
892
+ conversationId,
893
+ message: {
894
+ ...typeof message?.id === "string" ? { id: message.id } : {},
895
+ role: "assistant",
896
+ text: messageText
897
+ },
898
+ citations: rawCitations.flatMap((citation) => {
899
+ if (!citation || typeof citation !== "object") return [];
900
+ const item = citation;
901
+ const sourceId = item.source_id ?? item.id;
902
+ if (typeof sourceId !== "string" || typeof item.title !== "string") return [];
903
+ return [{
904
+ sourceId,
905
+ title: item.title,
906
+ ...typeof item.url === "string" ? { url: item.url } : {}
907
+ }];
908
+ }),
909
+ finishReason: void 0,
910
+ createdAt: void 0
911
+ };
912
+ }
913
+ const errorRecord = response.data && typeof response.data === "object" ? response.data.error : void 0;
914
+ const errorBody = errorRecord && typeof errorRecord === "object" ? errorRecord : void 0;
915
+ const code = typeof errorBody?.code === "string" ? errorBody.code : typeof errorRecord === "string" ? errorRecord : `HTTP_${response.status}`;
916
+ if (response.status === 401 || response.status === 403) {
917
+ throw new AuthenticationError("Asiyst runtime authorization was rejected.");
918
+ }
919
+ if (response.status === 429) {
920
+ throw new NetworkError("The assistant is rate limited. Wait before sending another message.");
921
+ }
922
+ if (response.status === 409) {
923
+ throw new NetworkError(`The conversation request conflicted (${code}); it was not retried.`);
924
+ }
925
+ if (response.status === 504 || code === "AI_PROVIDER_TIMEOUT") {
926
+ throw new NetworkError("The assistant timed out. The request was not retried to avoid duplicate work.");
915
927
  }
916
- return response.data;
928
+ if (code === "assistant_unavailable") {
929
+ throw new NetworkError("The assistant is temporarily unavailable.");
930
+ }
931
+ throw new NetworkError(
932
+ typeof errorBody?.message === "string" ? errorBody.message : typeof response.data?.message === "string" ? response.data.message : "Conversation service is unavailable."
933
+ );
917
934
  } finally {
918
935
  this.inFlightConversations.delete(dedupeKey2);
919
936
  }
@@ -922,63 +939,16 @@ var CloudClient = class {
922
939
  return conversationPromise;
923
940
  }
924
941
  async sendWebsiteMap(snapshot) {
925
- await this.safePost("/website-maps", snapshot);
942
+ throw new ConfigurationError("Website-map upload is not defined by the approved SDK API contract.");
926
943
  }
927
944
  async sendAnalytics(events) {
928
- await this.safePost("/analytics", { events });
945
+ throw new ConfigurationError("Analytics upload is not defined by the approved SDK API contract.");
929
946
  }
930
947
  async sendTelemetryEvent(eventType, metadata = {}) {
931
- try {
932
- const origin = typeof window !== "undefined" ? window.location.origin : void 0;
933
- const installationId = this.runtimeAuth ? this.runtimeAuth.options?.installationId : void 0;
934
- const sanitizedMeta = {
935
- sdkVersion: SDK_VERSION
936
- };
937
- for (const [key, val] of Object.entries(metadata)) {
938
- if (/(token|secret|cookie|session|api.?key|password|bearer|authorization)/i.test(key)) {
939
- continue;
940
- }
941
- if (typeof val === "string") {
942
- sanitizedMeta[key] = sanitizeText(val, 512);
943
- } else if (typeof val === "number" || typeof val === "boolean") {
944
- sanitizedMeta[key] = val;
945
- } else if (val && typeof val === "object" && !Array.isArray(val)) {
946
- sanitizedMeta[key] = val;
947
- }
948
- }
949
- const payload = {
950
- projectId: this.projectId,
951
- publicKey: this.publicKey,
952
- eventType,
953
- installationId,
954
- origin,
955
- metadata: sanitizedMeta
956
- };
957
- const baseUrl = this.getApiBaseUrl();
958
- 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";
959
- await fetch(targetUrl, {
960
- method: "POST",
961
- headers: {
962
- "Content-Type": "application/json",
963
- Accept: "application/json",
964
- "x-asiyst-public-key": this.publicKey
965
- },
966
- body: JSON.stringify(payload)
967
- });
968
- } catch {
969
- }
948
+ throw new ConfigurationError("Telemetry upload is not defined by the approved SDK API contract.");
970
949
  }
971
950
  async sendTaskUpdate(taskId, status, stepId) {
972
- await this.safePost(`/tasks/${encodeURIComponent(taskId)}/events`, {
973
- status,
974
- stepId
975
- });
976
- }
977
- async safePost(path, body) {
978
- try {
979
- await this.runtimeRequest({ path, method: "POST", body, idempotent: true }, "assistant:telemetry");
980
- } catch {
981
- }
951
+ throw new ConfigurationError("Cloud task updates are not defined by the approved SDK API contract.");
982
952
  }
983
953
  async runtimeRequest(request, capability = "assistant:config") {
984
954
  const fullRequest = {
@@ -987,14 +957,32 @@ var CloudClient = class {
987
957
  conversationId: request.conversationId ?? this.conversationId
988
958
  };
989
959
  if (!this.runtimeAuth) {
960
+ if (capability === "assistant:conversation" || capability === "assistant:heartbeat") {
961
+ throw new AuthenticationError("AI request authorization failed because no runtime token is available.");
962
+ }
990
963
  return this.transport.request(fullRequest);
991
964
  }
992
- let token = await this.getAuthToken(capability);
993
- let response = await this.transport.request({ ...fullRequest, authorizationToken: token });
965
+ let token = await this.getAuthToken();
966
+ const withToken = (value) => {
967
+ const headers = new Headers({
968
+ Accept: "application/json",
969
+ "Content-Type": "application/json"
970
+ });
971
+ if (fullRequest.headers) {
972
+ new Headers(fullRequest.headers).forEach((headerValue, key) => headers.set(key, headerValue));
973
+ }
974
+ if (value) headers.set("Authorization", `Bearer ${value}`);
975
+ return this.transport.request({
976
+ ...fullRequest,
977
+ headers,
978
+ canonical: true
979
+ });
980
+ };
981
+ let response = await withToken(token);
994
982
  if (response.status === 401) {
995
983
  if (!this.tokenRefreshPromise) {
996
984
  this.runtimeAuth.invalidate();
997
- this.tokenRefreshPromise = this.runtimeAuth.getToken(capability).then((newToken) => {
985
+ this.tokenRefreshPromise = this.runtimeAuth.getToken().then((newToken) => {
998
986
  this.activeToken = newToken;
999
987
  return newToken;
1000
988
  }).finally(() => {
@@ -1004,7 +992,7 @@ var CloudClient = class {
1004
992
  });
1005
993
  }
1006
994
  token = await this.tokenRefreshPromise ?? this.activeToken;
1007
- response = await this.transport.request({ ...fullRequest, authorizationToken: token });
995
+ response = await withToken(token);
1008
996
  }
1009
997
  return response;
1010
998
  }
@@ -1071,7 +1059,8 @@ var ConfigCache = class {
1071
1059
  if (parsed.schemaVersion !== CONFIG_SCHEMA_VERSION || parsed.projectId !== projectId) {
1072
1060
  return null;
1073
1061
  }
1074
- if (!ignoreTtl && Date.now() - parsed.fetchedAt > CONFIG_CACHE_TTL_MS) {
1062
+ const maxAgeMs = parsed.maxAgeMs ?? CONFIG_CACHE_TTL_MS;
1063
+ if (!ignoreTtl && Date.now() - parsed.fetchedAt > maxAgeMs) {
1075
1064
  return null;
1076
1065
  }
1077
1066
  return normalizeProjectConfig(parsed.config);
@@ -1101,6 +1090,8 @@ var ConfigCache = class {
1101
1090
  fetchedAt: Date.now(),
1102
1091
  etag: meta?.etag,
1103
1092
  revision: meta?.revision ?? config.version,
1093
+ maxAgeMs: meta?.maxAgeMs,
1094
+ staleIfErrorMs: meta?.staleIfErrorMs,
1104
1095
  config
1105
1096
  };
1106
1097
  this.storage.write("config", JSON.stringify(envelope));
@@ -1142,19 +1133,26 @@ var ConfigManager = class {
1142
1133
  async executeRefresh(_options) {
1143
1134
  const prev = this.current;
1144
1135
  try {
1145
- const remote = await this.cloud.fetchConfig();
1146
- const normalized = normalizeProjectConfig(remote);
1136
+ const cached = this.cache.getEnvelope(this.options.projectId);
1137
+ const normalized = normalizeProjectConfig(await this.cloud.fetchConfig(cached?.etag, cached?.config));
1138
+ const receivedMetadata = this.cloud.getConfigMetadata?.() ?? {};
1139
+ const metadata = {
1140
+ ...receivedMetadata,
1141
+ maxAgeMs: receivedMetadata.maxAgeMs ?? cached?.maxAgeMs,
1142
+ staleIfErrorMs: receivedMetadata.staleIfErrorMs ?? cached?.staleIfErrorMs
1143
+ };
1147
1144
  this.current = normalized;
1148
- this.cache.write(this.options.projectId, normalized);
1145
+ this.cache.write(this.options.projectId, normalized, metadata);
1149
1146
  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);
1150
1147
  if (hasChanged && this.onConfigUpdated) {
1151
1148
  this.onConfigUpdated(normalized, prev);
1152
1149
  }
1153
1150
  return this.current;
1154
1151
  } catch (error) {
1155
- const lastKnownGood = this.cache.read(this.options.projectId, true);
1156
- if (lastKnownGood) {
1157
- this.current = lastKnownGood;
1152
+ const cached = this.cache.getEnvelope(this.options.projectId);
1153
+ const staleIfErrorMs = cached?.staleIfErrorMs ?? API_LIMITS.configStaleIfErrorMs;
1154
+ if (cached && staleIfErrorMs > 0 && Date.now() - cached.fetchedAt <= staleIfErrorMs) {
1155
+ this.current = normalizeProjectConfig(cached.config);
1158
1156
  }
1159
1157
  this.events.emit("asiyst:error", {
1160
1158
  code: "config_refresh_failed",
@@ -1831,7 +1829,7 @@ var CHUNK_TYPE_JSON = 1313821514;
1831
1829
  var CHUNK_TYPE_BIN = 5130562;
1832
1830
  var AssetLoader = class {
1833
1831
  constructor() {
1834
- this.inFlightController = null;
1832
+ this.inFlightControllers = /* @__PURE__ */ new Set();
1835
1833
  this.createdObjectUrls = [];
1836
1834
  this.inFlightLoads = /* @__PURE__ */ new Map();
1837
1835
  this.cachedAssets = /* @__PURE__ */ new Map();
@@ -1841,31 +1839,42 @@ var AssetLoader = class {
1841
1839
  if (!sanitizedUrl) {
1842
1840
  throw new Error("Asset URL is required");
1843
1841
  }
1844
- const cached = this.cachedAssets.get(sanitizedUrl);
1842
+ let parsedUrl;
1843
+ try {
1844
+ parsedUrl = new URL(sanitizedUrl, typeof location === "undefined" ? void 0 : location.href);
1845
+ } catch {
1846
+ throw new Error("Avatar asset URL is invalid");
1847
+ }
1848
+ if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:" || parsedUrl.username || parsedUrl.password) {
1849
+ throw new Error("Avatar asset URL must use HTTP or HTTPS without embedded credentials");
1850
+ }
1851
+ const cacheKey = `${sanitizedUrl}\0${options?.integrity ?? ""}\0${options?.expectedFormat ?? ""}`;
1852
+ const cached = this.cachedAssets.get(cacheKey);
1845
1853
  if (cached) {
1846
1854
  return cached;
1847
1855
  }
1848
- const inFlight = this.inFlightLoads.get(sanitizedUrl);
1856
+ const inFlight = this.inFlightLoads.get(cacheKey);
1849
1857
  if (inFlight) {
1850
1858
  return inFlight;
1851
1859
  }
1852
1860
  const loadPromise = this.performLoad(sanitizedUrl, options);
1853
- this.inFlightLoads.set(sanitizedUrl, loadPromise);
1861
+ this.inFlightLoads.set(cacheKey, loadPromise);
1854
1862
  try {
1855
1863
  const asset = await loadPromise;
1856
- this.cachedAssets.set(sanitizedUrl, asset);
1864
+ this.cachedAssets.set(cacheKey, asset);
1857
1865
  return asset;
1858
1866
  } finally {
1859
- this.inFlightLoads.delete(sanitizedUrl);
1867
+ this.inFlightLoads.delete(cacheKey);
1860
1868
  }
1861
1869
  }
1862
1870
  async performLoad(sanitizedUrl, options) {
1863
1871
  const startTime = Date.now();
1864
- this.inFlightController = new AbortController();
1865
- const abortSignal = options?.signal ? anySignal([this.inFlightController.signal, options.signal]) : this.inFlightController.signal;
1872
+ const controller = new AbortController();
1873
+ this.inFlightControllers.add(controller);
1874
+ const abortSignal = options?.signal ? anySignal([controller.signal, options.signal]) : controller.signal;
1866
1875
  const timeoutMs = options?.timeoutMs ?? 6e4;
1867
1876
  const timeoutId = setTimeout(() => {
1868
- this.inFlightController?.abort();
1877
+ controller.abort();
1869
1878
  }, timeoutMs);
1870
1879
  try {
1871
1880
  const cleanPath = (sanitizedUrl.split("?")[0] ?? "").toLowerCase();
@@ -1939,12 +1948,25 @@ var AssetLoader = class {
1939
1948
  if (arrayBuffer.byteLength < 12) {
1940
1949
  throw new Error("Avatar asset payload is too small to be a valid 3D container");
1941
1950
  }
1951
+ if (options?.integrity) {
1952
+ await verifyIntegrity(arrayBuffer, options.integrity);
1953
+ }
1942
1954
  const headerBytes = new Uint8Array(arrayBuffer, 0, Math.min(256, arrayBuffer.byteLength));
1943
1955
  const headerStr = new TextDecoder("utf-8", { fatal: false }).decode(headerBytes).trim();
1944
1956
  if (/^<!DOCTYPE\s+html/i.test(headerStr) || /^<html/i.test(headerStr)) {
1945
1957
  throw new Error(`Avatar asset payload contains HTML error page instead of binary 3D container from ${sanitizedUrl}`);
1946
1958
  }
1947
- if (isFbxExtension || this.isFbxBuffer(arrayBuffer) || !isGlbExtension && !this.isGlbBuffer(arrayBuffer)) {
1959
+ const hasFbxSignature = this.isFbxBuffer(arrayBuffer);
1960
+ const hasGlbSignature = this.isGlbBuffer(arrayBuffer);
1961
+ const isFbx = hasFbxSignature || !hasGlbSignature && isFbxExtension;
1962
+ const isGlb = hasGlbSignature || !hasFbxSignature && isGlbExtension;
1963
+ if (isFbx && isGlb) {
1964
+ throw new Error("Avatar asset format is ambiguous");
1965
+ }
1966
+ if (isFbx) {
1967
+ if (options?.expectedFormat && options.expectedFormat !== "fbx") {
1968
+ throw new Error(`Avatar asset format mismatch: expected ${options.expectedFormat}, received fbx`);
1969
+ }
1948
1970
  const fbxHeader = this.parseFbxHeader(arrayBuffer);
1949
1971
  const resourcePath = sanitizedUrl.includes("/") ? sanitizedUrl.substring(0, sanitizedUrl.lastIndexOf("/") + 1) : "";
1950
1972
  return {
@@ -1957,6 +1979,12 @@ var AssetLoader = class {
1957
1979
  durationMs: Date.now() - startTime
1958
1980
  };
1959
1981
  }
1982
+ if (!isGlb) {
1983
+ throw new Error("Avatar asset format is unsupported; expected FBX or GLB");
1984
+ }
1985
+ if (options?.expectedFormat && options.expectedFormat !== "glb") {
1986
+ throw new Error(`Avatar asset format mismatch: expected ${options.expectedFormat}, received glb`);
1987
+ }
1960
1988
  const parsedGlb = this.parseGlb(arrayBuffer);
1961
1989
  return {
1962
1990
  format: "glb",
@@ -1969,7 +1997,7 @@ var AssetLoader = class {
1969
1997
  };
1970
1998
  } finally {
1971
1999
  clearTimeout(timeoutId);
1972
- this.inFlightController = null;
2000
+ this.inFlightControllers.delete(controller);
1973
2001
  }
1974
2002
  }
1975
2003
  isFbxBuffer(buffer) {
@@ -2185,10 +2213,8 @@ var AssetLoader = class {
2185
2213
  };
2186
2214
  }
2187
2215
  destroy() {
2188
- if (this.inFlightController) {
2189
- this.inFlightController.abort();
2190
- this.inFlightController = null;
2191
- }
2216
+ for (const controller of this.inFlightControllers) controller.abort();
2217
+ this.inFlightControllers.clear();
2192
2218
  this.inFlightLoads.clear();
2193
2219
  this.cachedAssets.clear();
2194
2220
  if (typeof URL !== "undefined" && typeof URL.revokeObjectURL === "function") {
@@ -2202,6 +2228,20 @@ var AssetLoader = class {
2202
2228
  this.createdObjectUrls.length = 0;
2203
2229
  }
2204
2230
  };
2231
+ async function verifyIntegrity(buffer, integrity) {
2232
+ const [algorithm, expected] = integrity.split("-", 2);
2233
+ if (algorithm !== "sha256" || !expected) {
2234
+ throw new Error("Avatar asset integrity metadata is invalid");
2235
+ }
2236
+ const cryptoApi = globalThis.crypto;
2237
+ if (!cryptoApi?.subtle) return;
2238
+ const digest = new Uint8Array(await cryptoApi.subtle.digest("SHA-256", buffer));
2239
+ let binary = "";
2240
+ for (const byte of digest) binary += String.fromCharCode(byte);
2241
+ if (btoa(binary) !== expected) {
2242
+ throw new Error("Avatar asset integrity verification failed");
2243
+ }
2244
+ }
2205
2245
  function anySignal(signals) {
2206
2246
  const controller = new AbortController();
2207
2247
  for (const sig of signals) {
@@ -2231,6 +2271,7 @@ var FbxRenderer = class {
2231
2271
  this.facing = "right";
2232
2272
  this.currentPose = "idle";
2233
2273
  this.initialRenderCompleted = false;
2274
+ this.baseScale = 1;
2234
2275
  }
2235
2276
  async mount(container, asset, options) {
2236
2277
  const doc = container.ownerDocument;
@@ -2248,13 +2289,17 @@ var FbxRenderer = class {
2248
2289
  throw new Error("WebGLRenderingContext is not available or supported in this browser environment");
2249
2290
  }
2250
2291
  const isMobile = typeof window !== "undefined" && window.innerWidth <= 640;
2251
- const width = options?.width || (isMobile ? 180 : 240);
2252
- const height = options?.height || (isMobile ? 360 : 460);
2292
+ const width = options?.width || (isMobile ? 140 : 190);
2293
+ const height = options?.height || (isMobile ? 280 : 360);
2253
2294
  const dpr = typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1;
2254
2295
  this.canvas.width = Math.round(width * dpr);
2255
2296
  this.canvas.height = Math.round(height * dpr);
2256
2297
  this.canvas.style.width = `${width}px`;
2257
2298
  this.canvas.style.height = `${height}px`;
2299
+ this.canvas.style.pointerEvents = "none";
2300
+ this.canvas.style.border = "none";
2301
+ this.canvas.style.outline = "none";
2302
+ this.canvas.style.boxShadow = "none";
2258
2303
  try {
2259
2304
  this.renderer = new THREE__namespace.WebGLRenderer({
2260
2305
  canvas: this.canvas,
@@ -2281,6 +2326,13 @@ var FbxRenderer = class {
2281
2326
  keyLight.castShadow = true;
2282
2327
  keyLight.shadow.mapSize.width = 512;
2283
2328
  keyLight.shadow.mapSize.height = 512;
2329
+ keyLight.shadow.camera.near = 0.5;
2330
+ keyLight.shadow.camera.far = 15;
2331
+ keyLight.shadow.camera.left = -1.5;
2332
+ keyLight.shadow.camera.right = 1.5;
2333
+ keyLight.shadow.camera.top = 2.5;
2334
+ keyLight.shadow.camera.bottom = -0.5;
2335
+ keyLight.shadow.bias = -5e-4;
2284
2336
  this.scene.add(keyLight);
2285
2337
  const fillLight = new THREE__namespace.DirectionalLight(15459032, 1.2);
2286
2338
  fillLight.position.set(-3, 2, 2);
@@ -2289,7 +2341,13 @@ var FbxRenderer = class {
2289
2341
  rimLight.position.set(0, 4, -3);
2290
2342
  this.scene.add(rimLight);
2291
2343
  const shadowGeo = new THREE__namespace.PlaneGeometry(3, 3);
2292
- const shadowMat = new THREE__namespace.ShadowMaterial({ opacity: 0.15 });
2344
+ const shadowMat = new THREE__namespace.ShadowMaterial({
2345
+ opacity: 0.12,
2346
+ depthWrite: false
2347
+ });
2348
+ shadowMat.polygonOffset = true;
2349
+ shadowMat.polygonOffsetFactor = -1;
2350
+ shadowMat.polygonOffsetUnits = -4;
2293
2351
  const shadowPlane = new THREE__namespace.Mesh(shadowGeo, shadowMat);
2294
2352
  shadowPlane.rotation.x = -Math.PI / 2;
2295
2353
  shadowPlane.position.y = 0;
@@ -2341,14 +2399,18 @@ var FbxRenderer = class {
2341
2399
  rawObject.position.set(-rawCenter.x, -rawBox.min.y, -rawCenter.z);
2342
2400
  const targetVisualHeight = 1.8;
2343
2401
  const targetScale = targetVisualHeight / rawHeight;
2402
+ this.baseScale = targetScale;
2344
2403
  this.modelRoot = new THREE__namespace.Group();
2345
2404
  this.modelRoot.add(rawObject);
2346
2405
  this.modelRoot.scale.setScalar(targetScale);
2347
2406
  this.scene.add(this.modelRoot);
2348
- const visualCenterY = targetVisualHeight * 0.52;
2407
+ const visualCenterY = targetVisualHeight * 0.5;
2349
2408
  const fovRadians = this.camera.fov * Math.PI / 180;
2350
- const fitDist = Math.max(2.4, targetVisualHeight / 2 / Math.tan(fovRadians / 2) * 1.25);
2351
- this.camera.position.set(0, visualCenterY + 0.1, fitDist);
2409
+ const aspect = width / height;
2410
+ const fitDistV = targetVisualHeight * 1.35 / 2 / Math.tan(fovRadians / 2);
2411
+ const fitDistH = 1.1 / 2 / (aspect * Math.tan(fovRadians / 2));
2412
+ const fitDist = Math.max(fitDistV, fitDistH, 2.85);
2413
+ this.camera.position.set(0, visualCenterY, fitDist);
2352
2414
  this.camera.lookAt(0, visualCenterY, 0);
2353
2415
  rawObject.traverse((child) => {
2354
2416
  const mesh = child;
@@ -2357,20 +2419,25 @@ var FbxRenderer = class {
2357
2419
  mesh.receiveShadow = true;
2358
2420
  }
2359
2421
  });
2422
+ options?.metricsTracker?.record("sceneInitComplete");
2360
2423
  this.rawObject = rawObject;
2361
2424
  this.mixer = new THREE__namespace.AnimationMixer(rawObject);
2362
2425
  this.allAnimations = [...modelAnimations];
2363
2426
  const externalAnims = options?.config?.animations || options?.config?.avatar?.animations || [];
2364
2427
  if (externalAnims.length > 0) {
2365
- try {
2366
- await Promise.race([
2367
- this.loadExternalAnimations(externalAnims, options?.config?.animation),
2368
- new Promise((resolve) => setTimeout(resolve, 8e3))
2369
- ]);
2370
- } catch (animErr) {
2371
- if (typeof console !== "undefined" && typeof console.warn === "function") {
2372
- console.warn("[asiyst] External animation loading notice:", animErr);
2428
+ if (modelAnimations.length === 0) {
2429
+ try {
2430
+ await Promise.race([
2431
+ this.loadExternalAnimations(externalAnims, options?.config?.animation),
2432
+ new Promise((resolve) => setTimeout(resolve, 2500))
2433
+ ]);
2434
+ } catch (animErr) {
2435
+ if (typeof console !== "undefined" && typeof console.warn === "function") {
2436
+ console.warn("[asiyst] External animation loading notice:", animErr);
2437
+ }
2373
2438
  }
2439
+ } else {
2440
+ void this.loadExternalAnimations(externalAnims, options?.config?.animation);
2374
2441
  }
2375
2442
  }
2376
2443
  this.startInitialIdleAnimation(options?.config);
@@ -2382,9 +2449,11 @@ var FbxRenderer = class {
2382
2449
  try {
2383
2450
  this.renderer.render(this.scene, this.camera);
2384
2451
  this.initialRenderCompleted = true;
2452
+ options?.metricsTracker?.record("firstRenderedFrame");
2385
2453
  if (this.canvas) {
2386
2454
  this.canvas.style.opacity = "1";
2387
2455
  }
2456
+ options?.metricsTracker?.record("firstVisibleCorrectlyFramed");
2388
2457
  } catch (renderErr) {
2389
2458
  const msg = renderErr instanceof Error ? renderErr.message : String(renderErr);
2390
2459
  throw new Error(`Initial FBX WebGL render failed: ${msg}`);
@@ -2413,53 +2482,29 @@ var FbxRenderer = class {
2413
2482
  if (this.playAnimation(pose)) {
2414
2483
  return;
2415
2484
  }
2416
- if (this.mixer && this.allAnimations.length > 0) {
2417
- let targetClip;
2418
- if (pose === "speak") {
2419
- targetClip = this.allAnimations.find(
2420
- (c) => c.name.toLowerCase().includes("talk") || c.name.toLowerCase().includes("speak")
2421
- );
2422
- } else if (pose === "think") {
2423
- targetClip = this.allAnimations.find(
2424
- (c) => c.name.toLowerCase().includes("think")
2425
- );
2426
- } else {
2427
- targetClip = this.allAnimations.find((c) => c.name.toLowerCase().includes("idle")) || this.animationMetadataList[0]?.clip || this.allAnimations[0];
2428
- }
2429
- if (targetClip) {
2430
- const newAction = this.mixer.clipAction(targetClip);
2431
- if (newAction !== this.currentAction) {
2432
- newAction.reset().fadeIn(0.25).play();
2433
- if (this.currentAction) {
2434
- this.currentAction.fadeOut(0.25);
2435
- }
2436
- this.currentAction = newAction;
2437
- return;
2438
- } else if (!this.currentAction?.isRunning()) {
2439
- this.currentAction?.play();
2440
- return;
2441
- }
2442
- return;
2443
- }
2444
- }
2445
2485
  if (!this.modelRoot) return;
2486
+ this.modelRoot.scale.setScalar(this.baseScale);
2446
2487
  switch (pose) {
2447
2488
  case "point":
2448
- this.modelRoot.rotation.z = -0.15;
2449
- this.modelRoot.rotation.x = 0.08;
2489
+ this.modelRoot.rotation.z = -0.06;
2490
+ this.modelRoot.rotation.x = 0.03;
2450
2491
  break;
2451
2492
  case "think":
2452
- this.modelRoot.rotation.z = 0.12;
2453
- this.modelRoot.rotation.x = -0.1;
2493
+ this.modelRoot.rotation.z = 0.05;
2494
+ this.modelRoot.rotation.x = -0.04;
2454
2495
  break;
2455
2496
  case "speak":
2456
2497
  this.modelRoot.rotation.y = this.facing === "left" ? -0.22 : 0.22;
2457
- this.modelRoot.rotation.x = 0.04;
2498
+ this.modelRoot.rotation.x = 0.03;
2458
2499
  break;
2459
2500
  case "celebrate":
2460
2501
  this.modelRoot.rotation.z = 0;
2461
- this.modelRoot.rotation.x = -0.15;
2462
- this.modelRoot.scale.multiplyScalar(1.05);
2502
+ this.modelRoot.rotation.x = -0.06;
2503
+ break;
2504
+ case "walk":
2505
+ this.modelRoot.rotation.z = 0;
2506
+ this.modelRoot.rotation.x = 0.03;
2507
+ this.modelRoot.rotation.y = this.facing === "left" ? -0.35 : 0.35;
2463
2508
  break;
2464
2509
  default:
2465
2510
  this.modelRoot.rotation.z = 0;
@@ -2481,13 +2526,13 @@ var FbxRenderer = class {
2481
2526
  return true;
2482
2527
  }
2483
2528
  const idleByName = this.animationMetadataList.find(
2484
- (m) => m.name.toLowerCase().includes("idle") || m.clipName && m.clipName.toLowerCase().includes("idle")
2529
+ (m) => m.name.toLowerCase() === "idle" || m.clipName?.toLowerCase() === "idle"
2485
2530
  );
2486
2531
  if (idleByName && this.playAnimation(idleByName.id || idleByName.name)) {
2487
2532
  return true;
2488
2533
  }
2489
2534
  const embeddedIdle = this.allAnimations.find(
2490
- (c) => c.name.toLowerCase().includes("idle")
2535
+ (c) => c.name.toLowerCase() === "idle"
2491
2536
  );
2492
2537
  if (embeddedIdle) {
2493
2538
  const action = this.mixer.clipAction(embeddedIdle);
@@ -2498,69 +2543,65 @@ var FbxRenderer = class {
2498
2543
  }
2499
2544
  return true;
2500
2545
  }
2501
- if (this.animationMetadataList.length > 0) {
2502
- const firstMeta = this.animationMetadataList[0];
2503
- if (this.playAnimation(firstMeta.id || firstMeta.name)) {
2504
- return true;
2505
- }
2506
- }
2507
- if (this.allAnimations.length > 0) {
2508
- const firstClip = this.allAnimations[0];
2509
- const action = this.mixer.clipAction(firstClip);
2510
- if (this.currentAction !== action) {
2511
- action.reset().fadeIn(0.25).play();
2512
- if (this.currentAction) this.currentAction.fadeOut(0.25);
2513
- this.currentAction = action;
2514
- }
2515
- return true;
2516
- }
2517
2546
  return false;
2518
2547
  }
2519
2548
  async loadExternalAnimations(animations, targetAnimationName) {
2520
2549
  if (!this.rawObject || !this.mixer) return;
2521
- for (const anim of animations) {
2522
- if (!anim.assetUrl) continue;
2523
- try {
2524
- const loaded = await this.assetLoader.load(anim.assetUrl);
2525
- let extractedClips = [];
2526
- if (loaded.format === "fbx") {
2527
- const loader = new FBXLoader_js.FBXLoader();
2528
- if (loaded.resourcePath) {
2529
- loader.setResourcePath(loaded.resourcePath);
2530
- }
2531
- const parsed = loader.parse(loaded.buffer, loaded.resourcePath || "");
2532
- extractedClips = parsed.animations || [];
2533
- } else if (loaded.format === "glb") {
2534
- const loader = new GLTFLoader_js.GLTFLoader();
2535
- const gltf = await new Promise((resolve, reject) => {
2536
- const glbBuffer = loaded.bin.buffer.slice(
2537
- loaded.bin.byteOffset,
2538
- loaded.bin.byteOffset + loaded.bin.byteLength
2539
- );
2540
- loader.parse(glbBuffer, loaded.url, resolve, reject);
2541
- });
2542
- extractedClips = gltf.animations || [];
2543
- }
2544
- for (const rawClip of extractedClips) {
2545
- const retargeted = this.retargetClip(rawClip, this.rawObject);
2546
- if (!retargeted) continue;
2547
- retargeted.name = anim.clipName || anim.name || rawClip.name;
2548
- this.allAnimations.push(retargeted);
2549
- this.animationMetadataList.push({
2550
- id: anim.id,
2551
- name: anim.name,
2552
- intent: anim.intent,
2553
- clipName: anim.clipName,
2554
- loopMode: anim.loopMode,
2555
- clip: retargeted
2556
- });
2557
- }
2558
- } catch (err) {
2559
- if (typeof console !== "undefined" && typeof console.warn === "function") {
2560
- const msg = err instanceof Error ? err.message : String(err);
2561
- console.warn(`[asiyst] Failed to load external animation "${anim.name}": ${msg}`);
2562
- }
2550
+ const pending = animations.filter(
2551
+ (anim) => {
2552
+ if (!anim.assetUrl) return false;
2553
+ const key = (anim.id || anim.name).toLowerCase();
2554
+ return !this.animationMetadataList.some(
2555
+ (m) => m.id && m.id.toLowerCase() === key || m.name.toLowerCase() === key
2556
+ );
2563
2557
  }
2558
+ );
2559
+ if (pending.length > 0) {
2560
+ await Promise.allSettled(
2561
+ pending.map(async (anim) => {
2562
+ try {
2563
+ const loaded = await this.assetLoader.load(anim.assetUrl, { integrity: anim.integrity });
2564
+ let extractedClips = [];
2565
+ if (loaded.format === "fbx") {
2566
+ const loader = new FBXLoader_js.FBXLoader();
2567
+ if (loaded.resourcePath) {
2568
+ loader.setResourcePath(loaded.resourcePath);
2569
+ }
2570
+ const parsed = loader.parse(loaded.buffer, loaded.resourcePath || "");
2571
+ extractedClips = parsed.animations || [];
2572
+ } else if (loaded.format === "glb") {
2573
+ const loader = new GLTFLoader_js.GLTFLoader();
2574
+ const gltf = await new Promise((resolve, reject) => {
2575
+ const glbBuffer = loaded.bin.buffer.slice(
2576
+ loaded.bin.byteOffset,
2577
+ loaded.bin.byteOffset + loaded.bin.byteLength
2578
+ );
2579
+ loader.parse(glbBuffer, loaded.url, resolve, reject);
2580
+ });
2581
+ extractedClips = gltf.animations || [];
2582
+ }
2583
+ for (const rawClip of extractedClips) {
2584
+ const retargeted = this.retargetClip(rawClip, this.rawObject);
2585
+ if (!retargeted) continue;
2586
+ retargeted.name = anim.clipName || anim.name || rawClip.name;
2587
+ this.allAnimations.push(retargeted);
2588
+ this.animationMetadataList.push({
2589
+ id: anim.id,
2590
+ name: anim.name,
2591
+ intent: anim.intent,
2592
+ clipName: anim.clipName,
2593
+ loopMode: anim.loopMode,
2594
+ clip: retargeted
2595
+ });
2596
+ }
2597
+ } catch (err) {
2598
+ if (typeof console !== "undefined" && typeof console.warn === "function") {
2599
+ const msg = err instanceof Error ? err.message : String(err);
2600
+ console.warn(`[asiyst] Failed to load external animation "${anim.name}": ${msg}`);
2601
+ }
2602
+ }
2603
+ })
2604
+ );
2564
2605
  }
2565
2606
  if (this.currentPose === "idle" || targetAnimationName) {
2566
2607
  this.startInitialIdleAnimation({ animation: targetAnimationName });
@@ -2645,13 +2686,13 @@ var FbxRenderer = class {
2645
2686
  clip = this.allAnimations.find((c) => c.name.toLowerCase() === query);
2646
2687
  }
2647
2688
  if (!clip) {
2648
- clip = this.allAnimations.find((c) => c.name.toLowerCase().includes(query));
2689
+ clip = this.allAnimations.find((c) => c.name.toLowerCase() === query);
2649
2690
  }
2650
2691
  if (!clip) {
2651
2692
  return false;
2652
2693
  }
2653
2694
  const action = this.mixer.clipAction(clip);
2654
- const effectiveLoop = loopMode || matched?.loopMode || "repeat";
2695
+ const effectiveLoop = (loopMode || matched?.loopMode || "loop").toLowerCase();
2655
2696
  if (effectiveLoop === "once") {
2656
2697
  action.setLoop(THREE__namespace.LoopOnce, 1);
2657
2698
  action.clampWhenFinished = true;
@@ -2697,9 +2738,17 @@ var FbxRenderer = class {
2697
2738
  }
2698
2739
  startLoop() {
2699
2740
  if (typeof requestAnimationFrame === "undefined") return;
2741
+ if (this.animFrameId !== null && typeof cancelAnimationFrame !== "undefined") {
2742
+ cancelAnimationFrame(this.animFrameId);
2743
+ this.animFrameId = null;
2744
+ }
2700
2745
  this.lastTime = typeof performance !== "undefined" ? performance.now() : Date.now();
2701
2746
  const tick = (now) => {
2702
2747
  if (!this.renderer || !this.scene || !this.camera) return;
2748
+ if (typeof document !== "undefined" && document.hidden) {
2749
+ this.animFrameId = requestAnimationFrame(tick);
2750
+ return;
2751
+ }
2703
2752
  const current = now || (typeof performance !== "undefined" ? performance.now() : Date.now());
2704
2753
  const delta = Math.min(Math.max((current - this.lastTime) / 1e3, 0), 0.1);
2705
2754
  this.lastTime = current;
@@ -2769,14 +2818,23 @@ var FbxRenderer = class {
2769
2818
  handleResize() {
2770
2819
  if (!this.canvas || !this.renderer || !this.camera) return;
2771
2820
  const isMobile = typeof window !== "undefined" && window.innerWidth <= 640;
2772
- const width = isMobile ? 180 : 240;
2773
- const height = isMobile ? 360 : 460;
2821
+ const width = isMobile ? 140 : 190;
2822
+ const height = isMobile ? 280 : 360;
2774
2823
  const dpr = typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1;
2775
2824
  this.canvas.width = Math.round(width * dpr);
2776
2825
  this.canvas.height = Math.round(height * dpr);
2777
2826
  this.canvas.style.width = `${width}px`;
2778
2827
  this.canvas.style.height = `${height}px`;
2779
- this.camera.aspect = width / height;
2828
+ const aspect = width / height;
2829
+ this.camera.aspect = aspect;
2830
+ const targetVisualHeight = 1.8;
2831
+ const visualCenterY = targetVisualHeight * 0.5;
2832
+ const fovRadians = this.camera.fov * Math.PI / 180;
2833
+ const fitDistV = targetVisualHeight * 1.35 / 2 / Math.tan(fovRadians / 2);
2834
+ const fitDistH = 1.1 / 2 / (aspect * Math.tan(fovRadians / 2));
2835
+ const fitDist = Math.max(fitDistV, fitDistH, 2.85);
2836
+ this.camera.position.set(0, visualCenterY, fitDist);
2837
+ this.camera.lookAt(0, visualCenterY, 0);
2780
2838
  this.camera.updateProjectionMatrix();
2781
2839
  this.renderer.setPixelRatio(Math.min(dpr, 2));
2782
2840
  this.renderer.setSize(width, height, false);
@@ -2801,7 +2859,7 @@ var AVATAR_CSS = `
2801
2859
  flex-direction: column;
2802
2860
  align-items: center;
2803
2861
  gap: 4px;
2804
- pointer-events: auto;
2862
+ pointer-events: none;
2805
2863
  user-select: none;
2806
2864
  }
2807
2865
  .asiyst-avatar.asiyst-animate {
@@ -2812,11 +2870,27 @@ var AVATAR_CSS = `
2812
2870
  place-items: center;
2813
2871
  position: relative;
2814
2872
  cursor: pointer;
2815
- border: none;
2873
+ border: 0 !important;
2816
2874
  padding: 0;
2817
- outline: none;
2818
- background: transparent;
2875
+ margin: 0;
2876
+ outline: none !important;
2877
+ background: transparent !important;
2878
+ box-shadow: none !important;
2819
2879
  overflow: visible;
2880
+ -webkit-appearance: none;
2881
+ appearance: none;
2882
+ -webkit-tap-highlight-color: transparent;
2883
+ }
2884
+ .asiyst-figure:focus,
2885
+ .asiyst-figure:focus-visible,
2886
+ .asiyst-figure:active {
2887
+ outline: none !important;
2888
+ border: 0 !important;
2889
+ box-shadow: none !important;
2890
+ }
2891
+ .asiyst-figure::-moz-focus-inner {
2892
+ border: 0 !important;
2893
+ padding: 0;
2820
2894
  }
2821
2895
  .asiyst-figure.asiyst-compact-launcher {
2822
2896
  border-radius: 28px;
@@ -2824,20 +2898,24 @@ var AVATAR_CSS = `
2824
2898
  font: 700 14px/1.2 system-ui, sans-serif;
2825
2899
  box-shadow: 0 10px 30px rgba(15, 23, 42, 0.28);
2826
2900
  overflow: hidden;
2827
- background: #2563eb;
2901
+ background: #2563eb !important;
2902
+ pointer-events: auto;
2828
2903
  }
2829
2904
  .asiyst-figure.asiyst-3d-active {
2830
- width: 240px !important;
2831
- height: 460px !important;
2905
+ width: 190px !important;
2906
+ height: 360px !important;
2832
2907
  background: transparent !important;
2908
+ border: 0 !important;
2833
2909
  border-radius: 0 !important;
2834
2910
  box-shadow: none !important;
2911
+ outline: none !important;
2835
2912
  overflow: visible !important;
2913
+ pointer-events: none;
2836
2914
  }
2837
2915
  @media (max-width: 640px) {
2838
2916
  .asiyst-figure.asiyst-3d-active {
2839
- width: 180px !important;
2840
- height: 360px !important;
2917
+ width: 140px !important;
2918
+ height: 280px !important;
2841
2919
  }
2842
2920
  }
2843
2921
  .asiyst-avatar-viewport {
@@ -2846,16 +2924,23 @@ var AVATAR_CSS = `
2846
2924
  height: 100%;
2847
2925
  display: grid;
2848
2926
  place-items: center;
2927
+ border: 0 !important;
2928
+ outline: none !important;
2929
+ background: transparent !important;
2849
2930
  border-radius: inherit;
2850
2931
  overflow: visible;
2851
- pointer-events: auto;
2932
+ pointer-events: none;
2852
2933
  }
2853
2934
  .asiyst-avatar-canvas {
2854
2935
  width: 100%;
2855
2936
  height: 100%;
2856
2937
  object-fit: contain;
2857
2938
  display: block;
2858
- pointer-events: auto;
2939
+ border: 0 !important;
2940
+ outline: none !important;
2941
+ background: transparent !important;
2942
+ box-shadow: none !important;
2943
+ pointer-events: none;
2859
2944
  }
2860
2945
  .asiyst-avatar-graphic {
2861
2946
  width: 100%;
@@ -3005,6 +3090,9 @@ var CssAvatarRenderer = class {
3005
3090
  this.isAssetLoadedFlag = false;
3006
3091
  this.isFallbackFlag = false;
3007
3092
  }
3093
+ setMetricsTracker(tracker) {
3094
+ this.metricsTracker = tracker;
3095
+ }
3008
3096
  mount(container, config) {
3009
3097
  const doc = container.ownerDocument;
3010
3098
  const style = doc.createElement("style");
@@ -3141,7 +3229,10 @@ var CssAvatarRenderer = class {
3141
3229
  this.chatActionBtn.style.display = open ? "none" : "inline-flex";
3142
3230
  }
3143
3231
  }
3144
- async loadAsset(config) {
3232
+ async loadAsset(config, metricsTracker) {
3233
+ if (metricsTracker) {
3234
+ this.metricsTracker = metricsTracker;
3235
+ }
3145
3236
  const assetUrl = config.assetUrl ?? config.thumbnailUrl;
3146
3237
  if (!assetUrl) {
3147
3238
  this.renderState = "idle";
@@ -3173,8 +3264,20 @@ var CssAvatarRenderer = class {
3173
3264
  this.renderLoader();
3174
3265
  }
3175
3266
  try {
3176
- const asset = await this.assetLoader.load(assetUrl, { timeoutMs: 6e4 });
3267
+ this.metricsTracker?.record("assetRequestStart");
3268
+ const asset = await this.assetLoader.load(assetUrl, {
3269
+ timeoutMs: 6e4,
3270
+ integrity: config.assetIntegrity,
3271
+ expectedFormat: config.assetUrl ? config.modelFormat : void 0
3272
+ });
3273
+ this.metricsTracker?.record("assetDownloadComplete");
3274
+ const byteSize = asset.buffer?.byteLength ?? asset.bin?.byteLength ?? asset.size;
3275
+ this.metricsTracker?.setAssetInfo({
3276
+ format: asset.format,
3277
+ byteSize: typeof byteSize === "number" ? byteSize : void 0
3278
+ });
3177
3279
  await this.renderLoadedAsset(asset, config);
3280
+ this.metricsTracker?.record("parseAndDecodeComplete");
3178
3281
  this.renderState = "ready";
3179
3282
  this.isAssetLoadedFlag = true;
3180
3283
  this.isFallbackFlag = false;
@@ -3238,14 +3341,20 @@ var CssAvatarRenderer = class {
3238
3341
  }
3239
3342
  if (asset.format === "fbx" || asset.format === "glb") {
3240
3343
  const isMobile = typeof window !== "undefined" && window.innerWidth <= 640;
3241
- const width = isMobile ? 180 : 240;
3242
- const height = isMobile ? 360 : 460;
3344
+ const width = isMobile ? 140 : 190;
3345
+ const height = isMobile ? 280 : 360;
3243
3346
  this.fbxRenderer = new FbxRenderer();
3244
3347
  this.renderMetrics = await this.fbxRenderer.mount(this.viewport, asset, {
3245
3348
  accentColor: this.accentColor,
3246
3349
  config,
3247
3350
  width,
3248
- height
3351
+ height,
3352
+ metricsTracker: this.metricsTracker
3353
+ });
3354
+ this.metricsTracker?.setAssetInfo({
3355
+ meshCount: this.renderMetrics.meshCount,
3356
+ vertexCount: this.renderMetrics.vertexCount,
3357
+ animationCount: this.renderMetrics.animationCount
3249
3358
  });
3250
3359
  this.fbxRenderer.setFacing(this.facing);
3251
3360
  this.fbxRenderer.setPose(this.pose);
@@ -3261,7 +3370,10 @@ var CssAvatarRenderer = class {
3261
3370
  const thumb = typeof asset.manifest.thumbnailUrl === "string" ? asset.manifest.thumbnailUrl : void 0;
3262
3371
  const modelUrl = typeof asset.manifest.assetUrl === "string" ? asset.manifest.assetUrl : typeof asset.manifest.modelUrl === "string" ? asset.manifest.modelUrl : void 0;
3263
3372
  if (modelUrl) {
3264
- const subAsset = await this.assetLoader.load(modelUrl, { timeoutMs: 6e4 });
3373
+ const subAsset = await this.assetLoader.load(modelUrl, {
3374
+ timeoutMs: 6e4,
3375
+ expectedFormat: config.modelFormat
3376
+ });
3265
3377
  await this.renderLoadedAsset(subAsset, config);
3266
3378
  } else if (thumb) {
3267
3379
  this.viewport.replaceChildren();
@@ -3336,7 +3448,7 @@ var CssAvatarRenderer = class {
3336
3448
  getSize() {
3337
3449
  if (this.isAssetLoadedFlag || this.has3dAssetConfigured) {
3338
3450
  const isMobile = typeof window !== "undefined" && window.innerWidth <= 640;
3339
- return { width: isMobile ? 180 : 240, height: isMobile ? 390 : 490 };
3451
+ return { width: isMobile ? 140 : 190, height: isMobile ? 310 : 390 };
3340
3452
  }
3341
3453
  return { width: this.size, height: this.size + 28 };
3342
3454
  }
@@ -4055,11 +4167,10 @@ function transition(from, to) {
4055
4167
 
4056
4168
  // src/task/TaskEngine.ts
4057
4169
  var TaskEngine = class {
4058
- constructor(interaction, events, analytics, cloud) {
4170
+ constructor(interaction, events, analytics) {
4059
4171
  this.interaction = interaction;
4060
4172
  this.events = events;
4061
4173
  this.analytics = analytics;
4062
- this.cloud = cloud;
4063
4174
  this.status = TaskStatus.Idle;
4064
4175
  this.abort = false;
4065
4176
  }
@@ -4075,7 +4186,6 @@ var TaskEngine = class {
4075
4186
  this.events.emit("asiyst:task:started", { taskId: task.id });
4076
4187
  this.analytics.track("task_started", { taskId: task.id });
4077
4188
  this.analytics.track("guide_started", { taskId: task.id });
4078
- void this.cloud.sendTaskUpdate(task.id, this.status);
4079
4189
  try {
4080
4190
  for (const [index, step] of task.steps.entries()) {
4081
4191
  if (this.abort) {
@@ -4110,13 +4220,11 @@ var TaskEngine = class {
4110
4220
  }
4111
4221
  this.move(TaskStatus.StepCompleted);
4112
4222
  this.events.emit("asiyst:task:step-completed", { taskId: task.id, stepId: step.id });
4113
- void this.cloud.sendTaskUpdate(task.id, this.status, step.id);
4114
4223
  }
4115
4224
  this.move(TaskStatus.TaskCompleted);
4116
4225
  this.events.emit("asiyst:task:completed", { taskId: task.id });
4117
4226
  this.analytics.track("task_completed", { taskId: task.id });
4118
4227
  this.analytics.track("guide_completed", { taskId: task.id });
4119
- void this.cloud.sendTaskUpdate(task.id, this.status);
4120
4228
  this.move(TaskStatus.Idle);
4121
4229
  return TaskStatus.TaskCompleted;
4122
4230
  } catch (error) {
@@ -4191,14 +4299,15 @@ var ConversationPanel = class {
4191
4299
  this.onToggle = onToggle;
4192
4300
  this.conversationId = "";
4193
4301
  this.openState = false;
4302
+ this.submitting = false;
4194
4303
  const doc = root.ownerDocument;
4195
4304
  this.style = doc.createElement("style");
4196
4305
  this.style.textContent = `
4197
4306
  .asiyst-panel {
4198
4307
  position: fixed;
4199
- right: 256px;
4308
+ right: 216px;
4200
4309
  bottom: 20px;
4201
- width: min(380px, calc(100vw - 280px));
4310
+ width: min(380px, calc(100vw - 240px));
4202
4311
  max-height: min(560px, 75vh);
4203
4312
  background: #ffffff;
4204
4313
  color: #0f172a;
@@ -4288,6 +4397,9 @@ var ConversationPanel = class {
4288
4397
  getConversationId() {
4289
4398
  return this.conversationId;
4290
4399
  }
4400
+ setConversationId(conversationId) {
4401
+ this.conversationId = conversationId;
4402
+ }
4291
4403
  open() {
4292
4404
  if (!this.conversationId) {
4293
4405
  this.conversationId = `conv_${Date.now().toString(36)}`;
@@ -4302,22 +4414,51 @@ var ConversationPanel = class {
4302
4414
  this.panel.hidden = true;
4303
4415
  this.onToggle(false);
4304
4416
  }
4305
- append(role, text) {
4417
+ append(role, text, citations = []) {
4306
4418
  const item = this.log.ownerDocument.createElement("div");
4307
4419
  item.className = "asiyst-msg";
4308
4420
  item.setAttribute("data-role", role);
4309
4421
  renderSafeText(item, text);
4422
+ for (const citation of citations) {
4423
+ if (!citation.url) continue;
4424
+ let url;
4425
+ try {
4426
+ url = new URL(citation.url);
4427
+ } catch {
4428
+ continue;
4429
+ }
4430
+ if (url.protocol !== "https:") continue;
4431
+ const link = this.log.ownerDocument.createElement("a");
4432
+ link.href = url.href;
4433
+ link.rel = "noopener noreferrer";
4434
+ link.target = "_blank";
4435
+ link.textContent = sanitizeText(citation.title, 160);
4436
+ const wrapper = this.log.ownerDocument.createElement("div");
4437
+ wrapper.appendChild(link);
4438
+ item.appendChild(wrapper);
4439
+ }
4310
4440
  this.log.appendChild(item);
4311
4441
  this.log.scrollTop = this.log.scrollHeight;
4312
4442
  }
4313
4443
  async submit() {
4444
+ if (this.submitting) return;
4314
4445
  const text = sanitizeText(this.input.value);
4315
4446
  if (!text) {
4316
4447
  return;
4317
4448
  }
4449
+ this.submitting = true;
4450
+ this.input.disabled = true;
4451
+ this.form.querySelector("button")?.setAttribute("disabled", "true");
4318
4452
  this.input.value = "";
4319
4453
  this.append("user", text);
4320
- await this.onSubmit(text);
4454
+ try {
4455
+ await this.onSubmit(text);
4456
+ } finally {
4457
+ this.submitting = false;
4458
+ this.input.disabled = false;
4459
+ this.form.querySelector("button")?.removeAttribute("disabled");
4460
+ this.input.focus();
4461
+ }
4321
4462
  }
4322
4463
  destroy() {
4323
4464
  if (this.keydownListener) {
@@ -4380,19 +4521,15 @@ function loadOrCreateInstallationId(projectId) {
4380
4521
  }
4381
4522
 
4382
4523
  // src/communication/RuntimeAuth.ts
4383
- var RUNTIME_AUDIENCE = "asiyst-sdk-runtime";
4384
- var RUNTIME_CAPABILITIES = [
4385
- "assistant:config",
4386
- "assistant:conversation",
4387
- "assistant:telemetry",
4388
- "assistant:heartbeat"
4389
- ];
4390
4524
  var RuntimeAuth = class {
4391
4525
  constructor(options) {
4392
4526
  this.options = options;
4393
4527
  }
4394
- async getToken(capability) {
4395
- if (this.token && this.isUsable(this.token) && this.token.capabilities.has(capability)) {
4528
+ setInstallationId(installationId) {
4529
+ this.options.installationId = installationId;
4530
+ }
4531
+ async getToken() {
4532
+ if (this.token && this.isUsable(this.token) && Date.now() < this.token.refreshAfter) {
4396
4533
  return this.token.value;
4397
4534
  }
4398
4535
  if (!this.requestInFlight) {
@@ -4401,33 +4538,38 @@ var RuntimeAuth = class {
4401
4538
  });
4402
4539
  }
4403
4540
  const token = await this.requestInFlight;
4404
- if (!token.capabilities.has(capability)) {
4405
- throw new AuthenticationError("ASIYST runtime authorization does not allow this operation.");
4406
- }
4407
4541
  return token.value;
4408
4542
  }
4409
4543
  invalidate() {
4410
4544
  this.token = void 0;
4411
4545
  }
4412
4546
  isUsable(token) {
4413
- return token.expiresAt - Date.now() > 3e4;
4547
+ return token.expiresAt > Date.now();
4414
4548
  }
4415
4549
  async issueToken() {
4550
+ const installationId = this.options.installationId;
4551
+ if (!installationId) {
4552
+ throw new AuthenticationError("ASIYST installation has not been verified.");
4553
+ }
4416
4554
  const controller = new AbortController();
4417
- const timeout = setTimeout(() => controller.abort(), 1e4);
4555
+ let timedOut = false;
4556
+ const timeout = setTimeout(() => {
4557
+ timedOut = true;
4558
+ controller.abort();
4559
+ }, 1e4);
4418
4560
  let response;
4419
4561
  try {
4420
4562
  const baseUrl = this.options.apiBaseUrl.replace(/\/$/, "");
4421
4563
  const payload = JSON.stringify({
4422
4564
  projectId: this.options.projectId,
4423
4565
  publicKey: this.options.publicKey,
4424
- installationId: this.options.installationId,
4566
+ installationId,
4425
4567
  origin: this.options.origin,
4426
- environment: this.options.environment,
4427
4568
  sdkVersion: SDK_VERSION,
4428
- capabilities: [...RUNTIME_CAPABILITIES]
4569
+ environment: this.options.environment,
4570
+ capabilities: ["assistant:config", "assistant:conversation", "assistant:heartbeat"]
4429
4571
  });
4430
- response = await fetch(`${baseUrl}/sdk/runtime/token`, {
4572
+ response = await fetch(contractApiUrl(baseUrl, API_ROUTES.runtimeToken), {
4431
4573
  method: "POST",
4432
4574
  headers: {
4433
4575
  Accept: "application/json",
@@ -4436,19 +4578,8 @@ var RuntimeAuth = class {
4436
4578
  body: payload,
4437
4579
  signal: controller.signal
4438
4580
  });
4439
- if (response.status === 404) {
4440
- response = await fetch(`${baseUrl}/api/v1/sdk/runtime/token`, {
4441
- method: "POST",
4442
- headers: {
4443
- Accept: "application/json",
4444
- "Content-Type": "application/json"
4445
- },
4446
- body: payload,
4447
- signal: controller.signal
4448
- });
4449
- }
4450
4581
  } catch {
4451
- throw new NetworkError("ASIYST runtime authentication is unavailable.");
4582
+ throw new NetworkError(timedOut ? "ASIYST runtime authentication request timed out." : "ASIYST runtime authentication is unavailable.");
4452
4583
  } finally {
4453
4584
  clearTimeout(timeout);
4454
4585
  }
@@ -4465,10 +4596,13 @@ var RuntimeAuth = class {
4465
4596
  if (response.status === 429) {
4466
4597
  throw new NetworkError("ASIYST runtime authentication is rate limited.");
4467
4598
  }
4599
+ if (response.status === 503) {
4600
+ throw new NetworkError("ASIYST runtime authentication is unavailable.");
4601
+ }
4468
4602
  throw new NetworkError("ASIYST runtime authentication is unavailable.");
4469
4603
  }
4470
4604
  const data = body?.data;
4471
- if (!data || body?.success !== true || typeof data.token !== "string" || data.token.length < 20 || data.tokenType !== "Bearer" || data.audience !== RUNTIME_AUDIENCE || typeof data.expiresIn !== "number" || !Number.isFinite(data.expiresIn) || data.expiresIn <= 0 || typeof data.expiresAt !== "string" || !Array.isArray(data.capabilities) || data.capabilities.some((capability) => !RUNTIME_CAPABILITIES.includes(capability))) {
4605
+ 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")) {
4472
4606
  throw new AuthenticationError("ASIYST returned an invalid runtime authorization response.");
4473
4607
  }
4474
4608
  const expiresAt = Date.parse(data.expiresAt);
@@ -4478,7 +4612,7 @@ var RuntimeAuth = class {
4478
4612
  const token = {
4479
4613
  value: data.token,
4480
4614
  expiresAt,
4481
- capabilities: new Set(data.capabilities)
4615
+ refreshAfter: expiresAt
4482
4616
  };
4483
4617
  this.token = token;
4484
4618
  return token;
@@ -4582,10 +4716,59 @@ function createSdkLifecycleEmitter(sink) {
4582
4716
  return new LifecycleEmitter(new UnsupportedLifecycleSink());
4583
4717
  }
4584
4718
 
4719
+ // src/avatar/AvatarMetrics.ts
4720
+ var AvatarMetricsTracker = class {
4721
+ constructor() {
4722
+ this.timestamps = {};
4723
+ this.assetInfo = {};
4724
+ }
4725
+ record(step, timestamp = typeof performance !== "undefined" ? performance.now() : Date.now()) {
4726
+ if (!this.timestamps[step]) {
4727
+ this.timestamps[step] = timestamp;
4728
+ }
4729
+ }
4730
+ setAssetInfo(info) {
4731
+ this.assetInfo = { ...this.assetInfo, ...info };
4732
+ }
4733
+ getMetrics() {
4734
+ const t = this.timestamps;
4735
+ const base = t.sdkInit ?? t.containerCreated ?? 0;
4736
+ const downloadStart = t.assetRequestStart ?? base;
4737
+ const downloadEnd = t.assetDownloadComplete ?? downloadStart;
4738
+ const parseEnd = t.parseAndDecodeComplete ?? downloadEnd;
4739
+ const sceneEnd = t.sceneInitComplete ?? parseEnd;
4740
+ const firstRender = t.firstRenderedFrame ?? sceneEnd;
4741
+ const firstVisible = t.firstVisibleCorrectlyFramed ?? firstRender;
4742
+ return {
4743
+ timestamps: {
4744
+ sdkInit: t.sdkInit ?? base,
4745
+ containerCreated: t.containerCreated ?? base,
4746
+ configRetrieved: t.configRetrieved ?? base,
4747
+ assetRequestStart: downloadStart,
4748
+ assetDownloadComplete: downloadEnd,
4749
+ parseAndDecodeComplete: parseEnd,
4750
+ sceneInitComplete: sceneEnd,
4751
+ firstRenderedFrame: firstRender,
4752
+ firstVisibleCorrectlyFramed: firstVisible
4753
+ },
4754
+ durations: {
4755
+ configRetrievalMs: Math.max(0, (t.configRetrieved ?? base) - base),
4756
+ downloadDurationMs: Math.max(0, downloadEnd - downloadStart),
4757
+ parseDurationMs: Math.max(0, parseEnd - downloadEnd),
4758
+ sceneInitDurationMs: Math.max(0, sceneEnd - parseEnd),
4759
+ firstRenderDurationMs: Math.max(0, firstRender - sceneEnd),
4760
+ timeToFirstVisibleMs: Math.max(0, firstVisible - base)
4761
+ },
4762
+ asset: { ...this.assetInfo }
4763
+ };
4764
+ }
4765
+ };
4766
+
4585
4767
  // src/core/Runtime.ts
4586
4768
  var AsiystRuntime = class {
4587
4769
  constructor(options, doc, win) {
4588
4770
  this.events = new EventBus();
4771
+ this.metricsTracker = new AvatarMetricsTracker();
4589
4772
  this.map = new WebsiteMap();
4590
4773
  this.observer = new DomObserver(() => this.rescan());
4591
4774
  this.lifecycle = createSdkLifecycleEmitter();
@@ -4595,6 +4778,7 @@ var AsiystRuntime = class {
4595
4778
  this.rescanDebounced = debounce(() => this.rescan(), DOM_SCAN_DEBOUNCE_MS);
4596
4779
  this.isHeartbeatInFlight = false;
4597
4780
  this.lastHeartbeatTime = 0;
4781
+ this.nextHeartbeatAfterMs = HEARTBEAT_INTERVAL_MS;
4598
4782
  this.registrationSucceeded = false;
4599
4783
  if (!doc.body) {
4600
4784
  throw new InitializationError("document.body is not available");
@@ -4614,10 +4798,11 @@ var AsiystRuntime = class {
4614
4798
  apiBaseUrl: options.apiBaseUrl ?? DEFAULT_API_BASE_URL,
4615
4799
  projectId: options.projectId,
4616
4800
  publicKey: options.publicKey,
4617
- installationId: this.installationId,
4801
+ installationId: void 0,
4618
4802
  origin: win.location.origin,
4619
4803
  environment: this.environment
4620
4804
  }) : void 0;
4805
+ this.runtimeAuth = runtimeAuth;
4621
4806
  this.cloud = new CloudClient(transport, options.projectId, options.publicKey, runtimeAuth, this.visitorSessionId, options.avatarId);
4622
4807
  this.config = new ConfigManager(options, this.cloud, this.events);
4623
4808
  this.config.onConfigUpdated = (newConfig, prevConfig) => {
@@ -4633,6 +4818,9 @@ var AsiystRuntime = class {
4633
4818
  this.renderer = new CssAvatarRenderer();
4634
4819
  this.renderer.onOpenChat = () => this.open();
4635
4820
  this.renderer.mount(this.host.chrome, this.config.get());
4821
+ this.metricsTracker.record("sdkInit");
4822
+ this.metricsTracker.record("containerCreated");
4823
+ this.renderer.setMetricsTracker(this.metricsTracker);
4636
4824
  this.highlights = new HighlightLayer(this.host.overlay, win);
4637
4825
  this.movement = new MovementEngine(win, doc, this.renderer, this.resolver, this.events, () => this.config.get());
4638
4826
  const live = createLiveRegion(this.host.shadow);
@@ -4646,21 +4834,19 @@ var AsiystRuntime = class {
4646
4834
  () => this.config.get()
4647
4835
  );
4648
4836
  const interaction = new InteractionEngine(this.avatar, this.resolver, () => this.config.get(), win);
4649
- this.tasks = new TaskEngine(interaction, this.events, this.analytics, this.cloud);
4837
+ this.tasks = new TaskEngine(interaction, this.events, this.analytics);
4650
4838
  this.workflows = new WorkflowEngine(this.cloud, this.tasks);
4651
4839
  this.panel = new ConversationPanel(
4652
4840
  this.host.chrome,
4653
4841
  (text) => this.handleUserMessage(text, doc),
4654
4842
  (open) => {
4655
- const convId = this.panel.getConversationId();
4656
- this.cloud.setConversationId(convId);
4657
4843
  this.renderer.setPanelOpen(open);
4658
4844
  if (open) {
4659
4845
  this.analytics.track("assistant_opened");
4660
- this.events.emit("asiyst:conversation:started", { conversationId: convId });
4661
4846
  } else {
4662
4847
  this.analytics.track("assistant_closed");
4663
- this.events.emit("asiyst:conversation:closed", { conversationId: convId });
4848
+ const conversationId = this.panel.getConversationId();
4849
+ if (conversationId) this.events.emit("asiyst:conversation:closed", { conversationId });
4664
4850
  }
4665
4851
  }
4666
4852
  );
@@ -4669,21 +4855,37 @@ var AsiystRuntime = class {
4669
4855
  this.observer.start(doc.documentElement);
4670
4856
  this.highlights.start();
4671
4857
  this.movement.start();
4672
- this.analytics.start();
4673
4858
  this.rescan();
4674
4859
  const figure = this.renderer.getFigure();
4675
4860
  if (figure) {
4676
4861
  this.figureClickListener = () => this.open();
4677
4862
  figure.addEventListener("click", this.figureClickListener);
4678
4863
  }
4679
- this.pagehideListener = () => {
4680
- void this.analytics.flush();
4681
- };
4682
- win.addEventListener("pagehide", this.pagehideListener);
4683
4864
  }
4684
4865
  async start() {
4685
4866
  this.events.emit("asiyst:initialized", { projectId: this.options.projectId });
4867
+ this.avatar.show();
4868
+ this.movement.goToAnchor();
4869
+ this.lifecycle.emit("sdk.verification_started", {
4870
+ projectId: this.options.projectId,
4871
+ origin: window.location.origin,
4872
+ environment: this.environment,
4873
+ installationId: this.installationId,
4874
+ sdkVersion: SDK_VERSION
4875
+ });
4876
+ try {
4877
+ await this.registerInstallation();
4878
+ } catch (error) {
4879
+ this.connectionStatus = "offline";
4880
+ this.verificationStatus = "error";
4881
+ this.events.emit("asiyst:error", {
4882
+ code: "runtime_connection_failed",
4883
+ message: error instanceof Error ? error.message : "Asiyst runtime connection failed."
4884
+ });
4885
+ return;
4886
+ }
4686
4887
  const cfg = await isolateAsync(() => this.config.refresh(), this.config.get());
4888
+ this.metricsTracker.record("configRetrieved");
4687
4889
  const domainCheck = validateWebsiteDomain(cfg, window.location.href);
4688
4890
  if (!domainCheck.allowed) {
4689
4891
  this.connectionStatus = "disconnected";
@@ -4696,28 +4898,7 @@ var AsiystRuntime = class {
4696
4898
  }
4697
4899
  this.avatar.applyConfig(cfg);
4698
4900
  this.movement.goToAnchor();
4699
- this.lifecycle.emit("sdk.verification_started", {
4700
- projectId: this.options.projectId,
4701
- origin: window.location.origin,
4702
- environment: this.environment,
4703
- installationId: this.installationId,
4704
- sdkVersion: SDK_VERSION
4705
- });
4706
- void (async () => {
4707
- try {
4708
- await this.registerInstallation();
4709
- await this.sendHeartbeat();
4710
- const doc = this.host.host.ownerDocument;
4711
- this.startHeartbeatScheduler(doc);
4712
- } catch {
4713
- }
4714
- })();
4715
4901
  this.events.emit("asiyst:ready", { projectId: this.options.projectId, configVersion: cfg.version });
4716
- void this.cloud.sendTelemetryEvent("avatar_runtime_initialized", {
4717
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4718
- avatarName: cfg.avatarName,
4719
- publishedVersion: cfg.publishedVersion
4720
- });
4721
4902
  const assetTarget = cfg.assetUrl ?? cfg.thumbnailUrl;
4722
4903
  if (assetTarget) {
4723
4904
  try {
@@ -4730,6 +4911,16 @@ var AsiystRuntime = class {
4730
4911
  this.avatar.show();
4731
4912
  this.movement.goToAnchor();
4732
4913
  }
4914
+ try {
4915
+ await this.sendHeartbeat();
4916
+ } catch (error) {
4917
+ this.connectionStatus = "offline";
4918
+ this.verificationStatus = "error";
4919
+ this.events.emit("asiyst:error", {
4920
+ code: "runtime_connection_failed",
4921
+ message: error instanceof Error ? error.message : "Asiyst runtime connection failed."
4922
+ });
4923
+ }
4733
4924
  this.startConfigRevalidationScheduler();
4734
4925
  }
4735
4926
  async loadAvatarAsset(cfg, assetTarget) {
@@ -4737,12 +4928,8 @@ var AsiystRuntime = class {
4737
4928
  avatarId: this.options.avatarId ?? cfg.avatarId,
4738
4929
  assetUrl: assetTarget
4739
4930
  });
4740
- void this.cloud.sendTelemetryEvent("avatar_asset_loading_started", {
4741
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4742
- assetUrl: assetTarget
4743
- });
4744
4931
  try {
4745
- const loaded = await this.renderer.loadAsset(cfg);
4932
+ const loaded = await this.renderer.loadAsset(cfg, this.metricsTracker);
4746
4933
  if (loaded) {
4747
4934
  this.movement.goToAnchor();
4748
4935
  const format = this.renderer.getLoadedFormat();
@@ -4753,23 +4940,13 @@ var AsiystRuntime = class {
4753
4940
  assetUrl,
4754
4941
  format
4755
4942
  });
4756
- void this.cloud.sendTelemetryEvent("avatar_asset_loaded", {
4757
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4758
- avatarName: cfg.avatarName,
4759
- assetUrl,
4760
- format,
4761
- publishedVersion: cfg.publishedVersion
4762
- });
4763
4943
  if (isRendered) {
4944
+ const metrics = this.metricsTracker.getMetrics();
4945
+ const durationMs = metrics?.durations.timeToFirstVisibleMs;
4764
4946
  this.events.emit("asiyst:avatar:rendered", {
4765
4947
  avatarId: this.options.avatarId ?? cfg.avatarId,
4766
- format
4767
- });
4768
- void this.cloud.sendTelemetryEvent("avatar_rendered", {
4769
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4770
- avatarName: cfg.avatarName,
4771
4948
  format,
4772
- publishedVersion: cfg.publishedVersion
4949
+ durationMs
4773
4950
  });
4774
4951
  }
4775
4952
  return true;
@@ -4780,11 +4957,6 @@ var AsiystRuntime = class {
4780
4957
  error: err,
4781
4958
  stage: "renderer_init"
4782
4959
  });
4783
- void this.cloud.sendTelemetryEvent("avatar_render_failed", {
4784
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4785
- error: err,
4786
- stage: "renderer_init"
4787
- });
4788
4960
  return false;
4789
4961
  }
4790
4962
  } catch (error) {
@@ -4794,11 +4966,6 @@ var AsiystRuntime = class {
4794
4966
  error: err,
4795
4967
  stage: "asset_fetch"
4796
4968
  });
4797
- void this.cloud.sendTelemetryEvent("avatar_render_failed", {
4798
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4799
- error: err,
4800
- stage: "asset_fetch"
4801
- });
4802
4969
  return false;
4803
4970
  }
4804
4971
  }
@@ -4845,6 +5012,7 @@ var AsiystRuntime = class {
4845
5012
  config: newConfig,
4846
5013
  previousVersion: prevConfig?.version
4847
5014
  });
5015
+ void this.sendHeartbeat();
4848
5016
  }
4849
5017
  async reloadConfig() {
4850
5018
  const updated = await this.config.refresh({ force: true });
@@ -4889,6 +5057,9 @@ var AsiystRuntime = class {
4889
5057
  getRenderer() {
4890
5058
  return this.renderer;
4891
5059
  }
5060
+ getAvatarPerformanceMetrics() {
5061
+ return this.metricsTracker.getMetrics();
5062
+ }
4892
5063
  avatarApi() {
4893
5064
  return this.avatar;
4894
5065
  }
@@ -4931,15 +5102,11 @@ var AsiystRuntime = class {
4931
5102
  clearInterval(this.configRevalidationTimer);
4932
5103
  this.configRevalidationTimer = void 0;
4933
5104
  }
4934
- const doc = this.host.host.ownerDocument;
4935
- if (doc && this.visibilityListener) {
4936
- doc.removeEventListener("visibilitychange", this.visibilityListener);
4937
- this.visibilityListener = void 0;
5105
+ if (this.heartbeatTimer) {
5106
+ clearTimeout(this.heartbeatTimer);
5107
+ this.heartbeatTimer = void 0;
4938
5108
  }
4939
5109
  this.isHeartbeatInFlight = false;
4940
- if (this.pagehideListener) {
4941
- win.removeEventListener("pagehide", this.pagehideListener);
4942
- }
4943
5110
  const figure = this.renderer.getFigure();
4944
5111
  if (figure && this.figureClickListener) {
4945
5112
  figure.removeEventListener("click", this.figureClickListener);
@@ -4956,26 +5123,20 @@ var AsiystRuntime = class {
4956
5123
  this.events.removeAll();
4957
5124
  await this.analytics.destroy();
4958
5125
  }
4959
- startHeartbeatScheduler(doc) {
4960
- if (this.heartbeatTimer) {
4961
- clearInterval(this.heartbeatTimer);
5126
+ async sendHeartbeat() {
5127
+ if (this.destroyed || this.isHeartbeatInFlight || !this.registrationSucceeded || !this.installationId) {
5128
+ return false;
4962
5129
  }
4963
- this.heartbeatTimer = setInterval(() => {
4964
- if (!this.destroyed) {
4965
- void this.sendHeartbeat(true);
5130
+ const state = this.renderer.getRenderState() === "error" ? "degraded" : "ready";
5131
+ if (this.lastReportedState === state) return true;
5132
+ const elapsed = Date.now() - this.lastHeartbeatTime;
5133
+ if (this.lastHeartbeatTime && elapsed < this.nextHeartbeatAfterMs) {
5134
+ if (!this.heartbeatTimer) {
5135
+ this.heartbeatTimer = setTimeout(() => {
5136
+ this.heartbeatTimer = void 0;
5137
+ void this.sendHeartbeat();
5138
+ }, this.nextHeartbeatAfterMs - elapsed);
4966
5139
  }
4967
- }, HEARTBEAT_INTERVAL_MS);
4968
- if (doc && typeof doc.addEventListener === "function") {
4969
- this.visibilityListener = () => {
4970
- if (!this.destroyed && doc.visibilityState === "visible" && Date.now() - this.lastHeartbeatTime > 3e4) {
4971
- void this.sendHeartbeat(true);
4972
- }
4973
- };
4974
- doc.addEventListener("visibilitychange", this.visibilityListener);
4975
- }
4976
- }
4977
- async sendHeartbeat(_isPeriodic = false) {
4978
- if (this.destroyed || this.isHeartbeatInFlight) {
4979
5140
  return false;
4980
5141
  }
4981
5142
  this.isHeartbeatInFlight = true;
@@ -4984,17 +5145,23 @@ var AsiystRuntime = class {
4984
5145
  const environment = this.environment;
4985
5146
  const installationId = this.installationId;
4986
5147
  try {
4987
- if (!this.registrationSucceeded && installationId) {
4988
- await this.registerInstallation();
4989
- }
4990
5148
  const heartbeat = await this.cloud.heartbeat({
4991
- origin,
4992
- environment,
4993
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
5149
+ installationId: this.installationId,
5150
+ sdkVersion: SDK_VERSION,
5151
+ state,
5152
+ avatarReady: this.renderer.getRenderState() === "ready",
5153
+ textChatReady: true,
5154
+ environment: this.environment,
5155
+ ...state === "degraded" ? { failureReason: "asset_load_failed" } : {}
4994
5156
  });
4995
5157
  this.lastHeartbeatTime = Date.now();
5158
+ if (heartbeat.ok) this.lastReportedState = state;
5159
+ this.nextHeartbeatAfterMs = Math.max(
5160
+ HEARTBEAT_INTERVAL_MS,
5161
+ heartbeat.nextHeartbeatAfterMs ?? heartbeat.retryAfterMs ?? HEARTBEAT_INTERVAL_MS
5162
+ );
4996
5163
  this.connectionStatus = heartbeat.ok ? "connected" : "disconnected";
4997
- this.verificationStatus = heartbeat.verificationStatus === "verified" ? "connected" : heartbeat.verificationStatus ?? (heartbeat.ok ? "connected" : "not_detected");
5164
+ this.verificationStatus = heartbeat.ok ? "connected" : "not_detected";
4998
5165
  if (heartbeat.ok) {
4999
5166
  if (!previousConnection) {
5000
5167
  this.events.emit("asiyst:runtime:connected", {
@@ -5011,32 +5178,21 @@ var AsiystRuntime = class {
5011
5178
  sdkVersion: SDK_VERSION
5012
5179
  });
5013
5180
  }
5014
- if (heartbeat.verificationStatus === "connected" || heartbeat.verificationStatus === "verified") {
5015
- this.lifecycle.emit("sdk.verified", {
5016
- projectId: this.options.projectId,
5017
- origin,
5018
- environment,
5019
- installationId,
5020
- sdkVersion: SDK_VERSION
5021
- });
5022
- }
5023
- if (heartbeat.versionOutdated) {
5024
- this.lifecycle.emit("sdk.version_outdated", {
5025
- projectId: this.options.projectId,
5026
- origin,
5027
- environment,
5028
- installationId,
5029
- sdkVersion: SDK_VERSION
5030
- });
5031
- }
5181
+ this.lifecycle.emit("sdk.verified", {
5182
+ projectId: this.options.projectId,
5183
+ origin,
5184
+ environment,
5185
+ installationId,
5186
+ sdkVersion: SDK_VERSION
5187
+ });
5032
5188
  return true;
5033
5189
  } else {
5034
- const reason = heartbeat.verificationStatus ?? "unverified";
5190
+ this.lastReportedState = void 0;
5035
5191
  this.lifecycle.emit("sdk.verification_failed", {
5036
5192
  projectId: this.options.projectId,
5037
5193
  origin,
5038
5194
  environment,
5039
- status: reason,
5195
+ status: "heartbeat_failed",
5040
5196
  reason: "heartbeat_failed"
5041
5197
  });
5042
5198
  if (previousConnection) {
@@ -5050,12 +5206,15 @@ var AsiystRuntime = class {
5050
5206
  environment,
5051
5207
  installationId,
5052
5208
  reason: "heartbeat_failed",
5053
- status: reason
5209
+ status: "heartbeat_failed"
5054
5210
  });
5055
5211
  }
5212
+ this.scheduleHeartbeatRetry();
5056
5213
  return false;
5057
5214
  }
5058
5215
  } catch (error) {
5216
+ this.lastHeartbeatTime = Date.now();
5217
+ this.lastReportedState = void 0;
5059
5218
  this.connectionStatus = "offline";
5060
5219
  this.verificationStatus = "error";
5061
5220
  this.lifecycle.emit("sdk.verification_failed", {
@@ -5066,6 +5225,10 @@ var AsiystRuntime = class {
5066
5225
  reason: "heartbeat_failed",
5067
5226
  category: error instanceof AuthenticationError ? "authorization" : "network"
5068
5227
  });
5228
+ this.events.emit("asiyst:error", {
5229
+ code: "runtime_heartbeat_failed",
5230
+ message: error instanceof Error ? error.message : "Asiyst heartbeat failed."
5231
+ });
5069
5232
  if (previousConnection) {
5070
5233
  this.events.emit("asiyst:runtime:disconnected", {
5071
5234
  projectId: this.options.projectId,
@@ -5085,73 +5248,72 @@ var AsiystRuntime = class {
5085
5248
  this.isHeartbeatInFlight = false;
5086
5249
  }
5087
5250
  }
5251
+ scheduleHeartbeatRetry() {
5252
+ if (this.destroyed || this.heartbeatTimer) return;
5253
+ const remaining = Math.max(0, this.nextHeartbeatAfterMs - (Date.now() - this.lastHeartbeatTime));
5254
+ this.heartbeatTimer = setTimeout(() => {
5255
+ this.heartbeatTimer = void 0;
5256
+ void this.sendHeartbeat();
5257
+ }, remaining);
5258
+ }
5088
5259
  async registerInstallation() {
5089
5260
  const origin = window.location.origin;
5090
5261
  const environment = this.environment;
5091
5262
  const installationId = this.installationId;
5092
5263
  if (!installationId) {
5093
- if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
5094
- console.debug("[asiyst] SDK installation identity is unavailable; registration skipped.");
5095
- }
5096
- return;
5264
+ throw new InitializationError("Asiyst could not establish a secure installation identity.");
5097
5265
  }
5098
- let lastError;
5099
- for (let attempt = 0; attempt < 2; attempt += 1) {
5100
- try {
5101
- await this.cloud.registerInstallation({
5102
- project_id: this.options.projectId,
5103
- public_key: this.options.publicKey,
5104
- installation_id: installationId,
5105
- origin,
5106
- environment,
5107
- sdk_version: SDK_VERSION
5108
- });
5109
- this.registrationSucceeded = true;
5110
- return;
5111
- } catch (error) {
5112
- lastError = error;
5113
- if (attempt === 1) {
5114
- if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
5115
- console.debug("[asiyst] SDK installation registration failed.", error);
5116
- }
5117
- this.lifecycle.emit("sdk.verification_failed", {
5118
- projectId: this.options.projectId,
5119
- origin,
5120
- environment,
5121
- installationId,
5122
- reason: "registration_failed",
5123
- category: error instanceof AuthenticationError ? "authorization" : "network"
5124
- });
5125
- return;
5126
- }
5127
- await new Promise((resolve) => setTimeout(resolve, 250));
5266
+ try {
5267
+ const verified = await this.cloud.registerInstallation({
5268
+ projectId: this.options.projectId,
5269
+ publicKey: this.options.publicKey,
5270
+ installationId,
5271
+ origin,
5272
+ environment,
5273
+ sdkVersion: SDK_VERSION
5274
+ });
5275
+ if (!verified.data.installationId) {
5276
+ throw new InitializationError("Asiyst returned no verified installation identifier.");
5128
5277
  }
5278
+ this.installationId = verified.data.installationId;
5279
+ this.runtimeAuth?.setInstallationId(verified.data.installationId);
5280
+ this.registrationSucceeded = true;
5281
+ } catch (error) {
5282
+ if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
5283
+ console.debug("[asiyst] SDK installation verification failed.", error);
5284
+ }
5285
+ this.lifecycle.emit("sdk.verification_failed", {
5286
+ projectId: this.options.projectId,
5287
+ origin,
5288
+ environment,
5289
+ installationId,
5290
+ reason: "registration_failed",
5291
+ category: error instanceof AuthenticationError ? "authorization" : "network"
5292
+ });
5293
+ throw error;
5129
5294
  }
5130
- this.lifecycle.emit("sdk.verification_failed", {
5131
- projectId: this.options.projectId,
5132
- origin,
5133
- environment,
5134
- installationId,
5135
- reason: "registration_failed",
5136
- category: lastError instanceof AuthenticationError ? "authorization" : "network"
5137
- });
5138
5295
  }
5139
5296
  rescan() {
5140
5297
  withIsolation(() => {
5141
5298
  const doc = this.host.host.ownerDocument;
5142
5299
  this.map.replace(inspectDocument(doc));
5143
- void this.cloud.sendWebsiteMap(this.map.snapshot(doc));
5144
5300
  });
5145
5301
  }
5146
5302
  async handleUserMessage(text, doc) {
5147
5303
  this.events.emit("asiyst:conversation:message", { role: "user", text });
5148
5304
  this.avatar.think();
5149
5305
  try {
5150
- const reply = await this.cloud.sendConversationMessage(text, doc.location.href);
5151
- this.panel.append("assistant", reply.message.text);
5306
+ const reply = await this.cloud.sendConversationMessage(
5307
+ text,
5308
+ doc.location.href,
5309
+ this.config.get().maxMessageChars
5310
+ );
5311
+ this.panel.setConversationId(reply.conversationId);
5312
+ this.cloud.setConversationId(reply.conversationId);
5313
+ this.events.emit("asiyst:conversation:started", { conversationId: reply.conversationId });
5314
+ this.panel.append("assistant", reply.message.text, reply.citations);
5152
5315
  this.avatar.speak(reply.message.text);
5153
5316
  this.events.emit("asiyst:conversation:message", { role: "assistant", text: reply.message.text });
5154
- await this.startTaskFromText(text, doc);
5155
5317
  } catch (error) {
5156
5318
  const message = error instanceof Error ? error.message : "Asiyst Cloud is unavailable";
5157
5319
  this.panel.append("assistant", message);
@@ -5175,6 +5337,9 @@ var Asiyst = {
5175
5337
  if (runtime) {
5176
5338
  throw new InitializationError("Asiyst is already initialized");
5177
5339
  }
5340
+ if (typeof document === "undefined" || typeof window === "undefined") {
5341
+ throw new InitializationError("Asiyst SDK can only be initialized in a browser environment.");
5342
+ }
5178
5343
  const credentials = validateInitOptions(options);
5179
5344
  const doc = document;
5180
5345
  const win = window;
@@ -5215,6 +5380,9 @@ var Asiyst = {
5215
5380
  isRuntimeConnected() {
5216
5381
  return requireRuntime().getConnectionStatus() === "connected";
5217
5382
  },
5383
+ getAvatarPerformanceMetrics() {
5384
+ return requireRuntime().getAvatarPerformanceMetrics();
5385
+ },
5218
5386
  avatar: {
5219
5387
  show() {
5220
5388
  withIsolation(() => requireRuntime().avatarApi().show());
@@ -5278,6 +5446,7 @@ exports.Asiyst = Asiyst;
5278
5446
  exports.AsiystError = AsiystError;
5279
5447
  exports.AssetLoader = AssetLoader;
5280
5448
  exports.AuthenticationError = AuthenticationError;
5449
+ exports.AvatarMetricsTracker = AvatarMetricsTracker;
5281
5450
  exports.ConfigurationError = ConfigurationError;
5282
5451
  exports.CssAvatarRenderer = CssAvatarRenderer;
5283
5452
  exports.FbxRenderer = FbxRenderer;