@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.js CHANGED
@@ -75,7 +75,7 @@ var ALL_ACTION_KINDS = [
75
75
  // src/core/constants.ts
76
76
  function resolveSdkVersion() {
77
77
  {
78
- return "0.1.28";
78
+ return "0.1.29";
79
79
  }
80
80
  }
81
81
  var SDK_VERSION = resolveSdkVersion();
@@ -94,7 +94,7 @@ var AVATAR_TARGET_GAP = 16;
94
94
  var WEBSITE_MAP_TEXT_LIMIT = 80;
95
95
  var CONFIG_CACHE_TTL_MS = 1e3 * 30;
96
96
  var CONFIG_REVALIDATION_INTERVAL_MS = 3e4;
97
- var HEARTBEAT_INTERVAL_MS = 45e3;
97
+ var HEARTBEAT_INTERVAL_MS = 3e5;
98
98
 
99
99
  // src/security/selectors.ts
100
100
  var DANGEROUS_SELECTOR = /javascript:|expression\(|@import|url\s*\(|behavior:|binding:|<script/i;
@@ -356,7 +356,8 @@ function parseAnimations(value) {
356
356
  clipName: typeof item.clipName === "string" ? sanitizeText(item.clipName, 64) : void 0,
357
357
  loopMode: typeof item.loopMode === "string" ? sanitizeText(item.loopMode, 32) : void 0,
358
358
  durationMs: typeof item.durationMs === "number" ? item.durationMs : void 0,
359
- assetUrl: typeof item.assetUrl === "string" ? item.assetUrl : null
359
+ assetUrl: typeof item.assetUrl === "string" ? item.assetUrl : null,
360
+ integrity: typeof item.integrity === "string" ? item.integrity : void 0
360
361
  });
361
362
  }
362
363
  }
@@ -383,6 +384,8 @@ function normalizeProjectConfig(raw) {
383
384
  ) || void 0;
384
385
  const assetUrl = typeof raw.assetUrl === "string" && raw.assetUrl ? raw.assetUrl : typeof rawAvatarRecord?.assetUrl === "string" && rawAvatarRecord.assetUrl ? rawAvatarRecord.assetUrl : typeof rawAvatarRecord?.modelUrl === "string" && rawAvatarRecord.modelUrl ? rawAvatarRecord.modelUrl : typeof rawConfigRecord?.assetUrl === "string" && rawConfigRecord.assetUrl ? rawConfigRecord.assetUrl : typeof rawManifestRecord?.assetUrl === "string" && rawManifestRecord.assetUrl ? rawManifestRecord.assetUrl : typeof rawManifestRecord?.modelUrl === "string" && rawManifestRecord.modelUrl ? rawManifestRecord.modelUrl : void 0;
385
386
  const thumbnailUrl = typeof raw.thumbnailUrl === "string" ? raw.thumbnailUrl : typeof rawAvatarRecord?.thumbnailUrl === "string" ? rawAvatarRecord.thumbnailUrl : typeof rawConfigRecord?.thumbnailUrl === "string" ? rawConfigRecord.thumbnailUrl : typeof rawManifestRecord?.thumbnailUrl === "string" ? rawManifestRecord.thumbnailUrl : rawAvatarRecord?.thumbnailUrl === null ? null : void 0;
387
+ const rawModelFormat = raw.modelFormat ?? rawAvatarRecord?.modelFormat ?? rawConfigRecord?.modelFormat ?? rawManifestRecord?.modelFormat;
388
+ const modelFormat = rawModelFormat === "fbx" || rawModelFormat === "glb" ? rawModelFormat : void 0;
386
389
  const publishedVersion = typeof raw.publishedVersion === "string" ? raw.publishedVersion : typeof rawAvatarRecord?.version === "string" ? rawAvatarRecord.version : typeof rawManifestRecord?.version === "string" ? rawManifestRecord.version : void 0;
387
390
  const animations = parseAnimations(
388
391
  raw.animations ?? rawAvatarRecord?.animations ?? rawConfigRecord?.animations
@@ -402,6 +405,8 @@ function normalizeProjectConfig(raw) {
402
405
  avatar,
403
406
  avatarId,
404
407
  assetUrl,
408
+ modelFormat,
409
+ assetIntegrity: typeof raw.assetIntegrity === "string" ? raw.assetIntegrity : typeof rawAvatarRecord?.assetIntegrity === "string" ? rawAvatarRecord.assetIntegrity : void 0,
405
410
  thumbnailUrl,
406
411
  publishedVersion,
407
412
  animations,
@@ -420,7 +425,8 @@ function normalizeProjectConfig(raw) {
420
425
  blockedRoutes: parseStringList(raw.blockedRoutes ?? raw.blocked_routes),
421
426
  rules: parseRules(raw.rules ?? raw.avatarRules),
422
427
  dataSources: parseDataSources(raw.dataSources ?? raw.enabledDataSources),
423
- elementSelectors: parseElementSelectors(raw.elementSelectors)
428
+ elementSelectors: parseElementSelectors(raw.elementSelectors),
429
+ maxMessageChars: asNumber(raw.maxMessageChars, 4e3, 1, 4e3)
424
430
  };
425
431
  }
426
432
  function validateInitOptions(options) {
@@ -504,7 +510,7 @@ var HttpTransport = class {
504
510
  return this.options.avatarId;
505
511
  }
506
512
  async request(req) {
507
- const url = `${this.options.apiBaseUrl.replace(/\/$/, "")}${req.path}`;
513
+ const url = /^https?:\/\//i.test(req.path) ? req.path : `${this.options.apiBaseUrl.replace(/\/$/, "")}${req.path}`;
508
514
  const requestId = req.requestId || generateRequestId();
509
515
  const timeoutMs = req.timeoutMs ?? this.options.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS;
510
516
  const isSafeOrIdempotent = req.method === "GET" || Boolean(req.idempotent);
@@ -532,36 +538,30 @@ var HttpTransport = class {
532
538
  }
533
539
  try {
534
540
  let response;
535
- try {
536
- response = await fetch(url, {
537
- method: req.method,
538
- headers: {
539
- Accept: "application/json",
540
- "Content-Type": "application/json",
541
- "X-Asiyst-Project-Id": this.options.projectId,
542
- "X-Asiyst-Public-Key": this.options.publicKey,
543
- ...this.options.avatarId ? { "X-Asiyst-Avatar-Id": this.options.avatarId } : {},
544
- "X-Asiyst-SDK-Version": SDK_VERSION,
545
- "X-Asiyst-Request-Id": requestId,
546
- ...req.sessionId ? { "X-Asiyst-Session-Id": req.sessionId } : {},
547
- ...req.conversationId ? { "X-Asiyst-Conversation-Id": req.conversationId } : {},
548
- ...req.authorizationToken ? { Authorization: `Bearer ${req.authorizationToken}` } : {}
549
- },
550
- body: req.body === void 0 ? void 0 : JSON.stringify(req.body),
551
- signal: controller.signal
552
- });
553
- } finally {
554
- clearTimeout(timeoutId);
555
- if (req.signal) {
556
- req.signal.removeEventListener("abort", onExternalAbort);
557
- }
558
- }
541
+ response = await fetch(url, {
542
+ method: req.method,
543
+ headers: req.headers ?? {
544
+ Accept: "application/json",
545
+ "Content-Type": "application/json",
546
+ "X-Asiyst-Project-Id": this.options.projectId,
547
+ "X-Asiyst-Public-Key": this.options.publicKey,
548
+ ...this.options.avatarId ? { "X-Asiyst-Avatar-Id": this.options.avatarId } : {},
549
+ "X-Asiyst-SDK-Version": SDK_VERSION,
550
+ "X-Asiyst-Request-Id": requestId,
551
+ ...req.sessionId ? { "X-Asiyst-Session-Id": req.sessionId } : {},
552
+ ...req.conversationId ? { "X-Asiyst-Conversation-Id": req.conversationId } : {},
553
+ ...req.authorizationToken ? { Authorization: `Bearer ${req.authorizationToken}` } : {}
554
+ },
555
+ body: req.body === void 0 ? void 0 : JSON.stringify(req.body),
556
+ signal: controller.signal
557
+ });
559
558
  if (isSafeOrIdempotent && attempt < maxRetries && [502, 503, 504].includes(response.status)) {
560
559
  continue;
561
560
  }
562
561
  if (response.status === 429 && isSafeOrIdempotent && attempt < maxRetries) {
563
562
  const retryAfterHeader = response.headers.get("retry-after");
564
563
  const retryAfterMs = retryAfterHeader ? Math.min(Number(retryAfterHeader) * 1e3 || 200, 1e3) : 100;
564
+ clearTimeout(timeoutId);
565
565
  await new Promise((resolve) => setTimeout(resolve, retryAfterMs));
566
566
  continue;
567
567
  }
@@ -571,33 +571,87 @@ var HttpTransport = class {
571
571
  try {
572
572
  data = await response.json();
573
573
  } catch {
574
+ if (timedOut) {
575
+ throw new NetworkError("Asiyst Cloud request timed out");
576
+ }
577
+ if (req.signal?.aborted) {
578
+ throw new NetworkError("Asiyst Cloud request was aborted");
579
+ }
574
580
  data = null;
575
581
  }
576
582
  }
577
583
  if (!response.ok) {
578
- return { ok: false, status: response.status, data };
584
+ return { ok: false, status: response.status, data, headers: response.headers };
579
585
  }
580
- return { ok: true, status: response.status, data };
586
+ return { ok: true, status: response.status, data, headers: response.headers };
581
587
  } catch (err) {
582
- clearTimeout(timeoutId);
583
- if (req.signal) {
584
- req.signal.removeEventListener("abort", onExternalAbort);
585
- }
586
588
  if (timedOut) {
587
589
  throw new NetworkError("Asiyst Cloud request timed out");
588
590
  }
591
+ if (req.signal?.aborted) {
592
+ throw new NetworkError("Asiyst Cloud request was aborted");
593
+ }
589
594
  lastError = err;
590
595
  if (isSafeOrIdempotent && attempt < maxRetries) {
591
596
  continue;
592
597
  }
593
598
  throw new NetworkError("Asiyst Cloud is unreachable");
599
+ } finally {
600
+ clearTimeout(timeoutId);
601
+ if (req.signal) {
602
+ req.signal.removeEventListener("abort", onExternalAbort);
603
+ }
594
604
  }
595
605
  }
596
606
  throw lastError instanceof Error ? lastError : new NetworkError("Asiyst Cloud is unreachable");
597
607
  }
598
608
  };
599
609
 
610
+ // ../api-contract.ts
611
+ var API_V1_BASE_PATH = "/api/v1";
612
+ var API_ROUTES = {
613
+ runtimeAvatar: "/runtime/avatar",
614
+ runtimeToken: "/sdk/runtime/token",
615
+ installationRegister: "/sdk/installations/register",
616
+ runtimeHeartbeat: "/sdk/heartbeat",
617
+ chat: "/conversations/messages",
618
+ projectApiKeyVerify: (projectId) => `/projects/${encodeURIComponent(projectId)}/api-key/verify`,
619
+ sdkInstallationVerify: "/sdk/installations/verify"
620
+ };
621
+ var API_LIMITS = {
622
+ configStaleIfErrorMs: 0,
623
+ maxMessageChars: 12e3,
624
+ pageUrlMaxChars: 2048};
625
+ function apiV1Path(route) {
626
+ return `${API_V1_BASE_PATH}${route.startsWith("/") ? route : `/${route}`}`;
627
+ }
628
+ function contractApiBaseUrl(configuredApiBaseUrl) {
629
+ const parsed = new URL(configuredApiBaseUrl);
630
+ if (parsed.pathname.replace(/\/+$/, "").endsWith("/functions/v1/api")) {
631
+ return "https://asiyst.com";
632
+ }
633
+ return parsed.origin;
634
+ }
635
+ function contractApiUrl(configuredApiBaseUrl, route) {
636
+ return `${contractApiBaseUrl(configuredApiBaseUrl).replace(/\/+$/, "")}${apiV1Path(route)}`;
637
+ }
638
+
600
639
  // src/communication/CloudClient.ts
640
+ function newRequestId() {
641
+ const cryptoApi = globalThis.crypto;
642
+ if (typeof cryptoApi?.randomUUID === "function") return cryptoApi.randomUUID();
643
+ if (typeof cryptoApi?.getRandomValues === "function") {
644
+ const bytes = cryptoApi.getRandomValues(new Uint8Array(16));
645
+ bytes[6] = (bytes[6] ?? 0) & 15 | 64;
646
+ bytes[8] = (bytes[8] ?? 0) & 63 | 128;
647
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
648
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
649
+ }
650
+ throw new ConfigurationError("Secure request identifiers are unavailable in this browser.");
651
+ }
652
+ function isUuid(value) {
653
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
654
+ }
601
655
  var CloudClient = class {
602
656
  constructor(transport, projectId, publicKey = "", runtimeAuth, sessionId, avatarId) {
603
657
  this.transport = transport;
@@ -605,6 +659,7 @@ var CloudClient = class {
605
659
  this.publicKey = publicKey;
606
660
  this.runtimeAuth = runtimeAuth;
607
661
  this.avatarId = avatarId;
662
+ this.configMetadata = {};
608
663
  this.inFlightConversations = /* @__PURE__ */ new Map();
609
664
  this.sessionId = sessionId;
610
665
  if (!this.avatarId && typeof transport.getAvatarId === "function") {
@@ -635,243 +690,152 @@ var CloudClient = class {
635
690
  }
636
691
  return DEFAULT_API_BASE_URL;
637
692
  }
638
- async getAuthToken(capability) {
693
+ async getAuthToken() {
639
694
  if (!this.runtimeAuth) return void 0;
640
695
  if (this.tokenRefreshPromise) return this.tokenRefreshPromise;
641
- if (!this.inFlightToken) {
642
- this.inFlightToken = this.runtimeAuth.getToken(capability).then((token) => {
643
- this.activeToken = token;
644
- return token;
645
- }).finally(() => {
646
- this.inFlightToken = void 0;
647
- });
648
- }
649
- return this.inFlightToken;
696
+ this.tokenRefreshPromise = this.runtimeAuth.getToken().then((token) => {
697
+ this.activeToken = token;
698
+ return token;
699
+ }).finally(() => {
700
+ this.tokenRefreshPromise = void 0;
701
+ });
702
+ return this.tokenRefreshPromise;
650
703
  }
651
- async fetchConfig() {
652
- const avatarParam = this.avatarId ? `?avatarId=${encodeURIComponent(this.avatarId)}` : "";
653
- const avatarAndKeyParams = `?projectId=${encodeURIComponent(this.projectId)}&publicKey=${encodeURIComponent(this.publicKey)}${this.avatarId ? `&avatarId=${encodeURIComponent(this.avatarId)}` : ""}`;
654
- const baseUrl = this.getApiBaseUrl();
655
- const resolveAssetUrls = (raw) => {
656
- let canonicalBase = "https://asiyst.com";
657
- try {
658
- if (baseUrl) {
659
- const u = new URL(baseUrl);
660
- canonicalBase = u.origin;
661
- }
662
- } catch {
663
- canonicalBase = "https://asiyst.com";
704
+ getConfigMetadata() {
705
+ return this.configMetadata;
706
+ }
707
+ async fetchConfig(etag, cachedConfig) {
708
+ const response = await this.transport.request({
709
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.runtimeAvatar),
710
+ method: "GET",
711
+ idempotent: true,
712
+ retries: 2,
713
+ headers: {
714
+ Accept: "application/json",
715
+ "X-Asiyst-Public-Key": this.publicKey,
716
+ "X-Asiyst-Project-Id": this.projectId,
717
+ ...this.avatarId ? { "X-Asiyst-Avatar-Id": this.avatarId } : {},
718
+ ...etag ? { "If-None-Match": etag } : {}
664
719
  }
665
- const toAbsolute = (url) => {
666
- if (typeof url === "string" && url.startsWith("/")) {
667
- return new URL(url, canonicalBase).href;
668
- }
669
- return url;
720
+ });
721
+ if (response.status === 304 && cachedConfig) {
722
+ this.configMetadata = {
723
+ etag: response.headers?.get("etag") ?? etag,
724
+ maxAgeMs: 0,
725
+ staleIfErrorMs: 0
670
726
  };
671
- if (raw.avatar && typeof raw.avatar === "object" && !Array.isArray(raw.avatar)) {
672
- const av = { ...raw.avatar };
673
- av.assetUrl = toAbsolute(av.assetUrl);
674
- av.thumbnailUrl = toAbsolute(av.thumbnailUrl);
675
- av.modelUrl = toAbsolute(av.modelUrl);
676
- av.manifestUrl = toAbsolute(av.manifestUrl);
677
- if (Array.isArray(av.animations)) {
678
- av.animations = av.animations.map((item) => {
679
- if (item && typeof item === "object") {
680
- const animObj = item;
681
- return { ...animObj, assetUrl: toAbsolute(animObj.assetUrl) };
682
- }
683
- return item;
684
- });
685
- }
686
- raw.avatar = av;
687
- }
688
- if (raw.config && typeof raw.config === "object" && !Array.isArray(raw.config)) {
689
- const cfg = { ...raw.config };
690
- cfg.assetUrl = toAbsolute(cfg.assetUrl);
691
- cfg.thumbnailUrl = toAbsolute(cfg.thumbnailUrl);
692
- cfg.manifestUrl = toAbsolute(cfg.manifestUrl);
693
- raw.config = cfg;
694
- }
695
- if (raw.manifest && typeof raw.manifest === "object" && !Array.isArray(raw.manifest)) {
696
- const mf = { ...raw.manifest };
697
- mf.assetUrl = toAbsolute(mf.assetUrl);
698
- mf.thumbnailUrl = toAbsolute(mf.thumbnailUrl);
699
- mf.modelUrl = toAbsolute(mf.modelUrl);
700
- raw.manifest = mf;
701
- }
702
- raw.assetUrl = toAbsolute(raw.assetUrl);
703
- raw.thumbnailUrl = toAbsolute(raw.thumbnailUrl);
704
- raw.manifestUrl = toAbsolute(raw.manifestUrl);
705
- if (raw.branding && typeof raw.branding === "object" && !Array.isArray(raw.branding)) {
706
- const br = { ...raw.branding };
707
- br.siteLogoUrl = toAbsolute(br.siteLogoUrl);
708
- raw.branding = br;
709
- }
710
- return raw;
711
- };
712
- let lastError;
713
- try {
714
- const response = await this.runtimeRequest({
715
- path: `/projects/${encodeURIComponent(this.projectId)}/avatar${avatarParam}`,
716
- method: "GET",
717
- idempotent: true
718
- });
719
- if (response.ok && response.data) {
720
- const fullData = response.data && typeof response.data === "object" && !Array.isArray(response.data) ? {
721
- ...response.data,
722
- ...response.data.config && typeof response.data.config === "object" ? response.data.config : {}
723
- } : {};
724
- return normalizeProjectConfig(resolveAssetUrls(fullData));
725
- }
726
- if (response.status === 404) {
727
- lastError = new ConfigurationError(`Project ${this.projectId} or avatar configuration not found`);
728
- }
729
- } catch (err) {
730
- if (err instanceof Error) lastError = err;
727
+ return cachedConfig;
731
728
  }
732
- try {
733
- const runtimeResponse = await this.runtimeRequest({
734
- path: `/api/v1/runtime/avatar${avatarAndKeyParams}`,
735
- method: "GET",
736
- idempotent: true
737
- });
738
- if (runtimeResponse.ok && runtimeResponse.data) {
739
- return normalizeProjectConfig(resolveAssetUrls(runtimeResponse.data));
740
- }
741
- if (runtimeResponse.status === 404) {
742
- lastError = new ConfigurationError(`Avatar ${this.avatarId ?? "active"} not found for project ${this.projectId}`);
743
- }
744
- } catch (err) {
745
- if (err instanceof Error) lastError = err;
746
- }
747
- try {
748
- const webBase = baseUrl.includes("localhost") || baseUrl.includes("127.0.0.1") ? baseUrl.replace(/\/functions\/v1.*$/, "").replace(/\/api\/v1.*$/, "") : "https://asiyst.com";
749
- const fullUrl = `${webBase.replace(/\/$/, "")}/api/v1/runtime/avatar${avatarAndKeyParams}`;
750
- const res = await fetch(fullUrl, {
751
- headers: {
752
- Accept: "application/json",
753
- "x-asiyst-public-key": this.publicKey
754
- }
755
- });
756
- if (res.ok) {
757
- const body = await res.json();
758
- if (body && typeof body === "object") {
759
- return normalizeProjectConfig(resolveAssetUrls(body));
760
- }
761
- } else {
762
- const errorBody = await res.json().catch(() => ({}));
763
- const errObj = errorBody?.error ?? errorBody;
764
- const code = String(errObj?.code ?? "");
765
- const message = String(errObj?.message ?? `HTTP ${res.status}`);
766
- if (res.status === 404) {
767
- throw new ConfigurationError(code === "AVATAR_NOT_FOUND" ? `Requested avatar not found for project ${this.projectId}` : `Project ${this.projectId} not found`);
768
- } else if (res.status === 401 || res.status === 403) {
769
- throw new AuthenticationError("Asiyst credentials unauthorized for this avatar configuration");
770
- } else if (res.status >= 500) {
771
- throw new NetworkError(`Asiyst Cloud avatar service error (${res.status}): ${message}`);
772
- }
773
- }
774
- } catch (err) {
775
- if (err instanceof ConfigurationError || err instanceof AuthenticationError || err instanceof NetworkError) {
776
- throw err;
729
+ if (!response.ok || !response.data) {
730
+ const body = response.data;
731
+ const code = body?.error?.code ?? `HTTP_${response.status}`;
732
+ if (response.status === 401 || response.status === 403) {
733
+ throw new AuthenticationError(body?.error?.message ?? `Asiyst runtime avatar configuration was rejected (${code}).`);
777
734
  }
778
- if (err instanceof Error) lastError = err;
779
- }
780
- if (lastError) {
781
- throw lastError;
782
- }
783
- throw new ConfigurationError(`Failed to resolve avatar configuration for project ${this.projectId}`);
735
+ throw new NetworkError(body?.error?.message ?? `Asiyst runtime avatar configuration is unavailable (${code}).`);
736
+ }
737
+ const data = response.data;
738
+ if (data.success !== true || data.projectId !== this.projectId || typeof data.avatarId !== "string" || !data.config || typeof data.config !== "object" || Array.isArray(data.config)) {
739
+ throw new ConfigurationError("Asiyst returned an invalid runtime configuration response.");
740
+ }
741
+ const rawConfig = data.config;
742
+ const rawAvatar = data.avatar && typeof data.avatar === "object" ? data.avatar : {};
743
+ const manifest = data.manifest && typeof data.manifest === "object" ? data.manifest : {};
744
+ const modelFormat = [data.format, data.modelFormat, rawConfig.modelFormat, rawAvatar.modelFormat].find((format) => typeof format === "string");
745
+ if (modelFormat && modelFormat !== "fbx" && modelFormat !== "glb") {
746
+ throw new ConfigurationError(`Asiyst returned an unsupported avatar format: ${modelFormat}.`);
747
+ }
748
+ const assetUrl = typeof rawConfig.assetUrl === "string" ? rawConfig.assetUrl : typeof rawAvatar.assetUrl === "string" ? rawAvatar.assetUrl : typeof rawAvatar.modelUrl === "string" ? rawAvatar.modelUrl : typeof manifest.assetUrl === "string" ? manifest.assetUrl : void 0;
749
+ const animations = Array.isArray(rawConfig.animations) ? rawConfig.animations : Array.isArray(data.animations) ? data.animations : Array.isArray(rawAvatar.animations) ? rawAvatar.animations : [];
750
+ const revision = typeof data.configRevision === "string" ? data.configRevision : typeof data.publishedVersionId === "string" ? data.publishedVersionId : "0";
751
+ const version = Number.parseInt(revision, 10);
752
+ const config = normalizeProjectConfig({
753
+ ...rawConfig,
754
+ avatarId: data.avatarId,
755
+ avatarName: typeof rawAvatar.name === "string" ? rawAvatar.name : rawConfig.avatarName,
756
+ assetUrl,
757
+ modelFormat,
758
+ publishedVersion: typeof data.publishedVersionId === "string" ? data.publishedVersionId : revision,
759
+ version: Number.isFinite(version) ? version : 0,
760
+ animations,
761
+ theme: rawConfig.theme ?? rawAvatar.theme,
762
+ personality: rawConfig.personality,
763
+ behavior: rawConfig.behavior ?? rawAvatar.behavior,
764
+ maxMessageChars: API_LIMITS.maxMessageChars
765
+ });
766
+ this.configMetadata = {
767
+ etag: response.headers?.get("etag") ?? void 0,
768
+ maxAgeMs: 0,
769
+ staleIfErrorMs: 0
770
+ };
771
+ return config;
784
772
  }
785
773
  async heartbeat(metadata) {
786
- let response = await this.runtimeRequest({
787
- path: "/sdk/heartbeat",
774
+ const response = await this.runtimeRequest({
775
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.runtimeHeartbeat),
788
776
  method: "POST",
789
- idempotent: true,
777
+ canonical: true,
790
778
  body: {
791
- project_id: this.projectId,
792
- public_key: this.publicKey,
793
- sdk_version: SDK_VERSION,
794
- origin: metadata.origin,
795
- environment: metadata.environment,
796
- timestamp: metadata.timestamp
779
+ projectId: this.projectId,
780
+ publicKey: this.publicKey,
781
+ sdkVersion: metadata.sdkVersion,
782
+ environment: metadata.environment
797
783
  }
798
784
  }, "assistant:heartbeat");
799
- if (response.status === 404) {
800
- response = await this.runtimeRequest({
801
- path: "/api/v1/sdk/heartbeat",
802
- method: "POST",
803
- idempotent: true,
804
- body: {
805
- project_id: this.projectId,
806
- public_key: this.publicKey,
807
- sdk_version: SDK_VERSION,
808
- origin: metadata.origin,
809
- environment: metadata.environment,
810
- timestamp: metadata.timestamp
811
- }
812
- }, "assistant:heartbeat");
813
- }
814
- const body = response.data && typeof response.data === "object" && !Array.isArray(response.data) ? response.data : void 0;
815
- const rawStatus = body?.status ?? body?.connectionStatus ?? body?.verificationStatus ?? (body?.verified === true ? "verified" : void 0);
816
- const verificationStatus = rawStatus === "connected" || rawStatus === "verified" || rawStatus === "inactive" || rawStatus === "not_detected" || rawStatus === "error" ? rawStatus : void 0;
817
- const versionOutdated = body?.versionOutdated === true || body?.sdkVersionOutdated === true || rawStatus === "outdated";
785
+ const body = response.data;
786
+ const validResponse = body?.success === true && body.data?.connected === true && body.data.projectId === this.projectId && typeof body.data.versionOutdated === "boolean";
818
787
  return {
819
- ok: response.ok && (verificationStatus === void 0 || verificationStatus === "connected" || verificationStatus === "verified"),
820
- status: response.status,
821
- verificationStatus,
822
- versionOutdated
788
+ ok: response.ok && response.status === 202 && validResponse,
789
+ status: response.status
823
790
  };
824
791
  }
825
792
  async registerInstallation(registration) {
826
- let response = await this.transport.request({
827
- path: "/sdk/installations/register",
793
+ const response = await this.transport.request({
794
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.installationRegister),
828
795
  method: "POST",
829
- body: registration,
830
- idempotent: true,
831
- sessionId: this.sessionId
796
+ headers: {
797
+ Accept: "application/json",
798
+ "Content-Type": "application/json",
799
+ "X-Asiyst-SDK-Version": registration.sdkVersion
800
+ },
801
+ body: {
802
+ projectId: registration.projectId,
803
+ publicKey: registration.publicKey,
804
+ installationId: registration.installationId,
805
+ origin: registration.origin,
806
+ environment: registration.environment,
807
+ sdkVersion: registration.sdkVersion
808
+ }
832
809
  });
833
- if (response.status === 404) {
834
- response = await this.transport.request({
835
- path: "/api/v1/sdk/installations/register",
836
- method: "POST",
837
- body: registration,
838
- idempotent: true,
839
- sessionId: this.sessionId
840
- });
841
- }
842
- if (!response.ok) {
843
- throw new NetworkError(`SDK installation registration failed (${response.status}).`);
810
+ const body = response.data;
811
+ if (!response.ok || body?.success !== true || body.data?.registered !== true || typeof body.data.installationId !== "string" || body.data.projectId !== registration.projectId || body.data.status === "revoked") {
812
+ const error = response.data && typeof response.data === "object" ? response.data.error : void 0;
813
+ if (response.status === 403 || body?.data?.status === "revoked") {
814
+ throw new AuthenticationError(error?.message ?? `SDK installation is not authorized (${error?.code ?? response.status}).`);
815
+ }
816
+ throw new NetworkError(error?.message ?? `SDK installation registration failed (${response.status}).`);
844
817
  }
845
- return response.data ?? {};
818
+ return body;
846
819
  }
847
820
  async requestTask(userText, pageUrl) {
848
- const response = await this.runtimeRequest({
849
- path: "/tasks",
850
- method: "POST",
851
- body: {
852
- projectId: this.projectId,
853
- text: userText,
854
- pageUrl
855
- }
856
- }, "assistant:conversation");
857
- if (!response.ok || !response.data?.task?.id || !Array.isArray(response.data.task.steps)) {
858
- throw new NetworkError("Task planning is unavailable");
859
- }
860
- return response.data.task;
821
+ throw new ConfigurationError("Cloud task planning is not defined by the approved SDK API contract.");
861
822
  }
862
823
  async fetchWorkflow(workflowId) {
863
- const response = await this.runtimeRequest({
864
- path: `/workflows/${encodeURIComponent(workflowId)}`,
865
- method: "GET",
866
- idempotent: true
867
- }, "assistant:conversation");
868
- if (!response.ok || !response.data?.workflow?.id || !Array.isArray(response.data.workflow.steps)) {
869
- throw new NetworkError("Workflow is unavailable");
870
- }
871
- return response.data.workflow;
824
+ throw new ConfigurationError("Cloud workflows are not defined by the approved SDK API contract.");
872
825
  }
873
- async sendConversationMessage(text, pageUrl) {
826
+ async sendConversationMessage(text, pageUrl, maxMessageChars = API_LIMITS.maxMessageChars) {
874
827
  const trimmed = text.trim();
828
+ if (!trimmed) throw new ConfigurationError("Message cannot be empty.");
829
+ if (trimmed.length > maxMessageChars) {
830
+ throw new ConfigurationError(`Message exceeds the ${maxMessageChars}-character limit.`);
831
+ }
832
+ if (pageUrl.length > API_LIMITS.pageUrlMaxChars) {
833
+ throw new ConfigurationError("Page URL exceeds the supported length.");
834
+ }
835
+ const sessionId = this.sessionId ?? newRequestId();
836
+ if (sessionId.length < 16 || sessionId.length > 128 || !/^[A-Za-z0-9_-]+$/.test(sessionId)) {
837
+ throw new ConfigurationError("Visitor session ID must be an opaque 16-128 character identifier.");
838
+ }
875
839
  const dedupeKey2 = `${this.conversationId ?? ""}:${trimmed}:${pageUrl}`;
876
840
  const existing = this.inFlightConversations.get(dedupeKey2);
877
841
  if (existing) {
@@ -879,19 +843,72 @@ var CloudClient = class {
879
843
  }
880
844
  const conversationPromise = (async () => {
881
845
  try {
846
+ const requestConversationId = this.conversationId && isUuid(this.conversationId) ? this.conversationId : void 0;
882
847
  const response = await this.runtimeRequest({
883
- path: "/conversations/messages",
848
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.chat),
884
849
  method: "POST",
885
- body: { projectId: this.projectId, text: trimmed, pageUrl },
886
- conversationId: this.conversationId
850
+ body: {
851
+ projectId: this.projectId,
852
+ text: trimmed,
853
+ ...requestConversationId ? { conversationId: requestConversationId } : {},
854
+ sessionId,
855
+ pageUrl
856
+ }
887
857
  }, "assistant:conversation");
888
- if (!response.ok || !response.data?.message?.text) {
889
- if (response.status === 401 || response.status === 403) {
890
- throw new NetworkError("AI request authorization failed. The project credentials may be inactive, revoked, or inaccessible.");
858
+ if (response.ok && response.data?.success === true) {
859
+ const body = response.data;
860
+ const message = body.message && typeof body.message === "object" ? body.message : void 0;
861
+ const conversationId = body.conversationId;
862
+ const messageText = message?.text ?? body.response ?? body.answer;
863
+ if (body.success !== true || typeof conversationId !== "string" || typeof messageText !== "string" || !messageText.trim() || message && message.role !== "assistant") {
864
+ throw new NetworkError("Asiyst returned an unsupported conversation response.");
891
865
  }
892
- throw new NetworkError("Conversation service is unavailable");
866
+ this.conversationId = conversationId;
867
+ const rawCitations = Array.isArray(body.sources) ? body.sources : [];
868
+ return {
869
+ requestId: typeof body.requestId === "string" ? body.requestId : void 0,
870
+ conversationId,
871
+ message: {
872
+ ...typeof message?.id === "string" ? { id: message.id } : {},
873
+ role: "assistant",
874
+ text: messageText
875
+ },
876
+ citations: rawCitations.flatMap((citation) => {
877
+ if (!citation || typeof citation !== "object") return [];
878
+ const item = citation;
879
+ const sourceId = item.source_id ?? item.id;
880
+ if (typeof sourceId !== "string" || typeof item.title !== "string") return [];
881
+ return [{
882
+ sourceId,
883
+ title: item.title,
884
+ ...typeof item.url === "string" ? { url: item.url } : {}
885
+ }];
886
+ }),
887
+ finishReason: void 0,
888
+ createdAt: void 0
889
+ };
890
+ }
891
+ const errorRecord = response.data && typeof response.data === "object" ? response.data.error : void 0;
892
+ const errorBody = errorRecord && typeof errorRecord === "object" ? errorRecord : void 0;
893
+ const code = typeof errorBody?.code === "string" ? errorBody.code : typeof errorRecord === "string" ? errorRecord : `HTTP_${response.status}`;
894
+ if (response.status === 401 || response.status === 403) {
895
+ throw new AuthenticationError("Asiyst runtime authorization was rejected.");
896
+ }
897
+ if (response.status === 429) {
898
+ throw new NetworkError("The assistant is rate limited. Wait before sending another message.");
899
+ }
900
+ if (response.status === 409) {
901
+ throw new NetworkError(`The conversation request conflicted (${code}); it was not retried.`);
902
+ }
903
+ if (response.status === 504 || code === "AI_PROVIDER_TIMEOUT") {
904
+ throw new NetworkError("The assistant timed out. The request was not retried to avoid duplicate work.");
893
905
  }
894
- return response.data;
906
+ if (code === "assistant_unavailable") {
907
+ throw new NetworkError("The assistant is temporarily unavailable.");
908
+ }
909
+ throw new NetworkError(
910
+ typeof errorBody?.message === "string" ? errorBody.message : typeof response.data?.message === "string" ? response.data.message : "Conversation service is unavailable."
911
+ );
895
912
  } finally {
896
913
  this.inFlightConversations.delete(dedupeKey2);
897
914
  }
@@ -900,63 +917,16 @@ var CloudClient = class {
900
917
  return conversationPromise;
901
918
  }
902
919
  async sendWebsiteMap(snapshot) {
903
- await this.safePost("/website-maps", snapshot);
920
+ throw new ConfigurationError("Website-map upload is not defined by the approved SDK API contract.");
904
921
  }
905
922
  async sendAnalytics(events) {
906
- await this.safePost("/analytics", { events });
923
+ throw new ConfigurationError("Analytics upload is not defined by the approved SDK API contract.");
907
924
  }
908
925
  async sendTelemetryEvent(eventType, metadata = {}) {
909
- try {
910
- const origin = typeof window !== "undefined" ? window.location.origin : void 0;
911
- const installationId = this.runtimeAuth ? this.runtimeAuth.options?.installationId : void 0;
912
- const sanitizedMeta = {
913
- sdkVersion: SDK_VERSION
914
- };
915
- for (const [key, val] of Object.entries(metadata)) {
916
- if (/(token|secret|cookie|session|api.?key|password|bearer|authorization)/i.test(key)) {
917
- continue;
918
- }
919
- if (typeof val === "string") {
920
- sanitizedMeta[key] = sanitizeText(val, 512);
921
- } else if (typeof val === "number" || typeof val === "boolean") {
922
- sanitizedMeta[key] = val;
923
- } else if (val && typeof val === "object" && !Array.isArray(val)) {
924
- sanitizedMeta[key] = val;
925
- }
926
- }
927
- const payload = {
928
- projectId: this.projectId,
929
- publicKey: this.publicKey,
930
- eventType,
931
- installationId,
932
- origin,
933
- metadata: sanitizedMeta
934
- };
935
- const baseUrl = this.getApiBaseUrl();
936
- const targetUrl = baseUrl.includes("localhost") || baseUrl.includes("127.0.0.1") ? `${baseUrl.replace(/\/functions\/v1.*$/, "").replace(/\/api\/v1.*$/, "")}/api/v1/events` : "https://asiyst.com/api/v1/events";
937
- await fetch(targetUrl, {
938
- method: "POST",
939
- headers: {
940
- "Content-Type": "application/json",
941
- Accept: "application/json",
942
- "x-asiyst-public-key": this.publicKey
943
- },
944
- body: JSON.stringify(payload)
945
- });
946
- } catch {
947
- }
926
+ throw new ConfigurationError("Telemetry upload is not defined by the approved SDK API contract.");
948
927
  }
949
928
  async sendTaskUpdate(taskId, status, stepId) {
950
- await this.safePost(`/tasks/${encodeURIComponent(taskId)}/events`, {
951
- status,
952
- stepId
953
- });
954
- }
955
- async safePost(path, body) {
956
- try {
957
- await this.runtimeRequest({ path, method: "POST", body, idempotent: true }, "assistant:telemetry");
958
- } catch {
959
- }
929
+ throw new ConfigurationError("Cloud task updates are not defined by the approved SDK API contract.");
960
930
  }
961
931
  async runtimeRequest(request, capability = "assistant:config") {
962
932
  const fullRequest = {
@@ -965,14 +935,32 @@ var CloudClient = class {
965
935
  conversationId: request.conversationId ?? this.conversationId
966
936
  };
967
937
  if (!this.runtimeAuth) {
938
+ if (capability === "assistant:conversation" || capability === "assistant:heartbeat") {
939
+ throw new AuthenticationError("AI request authorization failed because no runtime token is available.");
940
+ }
968
941
  return this.transport.request(fullRequest);
969
942
  }
970
- let token = await this.getAuthToken(capability);
971
- let response = await this.transport.request({ ...fullRequest, authorizationToken: token });
943
+ let token = await this.getAuthToken();
944
+ const withToken = (value) => {
945
+ const headers = new Headers({
946
+ Accept: "application/json",
947
+ "Content-Type": "application/json"
948
+ });
949
+ if (fullRequest.headers) {
950
+ new Headers(fullRequest.headers).forEach((headerValue, key) => headers.set(key, headerValue));
951
+ }
952
+ if (value) headers.set("Authorization", `Bearer ${value}`);
953
+ return this.transport.request({
954
+ ...fullRequest,
955
+ headers,
956
+ canonical: true
957
+ });
958
+ };
959
+ let response = await withToken(token);
972
960
  if (response.status === 401) {
973
961
  if (!this.tokenRefreshPromise) {
974
962
  this.runtimeAuth.invalidate();
975
- this.tokenRefreshPromise = this.runtimeAuth.getToken(capability).then((newToken) => {
963
+ this.tokenRefreshPromise = this.runtimeAuth.getToken().then((newToken) => {
976
964
  this.activeToken = newToken;
977
965
  return newToken;
978
966
  }).finally(() => {
@@ -982,7 +970,7 @@ var CloudClient = class {
982
970
  });
983
971
  }
984
972
  token = await this.tokenRefreshPromise ?? this.activeToken;
985
- response = await this.transport.request({ ...fullRequest, authorizationToken: token });
973
+ response = await withToken(token);
986
974
  }
987
975
  return response;
988
976
  }
@@ -1049,7 +1037,8 @@ var ConfigCache = class {
1049
1037
  if (parsed.schemaVersion !== CONFIG_SCHEMA_VERSION || parsed.projectId !== projectId) {
1050
1038
  return null;
1051
1039
  }
1052
- if (!ignoreTtl && Date.now() - parsed.fetchedAt > CONFIG_CACHE_TTL_MS) {
1040
+ const maxAgeMs = parsed.maxAgeMs ?? CONFIG_CACHE_TTL_MS;
1041
+ if (!ignoreTtl && Date.now() - parsed.fetchedAt > maxAgeMs) {
1053
1042
  return null;
1054
1043
  }
1055
1044
  return normalizeProjectConfig(parsed.config);
@@ -1079,6 +1068,8 @@ var ConfigCache = class {
1079
1068
  fetchedAt: Date.now(),
1080
1069
  etag: meta?.etag,
1081
1070
  revision: meta?.revision ?? config.version,
1071
+ maxAgeMs: meta?.maxAgeMs,
1072
+ staleIfErrorMs: meta?.staleIfErrorMs,
1082
1073
  config
1083
1074
  };
1084
1075
  this.storage.write("config", JSON.stringify(envelope));
@@ -1120,19 +1111,26 @@ var ConfigManager = class {
1120
1111
  async executeRefresh(_options) {
1121
1112
  const prev = this.current;
1122
1113
  try {
1123
- const remote = await this.cloud.fetchConfig();
1124
- const normalized = normalizeProjectConfig(remote);
1114
+ const cached = this.cache.getEnvelope(this.options.projectId);
1115
+ const normalized = normalizeProjectConfig(await this.cloud.fetchConfig(cached?.etag, cached?.config));
1116
+ const receivedMetadata = this.cloud.getConfigMetadata?.() ?? {};
1117
+ const metadata = {
1118
+ ...receivedMetadata,
1119
+ maxAgeMs: receivedMetadata.maxAgeMs ?? cached?.maxAgeMs,
1120
+ staleIfErrorMs: receivedMetadata.staleIfErrorMs ?? cached?.staleIfErrorMs
1121
+ };
1125
1122
  this.current = normalized;
1126
- this.cache.write(this.options.projectId, normalized);
1123
+ this.cache.write(this.options.projectId, normalized, metadata);
1127
1124
  const hasChanged = prev.version !== normalized.version || prev.avatarName !== normalized.avatarName || prev.position !== normalized.position || prev.size !== normalized.size || prev.assetUrl !== normalized.assetUrl || prev.thumbnailUrl !== normalized.thumbnailUrl || JSON.stringify(prev.theme) !== JSON.stringify(normalized.theme) || JSON.stringify(prev.animations) !== JSON.stringify(normalized.animations);
1128
1125
  if (hasChanged && this.onConfigUpdated) {
1129
1126
  this.onConfigUpdated(normalized, prev);
1130
1127
  }
1131
1128
  return this.current;
1132
1129
  } catch (error) {
1133
- const lastKnownGood = this.cache.read(this.options.projectId, true);
1134
- if (lastKnownGood) {
1135
- this.current = lastKnownGood;
1130
+ const cached = this.cache.getEnvelope(this.options.projectId);
1131
+ const staleIfErrorMs = cached?.staleIfErrorMs ?? API_LIMITS.configStaleIfErrorMs;
1132
+ if (cached && staleIfErrorMs > 0 && Date.now() - cached.fetchedAt <= staleIfErrorMs) {
1133
+ this.current = normalizeProjectConfig(cached.config);
1136
1134
  }
1137
1135
  this.events.emit("asiyst:error", {
1138
1136
  code: "config_refresh_failed",
@@ -1809,7 +1807,7 @@ var CHUNK_TYPE_JSON = 1313821514;
1809
1807
  var CHUNK_TYPE_BIN = 5130562;
1810
1808
  var AssetLoader = class {
1811
1809
  constructor() {
1812
- this.inFlightController = null;
1810
+ this.inFlightControllers = /* @__PURE__ */ new Set();
1813
1811
  this.createdObjectUrls = [];
1814
1812
  this.inFlightLoads = /* @__PURE__ */ new Map();
1815
1813
  this.cachedAssets = /* @__PURE__ */ new Map();
@@ -1819,31 +1817,42 @@ var AssetLoader = class {
1819
1817
  if (!sanitizedUrl) {
1820
1818
  throw new Error("Asset URL is required");
1821
1819
  }
1822
- const cached = this.cachedAssets.get(sanitizedUrl);
1820
+ let parsedUrl;
1821
+ try {
1822
+ parsedUrl = new URL(sanitizedUrl, typeof location === "undefined" ? void 0 : location.href);
1823
+ } catch {
1824
+ throw new Error("Avatar asset URL is invalid");
1825
+ }
1826
+ if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:" || parsedUrl.username || parsedUrl.password) {
1827
+ throw new Error("Avatar asset URL must use HTTP or HTTPS without embedded credentials");
1828
+ }
1829
+ const cacheKey = `${sanitizedUrl}\0${options?.integrity ?? ""}\0${options?.expectedFormat ?? ""}`;
1830
+ const cached = this.cachedAssets.get(cacheKey);
1823
1831
  if (cached) {
1824
1832
  return cached;
1825
1833
  }
1826
- const inFlight = this.inFlightLoads.get(sanitizedUrl);
1834
+ const inFlight = this.inFlightLoads.get(cacheKey);
1827
1835
  if (inFlight) {
1828
1836
  return inFlight;
1829
1837
  }
1830
1838
  const loadPromise = this.performLoad(sanitizedUrl, options);
1831
- this.inFlightLoads.set(sanitizedUrl, loadPromise);
1839
+ this.inFlightLoads.set(cacheKey, loadPromise);
1832
1840
  try {
1833
1841
  const asset = await loadPromise;
1834
- this.cachedAssets.set(sanitizedUrl, asset);
1842
+ this.cachedAssets.set(cacheKey, asset);
1835
1843
  return asset;
1836
1844
  } finally {
1837
- this.inFlightLoads.delete(sanitizedUrl);
1845
+ this.inFlightLoads.delete(cacheKey);
1838
1846
  }
1839
1847
  }
1840
1848
  async performLoad(sanitizedUrl, options) {
1841
1849
  const startTime = Date.now();
1842
- this.inFlightController = new AbortController();
1843
- const abortSignal = options?.signal ? anySignal([this.inFlightController.signal, options.signal]) : this.inFlightController.signal;
1850
+ const controller = new AbortController();
1851
+ this.inFlightControllers.add(controller);
1852
+ const abortSignal = options?.signal ? anySignal([controller.signal, options.signal]) : controller.signal;
1844
1853
  const timeoutMs = options?.timeoutMs ?? 6e4;
1845
1854
  const timeoutId = setTimeout(() => {
1846
- this.inFlightController?.abort();
1855
+ controller.abort();
1847
1856
  }, timeoutMs);
1848
1857
  try {
1849
1858
  const cleanPath = (sanitizedUrl.split("?")[0] ?? "").toLowerCase();
@@ -1917,12 +1926,25 @@ var AssetLoader = class {
1917
1926
  if (arrayBuffer.byteLength < 12) {
1918
1927
  throw new Error("Avatar asset payload is too small to be a valid 3D container");
1919
1928
  }
1929
+ if (options?.integrity) {
1930
+ await verifyIntegrity(arrayBuffer, options.integrity);
1931
+ }
1920
1932
  const headerBytes = new Uint8Array(arrayBuffer, 0, Math.min(256, arrayBuffer.byteLength));
1921
1933
  const headerStr = new TextDecoder("utf-8", { fatal: false }).decode(headerBytes).trim();
1922
1934
  if (/^<!DOCTYPE\s+html/i.test(headerStr) || /^<html/i.test(headerStr)) {
1923
1935
  throw new Error(`Avatar asset payload contains HTML error page instead of binary 3D container from ${sanitizedUrl}`);
1924
1936
  }
1925
- if (isFbxExtension || this.isFbxBuffer(arrayBuffer) || !isGlbExtension && !this.isGlbBuffer(arrayBuffer)) {
1937
+ const hasFbxSignature = this.isFbxBuffer(arrayBuffer);
1938
+ const hasGlbSignature = this.isGlbBuffer(arrayBuffer);
1939
+ const isFbx = hasFbxSignature || !hasGlbSignature && isFbxExtension;
1940
+ const isGlb = hasGlbSignature || !hasFbxSignature && isGlbExtension;
1941
+ if (isFbx && isGlb) {
1942
+ throw new Error("Avatar asset format is ambiguous");
1943
+ }
1944
+ if (isFbx) {
1945
+ if (options?.expectedFormat && options.expectedFormat !== "fbx") {
1946
+ throw new Error(`Avatar asset format mismatch: expected ${options.expectedFormat}, received fbx`);
1947
+ }
1926
1948
  const fbxHeader = this.parseFbxHeader(arrayBuffer);
1927
1949
  const resourcePath = sanitizedUrl.includes("/") ? sanitizedUrl.substring(0, sanitizedUrl.lastIndexOf("/") + 1) : "";
1928
1950
  return {
@@ -1935,6 +1957,12 @@ var AssetLoader = class {
1935
1957
  durationMs: Date.now() - startTime
1936
1958
  };
1937
1959
  }
1960
+ if (!isGlb) {
1961
+ throw new Error("Avatar asset format is unsupported; expected FBX or GLB");
1962
+ }
1963
+ if (options?.expectedFormat && options.expectedFormat !== "glb") {
1964
+ throw new Error(`Avatar asset format mismatch: expected ${options.expectedFormat}, received glb`);
1965
+ }
1938
1966
  const parsedGlb = this.parseGlb(arrayBuffer);
1939
1967
  return {
1940
1968
  format: "glb",
@@ -1947,7 +1975,7 @@ var AssetLoader = class {
1947
1975
  };
1948
1976
  } finally {
1949
1977
  clearTimeout(timeoutId);
1950
- this.inFlightController = null;
1978
+ this.inFlightControllers.delete(controller);
1951
1979
  }
1952
1980
  }
1953
1981
  isFbxBuffer(buffer) {
@@ -2163,10 +2191,8 @@ var AssetLoader = class {
2163
2191
  };
2164
2192
  }
2165
2193
  destroy() {
2166
- if (this.inFlightController) {
2167
- this.inFlightController.abort();
2168
- this.inFlightController = null;
2169
- }
2194
+ for (const controller of this.inFlightControllers) controller.abort();
2195
+ this.inFlightControllers.clear();
2170
2196
  this.inFlightLoads.clear();
2171
2197
  this.cachedAssets.clear();
2172
2198
  if (typeof URL !== "undefined" && typeof URL.revokeObjectURL === "function") {
@@ -2180,6 +2206,20 @@ var AssetLoader = class {
2180
2206
  this.createdObjectUrls.length = 0;
2181
2207
  }
2182
2208
  };
2209
+ async function verifyIntegrity(buffer, integrity) {
2210
+ const [algorithm, expected] = integrity.split("-", 2);
2211
+ if (algorithm !== "sha256" || !expected) {
2212
+ throw new Error("Avatar asset integrity metadata is invalid");
2213
+ }
2214
+ const cryptoApi = globalThis.crypto;
2215
+ if (!cryptoApi?.subtle) return;
2216
+ const digest = new Uint8Array(await cryptoApi.subtle.digest("SHA-256", buffer));
2217
+ let binary = "";
2218
+ for (const byte of digest) binary += String.fromCharCode(byte);
2219
+ if (btoa(binary) !== expected) {
2220
+ throw new Error("Avatar asset integrity verification failed");
2221
+ }
2222
+ }
2183
2223
  function anySignal(signals) {
2184
2224
  const controller = new AbortController();
2185
2225
  for (const sig of signals) {
@@ -2209,6 +2249,7 @@ var FbxRenderer = class {
2209
2249
  this.facing = "right";
2210
2250
  this.currentPose = "idle";
2211
2251
  this.initialRenderCompleted = false;
2252
+ this.baseScale = 1;
2212
2253
  }
2213
2254
  async mount(container, asset, options) {
2214
2255
  const doc = container.ownerDocument;
@@ -2226,13 +2267,17 @@ var FbxRenderer = class {
2226
2267
  throw new Error("WebGLRenderingContext is not available or supported in this browser environment");
2227
2268
  }
2228
2269
  const isMobile = typeof window !== "undefined" && window.innerWidth <= 640;
2229
- const width = options?.width || (isMobile ? 180 : 240);
2230
- const height = options?.height || (isMobile ? 360 : 460);
2270
+ const width = options?.width || (isMobile ? 140 : 190);
2271
+ const height = options?.height || (isMobile ? 280 : 360);
2231
2272
  const dpr = typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1;
2232
2273
  this.canvas.width = Math.round(width * dpr);
2233
2274
  this.canvas.height = Math.round(height * dpr);
2234
2275
  this.canvas.style.width = `${width}px`;
2235
2276
  this.canvas.style.height = `${height}px`;
2277
+ this.canvas.style.pointerEvents = "none";
2278
+ this.canvas.style.border = "none";
2279
+ this.canvas.style.outline = "none";
2280
+ this.canvas.style.boxShadow = "none";
2236
2281
  try {
2237
2282
  this.renderer = new THREE.WebGLRenderer({
2238
2283
  canvas: this.canvas,
@@ -2259,6 +2304,13 @@ var FbxRenderer = class {
2259
2304
  keyLight.castShadow = true;
2260
2305
  keyLight.shadow.mapSize.width = 512;
2261
2306
  keyLight.shadow.mapSize.height = 512;
2307
+ keyLight.shadow.camera.near = 0.5;
2308
+ keyLight.shadow.camera.far = 15;
2309
+ keyLight.shadow.camera.left = -1.5;
2310
+ keyLight.shadow.camera.right = 1.5;
2311
+ keyLight.shadow.camera.top = 2.5;
2312
+ keyLight.shadow.camera.bottom = -0.5;
2313
+ keyLight.shadow.bias = -5e-4;
2262
2314
  this.scene.add(keyLight);
2263
2315
  const fillLight = new THREE.DirectionalLight(15459032, 1.2);
2264
2316
  fillLight.position.set(-3, 2, 2);
@@ -2267,7 +2319,13 @@ var FbxRenderer = class {
2267
2319
  rimLight.position.set(0, 4, -3);
2268
2320
  this.scene.add(rimLight);
2269
2321
  const shadowGeo = new THREE.PlaneGeometry(3, 3);
2270
- const shadowMat = new THREE.ShadowMaterial({ opacity: 0.15 });
2322
+ const shadowMat = new THREE.ShadowMaterial({
2323
+ opacity: 0.12,
2324
+ depthWrite: false
2325
+ });
2326
+ shadowMat.polygonOffset = true;
2327
+ shadowMat.polygonOffsetFactor = -1;
2328
+ shadowMat.polygonOffsetUnits = -4;
2271
2329
  const shadowPlane = new THREE.Mesh(shadowGeo, shadowMat);
2272
2330
  shadowPlane.rotation.x = -Math.PI / 2;
2273
2331
  shadowPlane.position.y = 0;
@@ -2319,14 +2377,18 @@ var FbxRenderer = class {
2319
2377
  rawObject.position.set(-rawCenter.x, -rawBox.min.y, -rawCenter.z);
2320
2378
  const targetVisualHeight = 1.8;
2321
2379
  const targetScale = targetVisualHeight / rawHeight;
2380
+ this.baseScale = targetScale;
2322
2381
  this.modelRoot = new THREE.Group();
2323
2382
  this.modelRoot.add(rawObject);
2324
2383
  this.modelRoot.scale.setScalar(targetScale);
2325
2384
  this.scene.add(this.modelRoot);
2326
- const visualCenterY = targetVisualHeight * 0.52;
2385
+ const visualCenterY = targetVisualHeight * 0.5;
2327
2386
  const fovRadians = this.camera.fov * Math.PI / 180;
2328
- const fitDist = Math.max(2.4, targetVisualHeight / 2 / Math.tan(fovRadians / 2) * 1.25);
2329
- this.camera.position.set(0, visualCenterY + 0.1, fitDist);
2387
+ const aspect = width / height;
2388
+ const fitDistV = targetVisualHeight * 1.35 / 2 / Math.tan(fovRadians / 2);
2389
+ const fitDistH = 1.1 / 2 / (aspect * Math.tan(fovRadians / 2));
2390
+ const fitDist = Math.max(fitDistV, fitDistH, 2.85);
2391
+ this.camera.position.set(0, visualCenterY, fitDist);
2330
2392
  this.camera.lookAt(0, visualCenterY, 0);
2331
2393
  rawObject.traverse((child) => {
2332
2394
  const mesh = child;
@@ -2335,20 +2397,25 @@ var FbxRenderer = class {
2335
2397
  mesh.receiveShadow = true;
2336
2398
  }
2337
2399
  });
2400
+ options?.metricsTracker?.record("sceneInitComplete");
2338
2401
  this.rawObject = rawObject;
2339
2402
  this.mixer = new THREE.AnimationMixer(rawObject);
2340
2403
  this.allAnimations = [...modelAnimations];
2341
2404
  const externalAnims = options?.config?.animations || options?.config?.avatar?.animations || [];
2342
2405
  if (externalAnims.length > 0) {
2343
- try {
2344
- await Promise.race([
2345
- this.loadExternalAnimations(externalAnims, options?.config?.animation),
2346
- new Promise((resolve) => setTimeout(resolve, 8e3))
2347
- ]);
2348
- } catch (animErr) {
2349
- if (typeof console !== "undefined" && typeof console.warn === "function") {
2350
- console.warn("[asiyst] External animation loading notice:", animErr);
2406
+ if (modelAnimations.length === 0) {
2407
+ try {
2408
+ await Promise.race([
2409
+ this.loadExternalAnimations(externalAnims, options?.config?.animation),
2410
+ new Promise((resolve) => setTimeout(resolve, 2500))
2411
+ ]);
2412
+ } catch (animErr) {
2413
+ if (typeof console !== "undefined" && typeof console.warn === "function") {
2414
+ console.warn("[asiyst] External animation loading notice:", animErr);
2415
+ }
2351
2416
  }
2417
+ } else {
2418
+ void this.loadExternalAnimations(externalAnims, options?.config?.animation);
2352
2419
  }
2353
2420
  }
2354
2421
  this.startInitialIdleAnimation(options?.config);
@@ -2360,9 +2427,11 @@ var FbxRenderer = class {
2360
2427
  try {
2361
2428
  this.renderer.render(this.scene, this.camera);
2362
2429
  this.initialRenderCompleted = true;
2430
+ options?.metricsTracker?.record("firstRenderedFrame");
2363
2431
  if (this.canvas) {
2364
2432
  this.canvas.style.opacity = "1";
2365
2433
  }
2434
+ options?.metricsTracker?.record("firstVisibleCorrectlyFramed");
2366
2435
  } catch (renderErr) {
2367
2436
  const msg = renderErr instanceof Error ? renderErr.message : String(renderErr);
2368
2437
  throw new Error(`Initial FBX WebGL render failed: ${msg}`);
@@ -2391,53 +2460,29 @@ var FbxRenderer = class {
2391
2460
  if (this.playAnimation(pose)) {
2392
2461
  return;
2393
2462
  }
2394
- if (this.mixer && this.allAnimations.length > 0) {
2395
- let targetClip;
2396
- if (pose === "speak") {
2397
- targetClip = this.allAnimations.find(
2398
- (c) => c.name.toLowerCase().includes("talk") || c.name.toLowerCase().includes("speak")
2399
- );
2400
- } else if (pose === "think") {
2401
- targetClip = this.allAnimations.find(
2402
- (c) => c.name.toLowerCase().includes("think")
2403
- );
2404
- } else {
2405
- targetClip = this.allAnimations.find((c) => c.name.toLowerCase().includes("idle")) || this.animationMetadataList[0]?.clip || this.allAnimations[0];
2406
- }
2407
- if (targetClip) {
2408
- const newAction = this.mixer.clipAction(targetClip);
2409
- if (newAction !== this.currentAction) {
2410
- newAction.reset().fadeIn(0.25).play();
2411
- if (this.currentAction) {
2412
- this.currentAction.fadeOut(0.25);
2413
- }
2414
- this.currentAction = newAction;
2415
- return;
2416
- } else if (!this.currentAction?.isRunning()) {
2417
- this.currentAction?.play();
2418
- return;
2419
- }
2420
- return;
2421
- }
2422
- }
2423
2463
  if (!this.modelRoot) return;
2464
+ this.modelRoot.scale.setScalar(this.baseScale);
2424
2465
  switch (pose) {
2425
2466
  case "point":
2426
- this.modelRoot.rotation.z = -0.15;
2427
- this.modelRoot.rotation.x = 0.08;
2467
+ this.modelRoot.rotation.z = -0.06;
2468
+ this.modelRoot.rotation.x = 0.03;
2428
2469
  break;
2429
2470
  case "think":
2430
- this.modelRoot.rotation.z = 0.12;
2431
- this.modelRoot.rotation.x = -0.1;
2471
+ this.modelRoot.rotation.z = 0.05;
2472
+ this.modelRoot.rotation.x = -0.04;
2432
2473
  break;
2433
2474
  case "speak":
2434
2475
  this.modelRoot.rotation.y = this.facing === "left" ? -0.22 : 0.22;
2435
- this.modelRoot.rotation.x = 0.04;
2476
+ this.modelRoot.rotation.x = 0.03;
2436
2477
  break;
2437
2478
  case "celebrate":
2438
2479
  this.modelRoot.rotation.z = 0;
2439
- this.modelRoot.rotation.x = -0.15;
2440
- this.modelRoot.scale.multiplyScalar(1.05);
2480
+ this.modelRoot.rotation.x = -0.06;
2481
+ break;
2482
+ case "walk":
2483
+ this.modelRoot.rotation.z = 0;
2484
+ this.modelRoot.rotation.x = 0.03;
2485
+ this.modelRoot.rotation.y = this.facing === "left" ? -0.35 : 0.35;
2441
2486
  break;
2442
2487
  default:
2443
2488
  this.modelRoot.rotation.z = 0;
@@ -2459,13 +2504,13 @@ var FbxRenderer = class {
2459
2504
  return true;
2460
2505
  }
2461
2506
  const idleByName = this.animationMetadataList.find(
2462
- (m) => m.name.toLowerCase().includes("idle") || m.clipName && m.clipName.toLowerCase().includes("idle")
2507
+ (m) => m.name.toLowerCase() === "idle" || m.clipName?.toLowerCase() === "idle"
2463
2508
  );
2464
2509
  if (idleByName && this.playAnimation(idleByName.id || idleByName.name)) {
2465
2510
  return true;
2466
2511
  }
2467
2512
  const embeddedIdle = this.allAnimations.find(
2468
- (c) => c.name.toLowerCase().includes("idle")
2513
+ (c) => c.name.toLowerCase() === "idle"
2469
2514
  );
2470
2515
  if (embeddedIdle) {
2471
2516
  const action = this.mixer.clipAction(embeddedIdle);
@@ -2476,69 +2521,65 @@ var FbxRenderer = class {
2476
2521
  }
2477
2522
  return true;
2478
2523
  }
2479
- if (this.animationMetadataList.length > 0) {
2480
- const firstMeta = this.animationMetadataList[0];
2481
- if (this.playAnimation(firstMeta.id || firstMeta.name)) {
2482
- return true;
2483
- }
2484
- }
2485
- if (this.allAnimations.length > 0) {
2486
- const firstClip = this.allAnimations[0];
2487
- const action = this.mixer.clipAction(firstClip);
2488
- if (this.currentAction !== action) {
2489
- action.reset().fadeIn(0.25).play();
2490
- if (this.currentAction) this.currentAction.fadeOut(0.25);
2491
- this.currentAction = action;
2492
- }
2493
- return true;
2494
- }
2495
2524
  return false;
2496
2525
  }
2497
2526
  async loadExternalAnimations(animations, targetAnimationName) {
2498
2527
  if (!this.rawObject || !this.mixer) return;
2499
- for (const anim of animations) {
2500
- if (!anim.assetUrl) continue;
2501
- try {
2502
- const loaded = await this.assetLoader.load(anim.assetUrl);
2503
- let extractedClips = [];
2504
- if (loaded.format === "fbx") {
2505
- const loader = new FBXLoader();
2506
- if (loaded.resourcePath) {
2507
- loader.setResourcePath(loaded.resourcePath);
2508
- }
2509
- const parsed = loader.parse(loaded.buffer, loaded.resourcePath || "");
2510
- extractedClips = parsed.animations || [];
2511
- } else if (loaded.format === "glb") {
2512
- const loader = new GLTFLoader();
2513
- const gltf = await new Promise((resolve, reject) => {
2514
- const glbBuffer = loaded.bin.buffer.slice(
2515
- loaded.bin.byteOffset,
2516
- loaded.bin.byteOffset + loaded.bin.byteLength
2517
- );
2518
- loader.parse(glbBuffer, loaded.url, resolve, reject);
2519
- });
2520
- extractedClips = gltf.animations || [];
2521
- }
2522
- for (const rawClip of extractedClips) {
2523
- const retargeted = this.retargetClip(rawClip, this.rawObject);
2524
- if (!retargeted) continue;
2525
- retargeted.name = anim.clipName || anim.name || rawClip.name;
2526
- this.allAnimations.push(retargeted);
2527
- this.animationMetadataList.push({
2528
- id: anim.id,
2529
- name: anim.name,
2530
- intent: anim.intent,
2531
- clipName: anim.clipName,
2532
- loopMode: anim.loopMode,
2533
- clip: retargeted
2534
- });
2535
- }
2536
- } catch (err) {
2537
- if (typeof console !== "undefined" && typeof console.warn === "function") {
2538
- const msg = err instanceof Error ? err.message : String(err);
2539
- console.warn(`[asiyst] Failed to load external animation "${anim.name}": ${msg}`);
2540
- }
2528
+ const pending = animations.filter(
2529
+ (anim) => {
2530
+ if (!anim.assetUrl) return false;
2531
+ const key = (anim.id || anim.name).toLowerCase();
2532
+ return !this.animationMetadataList.some(
2533
+ (m) => m.id && m.id.toLowerCase() === key || m.name.toLowerCase() === key
2534
+ );
2541
2535
  }
2536
+ );
2537
+ if (pending.length > 0) {
2538
+ await Promise.allSettled(
2539
+ pending.map(async (anim) => {
2540
+ try {
2541
+ const loaded = await this.assetLoader.load(anim.assetUrl, { integrity: anim.integrity });
2542
+ let extractedClips = [];
2543
+ if (loaded.format === "fbx") {
2544
+ const loader = new FBXLoader();
2545
+ if (loaded.resourcePath) {
2546
+ loader.setResourcePath(loaded.resourcePath);
2547
+ }
2548
+ const parsed = loader.parse(loaded.buffer, loaded.resourcePath || "");
2549
+ extractedClips = parsed.animations || [];
2550
+ } else if (loaded.format === "glb") {
2551
+ const loader = new GLTFLoader();
2552
+ const gltf = await new Promise((resolve, reject) => {
2553
+ const glbBuffer = loaded.bin.buffer.slice(
2554
+ loaded.bin.byteOffset,
2555
+ loaded.bin.byteOffset + loaded.bin.byteLength
2556
+ );
2557
+ loader.parse(glbBuffer, loaded.url, resolve, reject);
2558
+ });
2559
+ extractedClips = gltf.animations || [];
2560
+ }
2561
+ for (const rawClip of extractedClips) {
2562
+ const retargeted = this.retargetClip(rawClip, this.rawObject);
2563
+ if (!retargeted) continue;
2564
+ retargeted.name = anim.clipName || anim.name || rawClip.name;
2565
+ this.allAnimations.push(retargeted);
2566
+ this.animationMetadataList.push({
2567
+ id: anim.id,
2568
+ name: anim.name,
2569
+ intent: anim.intent,
2570
+ clipName: anim.clipName,
2571
+ loopMode: anim.loopMode,
2572
+ clip: retargeted
2573
+ });
2574
+ }
2575
+ } catch (err) {
2576
+ if (typeof console !== "undefined" && typeof console.warn === "function") {
2577
+ const msg = err instanceof Error ? err.message : String(err);
2578
+ console.warn(`[asiyst] Failed to load external animation "${anim.name}": ${msg}`);
2579
+ }
2580
+ }
2581
+ })
2582
+ );
2542
2583
  }
2543
2584
  if (this.currentPose === "idle" || targetAnimationName) {
2544
2585
  this.startInitialIdleAnimation({ animation: targetAnimationName });
@@ -2623,13 +2664,13 @@ var FbxRenderer = class {
2623
2664
  clip = this.allAnimations.find((c) => c.name.toLowerCase() === query);
2624
2665
  }
2625
2666
  if (!clip) {
2626
- clip = this.allAnimations.find((c) => c.name.toLowerCase().includes(query));
2667
+ clip = this.allAnimations.find((c) => c.name.toLowerCase() === query);
2627
2668
  }
2628
2669
  if (!clip) {
2629
2670
  return false;
2630
2671
  }
2631
2672
  const action = this.mixer.clipAction(clip);
2632
- const effectiveLoop = loopMode || matched?.loopMode || "repeat";
2673
+ const effectiveLoop = (loopMode || matched?.loopMode || "loop").toLowerCase();
2633
2674
  if (effectiveLoop === "once") {
2634
2675
  action.setLoop(THREE.LoopOnce, 1);
2635
2676
  action.clampWhenFinished = true;
@@ -2675,9 +2716,17 @@ var FbxRenderer = class {
2675
2716
  }
2676
2717
  startLoop() {
2677
2718
  if (typeof requestAnimationFrame === "undefined") return;
2719
+ if (this.animFrameId !== null && typeof cancelAnimationFrame !== "undefined") {
2720
+ cancelAnimationFrame(this.animFrameId);
2721
+ this.animFrameId = null;
2722
+ }
2678
2723
  this.lastTime = typeof performance !== "undefined" ? performance.now() : Date.now();
2679
2724
  const tick = (now) => {
2680
2725
  if (!this.renderer || !this.scene || !this.camera) return;
2726
+ if (typeof document !== "undefined" && document.hidden) {
2727
+ this.animFrameId = requestAnimationFrame(tick);
2728
+ return;
2729
+ }
2681
2730
  const current = now || (typeof performance !== "undefined" ? performance.now() : Date.now());
2682
2731
  const delta = Math.min(Math.max((current - this.lastTime) / 1e3, 0), 0.1);
2683
2732
  this.lastTime = current;
@@ -2747,14 +2796,23 @@ var FbxRenderer = class {
2747
2796
  handleResize() {
2748
2797
  if (!this.canvas || !this.renderer || !this.camera) return;
2749
2798
  const isMobile = typeof window !== "undefined" && window.innerWidth <= 640;
2750
- const width = isMobile ? 180 : 240;
2751
- const height = isMobile ? 360 : 460;
2799
+ const width = isMobile ? 140 : 190;
2800
+ const height = isMobile ? 280 : 360;
2752
2801
  const dpr = typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1;
2753
2802
  this.canvas.width = Math.round(width * dpr);
2754
2803
  this.canvas.height = Math.round(height * dpr);
2755
2804
  this.canvas.style.width = `${width}px`;
2756
2805
  this.canvas.style.height = `${height}px`;
2757
- this.camera.aspect = width / height;
2806
+ const aspect = width / height;
2807
+ this.camera.aspect = aspect;
2808
+ const targetVisualHeight = 1.8;
2809
+ const visualCenterY = targetVisualHeight * 0.5;
2810
+ const fovRadians = this.camera.fov * Math.PI / 180;
2811
+ const fitDistV = targetVisualHeight * 1.35 / 2 / Math.tan(fovRadians / 2);
2812
+ const fitDistH = 1.1 / 2 / (aspect * Math.tan(fovRadians / 2));
2813
+ const fitDist = Math.max(fitDistV, fitDistH, 2.85);
2814
+ this.camera.position.set(0, visualCenterY, fitDist);
2815
+ this.camera.lookAt(0, visualCenterY, 0);
2758
2816
  this.camera.updateProjectionMatrix();
2759
2817
  this.renderer.setPixelRatio(Math.min(dpr, 2));
2760
2818
  this.renderer.setSize(width, height, false);
@@ -2779,7 +2837,7 @@ var AVATAR_CSS = `
2779
2837
  flex-direction: column;
2780
2838
  align-items: center;
2781
2839
  gap: 4px;
2782
- pointer-events: auto;
2840
+ pointer-events: none;
2783
2841
  user-select: none;
2784
2842
  }
2785
2843
  .asiyst-avatar.asiyst-animate {
@@ -2790,11 +2848,27 @@ var AVATAR_CSS = `
2790
2848
  place-items: center;
2791
2849
  position: relative;
2792
2850
  cursor: pointer;
2793
- border: none;
2851
+ border: 0 !important;
2794
2852
  padding: 0;
2795
- outline: none;
2796
- background: transparent;
2853
+ margin: 0;
2854
+ outline: none !important;
2855
+ background: transparent !important;
2856
+ box-shadow: none !important;
2797
2857
  overflow: visible;
2858
+ -webkit-appearance: none;
2859
+ appearance: none;
2860
+ -webkit-tap-highlight-color: transparent;
2861
+ }
2862
+ .asiyst-figure:focus,
2863
+ .asiyst-figure:focus-visible,
2864
+ .asiyst-figure:active {
2865
+ outline: none !important;
2866
+ border: 0 !important;
2867
+ box-shadow: none !important;
2868
+ }
2869
+ .asiyst-figure::-moz-focus-inner {
2870
+ border: 0 !important;
2871
+ padding: 0;
2798
2872
  }
2799
2873
  .asiyst-figure.asiyst-compact-launcher {
2800
2874
  border-radius: 28px;
@@ -2802,20 +2876,24 @@ var AVATAR_CSS = `
2802
2876
  font: 700 14px/1.2 system-ui, sans-serif;
2803
2877
  box-shadow: 0 10px 30px rgba(15, 23, 42, 0.28);
2804
2878
  overflow: hidden;
2805
- background: #2563eb;
2879
+ background: #2563eb !important;
2880
+ pointer-events: auto;
2806
2881
  }
2807
2882
  .asiyst-figure.asiyst-3d-active {
2808
- width: 240px !important;
2809
- height: 460px !important;
2883
+ width: 190px !important;
2884
+ height: 360px !important;
2810
2885
  background: transparent !important;
2886
+ border: 0 !important;
2811
2887
  border-radius: 0 !important;
2812
2888
  box-shadow: none !important;
2889
+ outline: none !important;
2813
2890
  overflow: visible !important;
2891
+ pointer-events: none;
2814
2892
  }
2815
2893
  @media (max-width: 640px) {
2816
2894
  .asiyst-figure.asiyst-3d-active {
2817
- width: 180px !important;
2818
- height: 360px !important;
2895
+ width: 140px !important;
2896
+ height: 280px !important;
2819
2897
  }
2820
2898
  }
2821
2899
  .asiyst-avatar-viewport {
@@ -2824,16 +2902,23 @@ var AVATAR_CSS = `
2824
2902
  height: 100%;
2825
2903
  display: grid;
2826
2904
  place-items: center;
2905
+ border: 0 !important;
2906
+ outline: none !important;
2907
+ background: transparent !important;
2827
2908
  border-radius: inherit;
2828
2909
  overflow: visible;
2829
- pointer-events: auto;
2910
+ pointer-events: none;
2830
2911
  }
2831
2912
  .asiyst-avatar-canvas {
2832
2913
  width: 100%;
2833
2914
  height: 100%;
2834
2915
  object-fit: contain;
2835
2916
  display: block;
2836
- pointer-events: auto;
2917
+ border: 0 !important;
2918
+ outline: none !important;
2919
+ background: transparent !important;
2920
+ box-shadow: none !important;
2921
+ pointer-events: none;
2837
2922
  }
2838
2923
  .asiyst-avatar-graphic {
2839
2924
  width: 100%;
@@ -2983,6 +3068,9 @@ var CssAvatarRenderer = class {
2983
3068
  this.isAssetLoadedFlag = false;
2984
3069
  this.isFallbackFlag = false;
2985
3070
  }
3071
+ setMetricsTracker(tracker) {
3072
+ this.metricsTracker = tracker;
3073
+ }
2986
3074
  mount(container, config) {
2987
3075
  const doc = container.ownerDocument;
2988
3076
  const style = doc.createElement("style");
@@ -3119,7 +3207,10 @@ var CssAvatarRenderer = class {
3119
3207
  this.chatActionBtn.style.display = open ? "none" : "inline-flex";
3120
3208
  }
3121
3209
  }
3122
- async loadAsset(config) {
3210
+ async loadAsset(config, metricsTracker) {
3211
+ if (metricsTracker) {
3212
+ this.metricsTracker = metricsTracker;
3213
+ }
3123
3214
  const assetUrl = config.assetUrl ?? config.thumbnailUrl;
3124
3215
  if (!assetUrl) {
3125
3216
  this.renderState = "idle";
@@ -3151,8 +3242,20 @@ var CssAvatarRenderer = class {
3151
3242
  this.renderLoader();
3152
3243
  }
3153
3244
  try {
3154
- const asset = await this.assetLoader.load(assetUrl, { timeoutMs: 6e4 });
3245
+ this.metricsTracker?.record("assetRequestStart");
3246
+ const asset = await this.assetLoader.load(assetUrl, {
3247
+ timeoutMs: 6e4,
3248
+ integrity: config.assetIntegrity,
3249
+ expectedFormat: config.assetUrl ? config.modelFormat : void 0
3250
+ });
3251
+ this.metricsTracker?.record("assetDownloadComplete");
3252
+ const byteSize = asset.buffer?.byteLength ?? asset.bin?.byteLength ?? asset.size;
3253
+ this.metricsTracker?.setAssetInfo({
3254
+ format: asset.format,
3255
+ byteSize: typeof byteSize === "number" ? byteSize : void 0
3256
+ });
3155
3257
  await this.renderLoadedAsset(asset, config);
3258
+ this.metricsTracker?.record("parseAndDecodeComplete");
3156
3259
  this.renderState = "ready";
3157
3260
  this.isAssetLoadedFlag = true;
3158
3261
  this.isFallbackFlag = false;
@@ -3216,14 +3319,20 @@ var CssAvatarRenderer = class {
3216
3319
  }
3217
3320
  if (asset.format === "fbx" || asset.format === "glb") {
3218
3321
  const isMobile = typeof window !== "undefined" && window.innerWidth <= 640;
3219
- const width = isMobile ? 180 : 240;
3220
- const height = isMobile ? 360 : 460;
3322
+ const width = isMobile ? 140 : 190;
3323
+ const height = isMobile ? 280 : 360;
3221
3324
  this.fbxRenderer = new FbxRenderer();
3222
3325
  this.renderMetrics = await this.fbxRenderer.mount(this.viewport, asset, {
3223
3326
  accentColor: this.accentColor,
3224
3327
  config,
3225
3328
  width,
3226
- height
3329
+ height,
3330
+ metricsTracker: this.metricsTracker
3331
+ });
3332
+ this.metricsTracker?.setAssetInfo({
3333
+ meshCount: this.renderMetrics.meshCount,
3334
+ vertexCount: this.renderMetrics.vertexCount,
3335
+ animationCount: this.renderMetrics.animationCount
3227
3336
  });
3228
3337
  this.fbxRenderer.setFacing(this.facing);
3229
3338
  this.fbxRenderer.setPose(this.pose);
@@ -3239,7 +3348,10 @@ var CssAvatarRenderer = class {
3239
3348
  const thumb = typeof asset.manifest.thumbnailUrl === "string" ? asset.manifest.thumbnailUrl : void 0;
3240
3349
  const modelUrl = typeof asset.manifest.assetUrl === "string" ? asset.manifest.assetUrl : typeof asset.manifest.modelUrl === "string" ? asset.manifest.modelUrl : void 0;
3241
3350
  if (modelUrl) {
3242
- const subAsset = await this.assetLoader.load(modelUrl, { timeoutMs: 6e4 });
3351
+ const subAsset = await this.assetLoader.load(modelUrl, {
3352
+ timeoutMs: 6e4,
3353
+ expectedFormat: config.modelFormat
3354
+ });
3243
3355
  await this.renderLoadedAsset(subAsset, config);
3244
3356
  } else if (thumb) {
3245
3357
  this.viewport.replaceChildren();
@@ -3314,7 +3426,7 @@ var CssAvatarRenderer = class {
3314
3426
  getSize() {
3315
3427
  if (this.isAssetLoadedFlag || this.has3dAssetConfigured) {
3316
3428
  const isMobile = typeof window !== "undefined" && window.innerWidth <= 640;
3317
- return { width: isMobile ? 180 : 240, height: isMobile ? 390 : 490 };
3429
+ return { width: isMobile ? 140 : 190, height: isMobile ? 310 : 390 };
3318
3430
  }
3319
3431
  return { width: this.size, height: this.size + 28 };
3320
3432
  }
@@ -4033,11 +4145,10 @@ function transition(from, to) {
4033
4145
 
4034
4146
  // src/task/TaskEngine.ts
4035
4147
  var TaskEngine = class {
4036
- constructor(interaction, events, analytics, cloud) {
4148
+ constructor(interaction, events, analytics) {
4037
4149
  this.interaction = interaction;
4038
4150
  this.events = events;
4039
4151
  this.analytics = analytics;
4040
- this.cloud = cloud;
4041
4152
  this.status = TaskStatus.Idle;
4042
4153
  this.abort = false;
4043
4154
  }
@@ -4053,7 +4164,6 @@ var TaskEngine = class {
4053
4164
  this.events.emit("asiyst:task:started", { taskId: task.id });
4054
4165
  this.analytics.track("task_started", { taskId: task.id });
4055
4166
  this.analytics.track("guide_started", { taskId: task.id });
4056
- void this.cloud.sendTaskUpdate(task.id, this.status);
4057
4167
  try {
4058
4168
  for (const [index, step] of task.steps.entries()) {
4059
4169
  if (this.abort) {
@@ -4088,13 +4198,11 @@ var TaskEngine = class {
4088
4198
  }
4089
4199
  this.move(TaskStatus.StepCompleted);
4090
4200
  this.events.emit("asiyst:task:step-completed", { taskId: task.id, stepId: step.id });
4091
- void this.cloud.sendTaskUpdate(task.id, this.status, step.id);
4092
4201
  }
4093
4202
  this.move(TaskStatus.TaskCompleted);
4094
4203
  this.events.emit("asiyst:task:completed", { taskId: task.id });
4095
4204
  this.analytics.track("task_completed", { taskId: task.id });
4096
4205
  this.analytics.track("guide_completed", { taskId: task.id });
4097
- void this.cloud.sendTaskUpdate(task.id, this.status);
4098
4206
  this.move(TaskStatus.Idle);
4099
4207
  return TaskStatus.TaskCompleted;
4100
4208
  } catch (error) {
@@ -4169,14 +4277,15 @@ var ConversationPanel = class {
4169
4277
  this.onToggle = onToggle;
4170
4278
  this.conversationId = "";
4171
4279
  this.openState = false;
4280
+ this.submitting = false;
4172
4281
  const doc = root.ownerDocument;
4173
4282
  this.style = doc.createElement("style");
4174
4283
  this.style.textContent = `
4175
4284
  .asiyst-panel {
4176
4285
  position: fixed;
4177
- right: 256px;
4286
+ right: 216px;
4178
4287
  bottom: 20px;
4179
- width: min(380px, calc(100vw - 280px));
4288
+ width: min(380px, calc(100vw - 240px));
4180
4289
  max-height: min(560px, 75vh);
4181
4290
  background: #ffffff;
4182
4291
  color: #0f172a;
@@ -4266,6 +4375,9 @@ var ConversationPanel = class {
4266
4375
  getConversationId() {
4267
4376
  return this.conversationId;
4268
4377
  }
4378
+ setConversationId(conversationId) {
4379
+ this.conversationId = conversationId;
4380
+ }
4269
4381
  open() {
4270
4382
  if (!this.conversationId) {
4271
4383
  this.conversationId = `conv_${Date.now().toString(36)}`;
@@ -4280,22 +4392,51 @@ var ConversationPanel = class {
4280
4392
  this.panel.hidden = true;
4281
4393
  this.onToggle(false);
4282
4394
  }
4283
- append(role, text) {
4395
+ append(role, text, citations = []) {
4284
4396
  const item = this.log.ownerDocument.createElement("div");
4285
4397
  item.className = "asiyst-msg";
4286
4398
  item.setAttribute("data-role", role);
4287
4399
  renderSafeText(item, text);
4400
+ for (const citation of citations) {
4401
+ if (!citation.url) continue;
4402
+ let url;
4403
+ try {
4404
+ url = new URL(citation.url);
4405
+ } catch {
4406
+ continue;
4407
+ }
4408
+ if (url.protocol !== "https:") continue;
4409
+ const link = this.log.ownerDocument.createElement("a");
4410
+ link.href = url.href;
4411
+ link.rel = "noopener noreferrer";
4412
+ link.target = "_blank";
4413
+ link.textContent = sanitizeText(citation.title, 160);
4414
+ const wrapper = this.log.ownerDocument.createElement("div");
4415
+ wrapper.appendChild(link);
4416
+ item.appendChild(wrapper);
4417
+ }
4288
4418
  this.log.appendChild(item);
4289
4419
  this.log.scrollTop = this.log.scrollHeight;
4290
4420
  }
4291
4421
  async submit() {
4422
+ if (this.submitting) return;
4292
4423
  const text = sanitizeText(this.input.value);
4293
4424
  if (!text) {
4294
4425
  return;
4295
4426
  }
4427
+ this.submitting = true;
4428
+ this.input.disabled = true;
4429
+ this.form.querySelector("button")?.setAttribute("disabled", "true");
4296
4430
  this.input.value = "";
4297
4431
  this.append("user", text);
4298
- await this.onSubmit(text);
4432
+ try {
4433
+ await this.onSubmit(text);
4434
+ } finally {
4435
+ this.submitting = false;
4436
+ this.input.disabled = false;
4437
+ this.form.querySelector("button")?.removeAttribute("disabled");
4438
+ this.input.focus();
4439
+ }
4299
4440
  }
4300
4441
  destroy() {
4301
4442
  if (this.keydownListener) {
@@ -4358,19 +4499,15 @@ function loadOrCreateInstallationId(projectId) {
4358
4499
  }
4359
4500
 
4360
4501
  // src/communication/RuntimeAuth.ts
4361
- var RUNTIME_AUDIENCE = "asiyst-sdk-runtime";
4362
- var RUNTIME_CAPABILITIES = [
4363
- "assistant:config",
4364
- "assistant:conversation",
4365
- "assistant:telemetry",
4366
- "assistant:heartbeat"
4367
- ];
4368
4502
  var RuntimeAuth = class {
4369
4503
  constructor(options) {
4370
4504
  this.options = options;
4371
4505
  }
4372
- async getToken(capability) {
4373
- if (this.token && this.isUsable(this.token) && this.token.capabilities.has(capability)) {
4506
+ setInstallationId(installationId) {
4507
+ this.options.installationId = installationId;
4508
+ }
4509
+ async getToken() {
4510
+ if (this.token && this.isUsable(this.token) && Date.now() < this.token.refreshAfter) {
4374
4511
  return this.token.value;
4375
4512
  }
4376
4513
  if (!this.requestInFlight) {
@@ -4379,33 +4516,38 @@ var RuntimeAuth = class {
4379
4516
  });
4380
4517
  }
4381
4518
  const token = await this.requestInFlight;
4382
- if (!token.capabilities.has(capability)) {
4383
- throw new AuthenticationError("ASIYST runtime authorization does not allow this operation.");
4384
- }
4385
4519
  return token.value;
4386
4520
  }
4387
4521
  invalidate() {
4388
4522
  this.token = void 0;
4389
4523
  }
4390
4524
  isUsable(token) {
4391
- return token.expiresAt - Date.now() > 3e4;
4525
+ return token.expiresAt > Date.now();
4392
4526
  }
4393
4527
  async issueToken() {
4528
+ const installationId = this.options.installationId;
4529
+ if (!installationId) {
4530
+ throw new AuthenticationError("ASIYST installation has not been verified.");
4531
+ }
4394
4532
  const controller = new AbortController();
4395
- const timeout = setTimeout(() => controller.abort(), 1e4);
4533
+ let timedOut = false;
4534
+ const timeout = setTimeout(() => {
4535
+ timedOut = true;
4536
+ controller.abort();
4537
+ }, 1e4);
4396
4538
  let response;
4397
4539
  try {
4398
4540
  const baseUrl = this.options.apiBaseUrl.replace(/\/$/, "");
4399
4541
  const payload = JSON.stringify({
4400
4542
  projectId: this.options.projectId,
4401
4543
  publicKey: this.options.publicKey,
4402
- installationId: this.options.installationId,
4544
+ installationId,
4403
4545
  origin: this.options.origin,
4404
- environment: this.options.environment,
4405
4546
  sdkVersion: SDK_VERSION,
4406
- capabilities: [...RUNTIME_CAPABILITIES]
4547
+ environment: this.options.environment,
4548
+ capabilities: ["assistant:config", "assistant:conversation", "assistant:heartbeat"]
4407
4549
  });
4408
- response = await fetch(`${baseUrl}/sdk/runtime/token`, {
4550
+ response = await fetch(contractApiUrl(baseUrl, API_ROUTES.runtimeToken), {
4409
4551
  method: "POST",
4410
4552
  headers: {
4411
4553
  Accept: "application/json",
@@ -4414,19 +4556,8 @@ var RuntimeAuth = class {
4414
4556
  body: payload,
4415
4557
  signal: controller.signal
4416
4558
  });
4417
- if (response.status === 404) {
4418
- response = await fetch(`${baseUrl}/api/v1/sdk/runtime/token`, {
4419
- method: "POST",
4420
- headers: {
4421
- Accept: "application/json",
4422
- "Content-Type": "application/json"
4423
- },
4424
- body: payload,
4425
- signal: controller.signal
4426
- });
4427
- }
4428
4559
  } catch {
4429
- throw new NetworkError("ASIYST runtime authentication is unavailable.");
4560
+ throw new NetworkError(timedOut ? "ASIYST runtime authentication request timed out." : "ASIYST runtime authentication is unavailable.");
4430
4561
  } finally {
4431
4562
  clearTimeout(timeout);
4432
4563
  }
@@ -4443,10 +4574,13 @@ var RuntimeAuth = class {
4443
4574
  if (response.status === 429) {
4444
4575
  throw new NetworkError("ASIYST runtime authentication is rate limited.");
4445
4576
  }
4577
+ if (response.status === 503) {
4578
+ throw new NetworkError("ASIYST runtime authentication is unavailable.");
4579
+ }
4446
4580
  throw new NetworkError("ASIYST runtime authentication is unavailable.");
4447
4581
  }
4448
4582
  const data = body?.data;
4449
- 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))) {
4583
+ if (body?.success !== true || !data || typeof data.token !== "string" || data.token.length < 20 || data.tokenType !== "Bearer" || data.audience !== "asiyst-sdk-runtime" || typeof data.expiresAt !== "string" || data.expiresIn !== 300 || !Array.isArray(data.capabilities) || !data.capabilities.includes("assistant:config") || !data.capabilities.includes("assistant:conversation") || !data.capabilities.includes("assistant:heartbeat")) {
4450
4584
  throw new AuthenticationError("ASIYST returned an invalid runtime authorization response.");
4451
4585
  }
4452
4586
  const expiresAt = Date.parse(data.expiresAt);
@@ -4456,7 +4590,7 @@ var RuntimeAuth = class {
4456
4590
  const token = {
4457
4591
  value: data.token,
4458
4592
  expiresAt,
4459
- capabilities: new Set(data.capabilities)
4593
+ refreshAfter: expiresAt
4460
4594
  };
4461
4595
  this.token = token;
4462
4596
  return token;
@@ -4560,10 +4694,59 @@ function createSdkLifecycleEmitter(sink) {
4560
4694
  return new LifecycleEmitter(new UnsupportedLifecycleSink());
4561
4695
  }
4562
4696
 
4697
+ // src/avatar/AvatarMetrics.ts
4698
+ var AvatarMetricsTracker = class {
4699
+ constructor() {
4700
+ this.timestamps = {};
4701
+ this.assetInfo = {};
4702
+ }
4703
+ record(step, timestamp = typeof performance !== "undefined" ? performance.now() : Date.now()) {
4704
+ if (!this.timestamps[step]) {
4705
+ this.timestamps[step] = timestamp;
4706
+ }
4707
+ }
4708
+ setAssetInfo(info) {
4709
+ this.assetInfo = { ...this.assetInfo, ...info };
4710
+ }
4711
+ getMetrics() {
4712
+ const t = this.timestamps;
4713
+ const base = t.sdkInit ?? t.containerCreated ?? 0;
4714
+ const downloadStart = t.assetRequestStart ?? base;
4715
+ const downloadEnd = t.assetDownloadComplete ?? downloadStart;
4716
+ const parseEnd = t.parseAndDecodeComplete ?? downloadEnd;
4717
+ const sceneEnd = t.sceneInitComplete ?? parseEnd;
4718
+ const firstRender = t.firstRenderedFrame ?? sceneEnd;
4719
+ const firstVisible = t.firstVisibleCorrectlyFramed ?? firstRender;
4720
+ return {
4721
+ timestamps: {
4722
+ sdkInit: t.sdkInit ?? base,
4723
+ containerCreated: t.containerCreated ?? base,
4724
+ configRetrieved: t.configRetrieved ?? base,
4725
+ assetRequestStart: downloadStart,
4726
+ assetDownloadComplete: downloadEnd,
4727
+ parseAndDecodeComplete: parseEnd,
4728
+ sceneInitComplete: sceneEnd,
4729
+ firstRenderedFrame: firstRender,
4730
+ firstVisibleCorrectlyFramed: firstVisible
4731
+ },
4732
+ durations: {
4733
+ configRetrievalMs: Math.max(0, (t.configRetrieved ?? base) - base),
4734
+ downloadDurationMs: Math.max(0, downloadEnd - downloadStart),
4735
+ parseDurationMs: Math.max(0, parseEnd - downloadEnd),
4736
+ sceneInitDurationMs: Math.max(0, sceneEnd - parseEnd),
4737
+ firstRenderDurationMs: Math.max(0, firstRender - sceneEnd),
4738
+ timeToFirstVisibleMs: Math.max(0, firstVisible - base)
4739
+ },
4740
+ asset: { ...this.assetInfo }
4741
+ };
4742
+ }
4743
+ };
4744
+
4563
4745
  // src/core/Runtime.ts
4564
4746
  var AsiystRuntime = class {
4565
4747
  constructor(options, doc, win) {
4566
4748
  this.events = new EventBus();
4749
+ this.metricsTracker = new AvatarMetricsTracker();
4567
4750
  this.map = new WebsiteMap();
4568
4751
  this.observer = new DomObserver(() => this.rescan());
4569
4752
  this.lifecycle = createSdkLifecycleEmitter();
@@ -4573,6 +4756,7 @@ var AsiystRuntime = class {
4573
4756
  this.rescanDebounced = debounce(() => this.rescan(), DOM_SCAN_DEBOUNCE_MS);
4574
4757
  this.isHeartbeatInFlight = false;
4575
4758
  this.lastHeartbeatTime = 0;
4759
+ this.nextHeartbeatAfterMs = HEARTBEAT_INTERVAL_MS;
4576
4760
  this.registrationSucceeded = false;
4577
4761
  if (!doc.body) {
4578
4762
  throw new InitializationError("document.body is not available");
@@ -4592,10 +4776,11 @@ var AsiystRuntime = class {
4592
4776
  apiBaseUrl: options.apiBaseUrl ?? DEFAULT_API_BASE_URL,
4593
4777
  projectId: options.projectId,
4594
4778
  publicKey: options.publicKey,
4595
- installationId: this.installationId,
4779
+ installationId: void 0,
4596
4780
  origin: win.location.origin,
4597
4781
  environment: this.environment
4598
4782
  }) : void 0;
4783
+ this.runtimeAuth = runtimeAuth;
4599
4784
  this.cloud = new CloudClient(transport, options.projectId, options.publicKey, runtimeAuth, this.visitorSessionId, options.avatarId);
4600
4785
  this.config = new ConfigManager(options, this.cloud, this.events);
4601
4786
  this.config.onConfigUpdated = (newConfig, prevConfig) => {
@@ -4611,6 +4796,9 @@ var AsiystRuntime = class {
4611
4796
  this.renderer = new CssAvatarRenderer();
4612
4797
  this.renderer.onOpenChat = () => this.open();
4613
4798
  this.renderer.mount(this.host.chrome, this.config.get());
4799
+ this.metricsTracker.record("sdkInit");
4800
+ this.metricsTracker.record("containerCreated");
4801
+ this.renderer.setMetricsTracker(this.metricsTracker);
4614
4802
  this.highlights = new HighlightLayer(this.host.overlay, win);
4615
4803
  this.movement = new MovementEngine(win, doc, this.renderer, this.resolver, this.events, () => this.config.get());
4616
4804
  const live = createLiveRegion(this.host.shadow);
@@ -4624,21 +4812,19 @@ var AsiystRuntime = class {
4624
4812
  () => this.config.get()
4625
4813
  );
4626
4814
  const interaction = new InteractionEngine(this.avatar, this.resolver, () => this.config.get(), win);
4627
- this.tasks = new TaskEngine(interaction, this.events, this.analytics, this.cloud);
4815
+ this.tasks = new TaskEngine(interaction, this.events, this.analytics);
4628
4816
  this.workflows = new WorkflowEngine(this.cloud, this.tasks);
4629
4817
  this.panel = new ConversationPanel(
4630
4818
  this.host.chrome,
4631
4819
  (text) => this.handleUserMessage(text, doc),
4632
4820
  (open) => {
4633
- const convId = this.panel.getConversationId();
4634
- this.cloud.setConversationId(convId);
4635
4821
  this.renderer.setPanelOpen(open);
4636
4822
  if (open) {
4637
4823
  this.analytics.track("assistant_opened");
4638
- this.events.emit("asiyst:conversation:started", { conversationId: convId });
4639
4824
  } else {
4640
4825
  this.analytics.track("assistant_closed");
4641
- this.events.emit("asiyst:conversation:closed", { conversationId: convId });
4826
+ const conversationId = this.panel.getConversationId();
4827
+ if (conversationId) this.events.emit("asiyst:conversation:closed", { conversationId });
4642
4828
  }
4643
4829
  }
4644
4830
  );
@@ -4647,21 +4833,37 @@ var AsiystRuntime = class {
4647
4833
  this.observer.start(doc.documentElement);
4648
4834
  this.highlights.start();
4649
4835
  this.movement.start();
4650
- this.analytics.start();
4651
4836
  this.rescan();
4652
4837
  const figure = this.renderer.getFigure();
4653
4838
  if (figure) {
4654
4839
  this.figureClickListener = () => this.open();
4655
4840
  figure.addEventListener("click", this.figureClickListener);
4656
4841
  }
4657
- this.pagehideListener = () => {
4658
- void this.analytics.flush();
4659
- };
4660
- win.addEventListener("pagehide", this.pagehideListener);
4661
4842
  }
4662
4843
  async start() {
4663
4844
  this.events.emit("asiyst:initialized", { projectId: this.options.projectId });
4845
+ this.avatar.show();
4846
+ this.movement.goToAnchor();
4847
+ this.lifecycle.emit("sdk.verification_started", {
4848
+ projectId: this.options.projectId,
4849
+ origin: window.location.origin,
4850
+ environment: this.environment,
4851
+ installationId: this.installationId,
4852
+ sdkVersion: SDK_VERSION
4853
+ });
4854
+ try {
4855
+ await this.registerInstallation();
4856
+ } catch (error) {
4857
+ this.connectionStatus = "offline";
4858
+ this.verificationStatus = "error";
4859
+ this.events.emit("asiyst:error", {
4860
+ code: "runtime_connection_failed",
4861
+ message: error instanceof Error ? error.message : "Asiyst runtime connection failed."
4862
+ });
4863
+ return;
4864
+ }
4664
4865
  const cfg = await isolateAsync(() => this.config.refresh(), this.config.get());
4866
+ this.metricsTracker.record("configRetrieved");
4665
4867
  const domainCheck = validateWebsiteDomain(cfg, window.location.href);
4666
4868
  if (!domainCheck.allowed) {
4667
4869
  this.connectionStatus = "disconnected";
@@ -4674,28 +4876,7 @@ var AsiystRuntime = class {
4674
4876
  }
4675
4877
  this.avatar.applyConfig(cfg);
4676
4878
  this.movement.goToAnchor();
4677
- this.lifecycle.emit("sdk.verification_started", {
4678
- projectId: this.options.projectId,
4679
- origin: window.location.origin,
4680
- environment: this.environment,
4681
- installationId: this.installationId,
4682
- sdkVersion: SDK_VERSION
4683
- });
4684
- void (async () => {
4685
- try {
4686
- await this.registerInstallation();
4687
- await this.sendHeartbeat();
4688
- const doc = this.host.host.ownerDocument;
4689
- this.startHeartbeatScheduler(doc);
4690
- } catch {
4691
- }
4692
- })();
4693
4879
  this.events.emit("asiyst:ready", { projectId: this.options.projectId, configVersion: cfg.version });
4694
- void this.cloud.sendTelemetryEvent("avatar_runtime_initialized", {
4695
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4696
- avatarName: cfg.avatarName,
4697
- publishedVersion: cfg.publishedVersion
4698
- });
4699
4880
  const assetTarget = cfg.assetUrl ?? cfg.thumbnailUrl;
4700
4881
  if (assetTarget) {
4701
4882
  try {
@@ -4708,6 +4889,16 @@ var AsiystRuntime = class {
4708
4889
  this.avatar.show();
4709
4890
  this.movement.goToAnchor();
4710
4891
  }
4892
+ try {
4893
+ await this.sendHeartbeat();
4894
+ } catch (error) {
4895
+ this.connectionStatus = "offline";
4896
+ this.verificationStatus = "error";
4897
+ this.events.emit("asiyst:error", {
4898
+ code: "runtime_connection_failed",
4899
+ message: error instanceof Error ? error.message : "Asiyst runtime connection failed."
4900
+ });
4901
+ }
4711
4902
  this.startConfigRevalidationScheduler();
4712
4903
  }
4713
4904
  async loadAvatarAsset(cfg, assetTarget) {
@@ -4715,12 +4906,8 @@ var AsiystRuntime = class {
4715
4906
  avatarId: this.options.avatarId ?? cfg.avatarId,
4716
4907
  assetUrl: assetTarget
4717
4908
  });
4718
- void this.cloud.sendTelemetryEvent("avatar_asset_loading_started", {
4719
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4720
- assetUrl: assetTarget
4721
- });
4722
4909
  try {
4723
- const loaded = await this.renderer.loadAsset(cfg);
4910
+ const loaded = await this.renderer.loadAsset(cfg, this.metricsTracker);
4724
4911
  if (loaded) {
4725
4912
  this.movement.goToAnchor();
4726
4913
  const format = this.renderer.getLoadedFormat();
@@ -4731,23 +4918,13 @@ var AsiystRuntime = class {
4731
4918
  assetUrl,
4732
4919
  format
4733
4920
  });
4734
- void this.cloud.sendTelemetryEvent("avatar_asset_loaded", {
4735
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4736
- avatarName: cfg.avatarName,
4737
- assetUrl,
4738
- format,
4739
- publishedVersion: cfg.publishedVersion
4740
- });
4741
4921
  if (isRendered) {
4922
+ const metrics = this.metricsTracker.getMetrics();
4923
+ const durationMs = metrics?.durations.timeToFirstVisibleMs;
4742
4924
  this.events.emit("asiyst:avatar:rendered", {
4743
4925
  avatarId: this.options.avatarId ?? cfg.avatarId,
4744
- format
4745
- });
4746
- void this.cloud.sendTelemetryEvent("avatar_rendered", {
4747
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4748
- avatarName: cfg.avatarName,
4749
4926
  format,
4750
- publishedVersion: cfg.publishedVersion
4927
+ durationMs
4751
4928
  });
4752
4929
  }
4753
4930
  return true;
@@ -4758,11 +4935,6 @@ var AsiystRuntime = class {
4758
4935
  error: err,
4759
4936
  stage: "renderer_init"
4760
4937
  });
4761
- void this.cloud.sendTelemetryEvent("avatar_render_failed", {
4762
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4763
- error: err,
4764
- stage: "renderer_init"
4765
- });
4766
4938
  return false;
4767
4939
  }
4768
4940
  } catch (error) {
@@ -4772,11 +4944,6 @@ var AsiystRuntime = class {
4772
4944
  error: err,
4773
4945
  stage: "asset_fetch"
4774
4946
  });
4775
- void this.cloud.sendTelemetryEvent("avatar_render_failed", {
4776
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4777
- error: err,
4778
- stage: "asset_fetch"
4779
- });
4780
4947
  return false;
4781
4948
  }
4782
4949
  }
@@ -4823,6 +4990,7 @@ var AsiystRuntime = class {
4823
4990
  config: newConfig,
4824
4991
  previousVersion: prevConfig?.version
4825
4992
  });
4993
+ void this.sendHeartbeat();
4826
4994
  }
4827
4995
  async reloadConfig() {
4828
4996
  const updated = await this.config.refresh({ force: true });
@@ -4867,6 +5035,9 @@ var AsiystRuntime = class {
4867
5035
  getRenderer() {
4868
5036
  return this.renderer;
4869
5037
  }
5038
+ getAvatarPerformanceMetrics() {
5039
+ return this.metricsTracker.getMetrics();
5040
+ }
4870
5041
  avatarApi() {
4871
5042
  return this.avatar;
4872
5043
  }
@@ -4909,15 +5080,11 @@ var AsiystRuntime = class {
4909
5080
  clearInterval(this.configRevalidationTimer);
4910
5081
  this.configRevalidationTimer = void 0;
4911
5082
  }
4912
- const doc = this.host.host.ownerDocument;
4913
- if (doc && this.visibilityListener) {
4914
- doc.removeEventListener("visibilitychange", this.visibilityListener);
4915
- this.visibilityListener = void 0;
5083
+ if (this.heartbeatTimer) {
5084
+ clearTimeout(this.heartbeatTimer);
5085
+ this.heartbeatTimer = void 0;
4916
5086
  }
4917
5087
  this.isHeartbeatInFlight = false;
4918
- if (this.pagehideListener) {
4919
- win.removeEventListener("pagehide", this.pagehideListener);
4920
- }
4921
5088
  const figure = this.renderer.getFigure();
4922
5089
  if (figure && this.figureClickListener) {
4923
5090
  figure.removeEventListener("click", this.figureClickListener);
@@ -4934,26 +5101,20 @@ var AsiystRuntime = class {
4934
5101
  this.events.removeAll();
4935
5102
  await this.analytics.destroy();
4936
5103
  }
4937
- startHeartbeatScheduler(doc) {
4938
- if (this.heartbeatTimer) {
4939
- clearInterval(this.heartbeatTimer);
5104
+ async sendHeartbeat() {
5105
+ if (this.destroyed || this.isHeartbeatInFlight || !this.registrationSucceeded || !this.installationId) {
5106
+ return false;
4940
5107
  }
4941
- this.heartbeatTimer = setInterval(() => {
4942
- if (!this.destroyed) {
4943
- void this.sendHeartbeat(true);
5108
+ const state = this.renderer.getRenderState() === "error" ? "degraded" : "ready";
5109
+ if (this.lastReportedState === state) return true;
5110
+ const elapsed = Date.now() - this.lastHeartbeatTime;
5111
+ if (this.lastHeartbeatTime && elapsed < this.nextHeartbeatAfterMs) {
5112
+ if (!this.heartbeatTimer) {
5113
+ this.heartbeatTimer = setTimeout(() => {
5114
+ this.heartbeatTimer = void 0;
5115
+ void this.sendHeartbeat();
5116
+ }, this.nextHeartbeatAfterMs - elapsed);
4944
5117
  }
4945
- }, HEARTBEAT_INTERVAL_MS);
4946
- if (doc && typeof doc.addEventListener === "function") {
4947
- this.visibilityListener = () => {
4948
- if (!this.destroyed && doc.visibilityState === "visible" && Date.now() - this.lastHeartbeatTime > 3e4) {
4949
- void this.sendHeartbeat(true);
4950
- }
4951
- };
4952
- doc.addEventListener("visibilitychange", this.visibilityListener);
4953
- }
4954
- }
4955
- async sendHeartbeat(_isPeriodic = false) {
4956
- if (this.destroyed || this.isHeartbeatInFlight) {
4957
5118
  return false;
4958
5119
  }
4959
5120
  this.isHeartbeatInFlight = true;
@@ -4962,17 +5123,23 @@ var AsiystRuntime = class {
4962
5123
  const environment = this.environment;
4963
5124
  const installationId = this.installationId;
4964
5125
  try {
4965
- if (!this.registrationSucceeded && installationId) {
4966
- await this.registerInstallation();
4967
- }
4968
5126
  const heartbeat = await this.cloud.heartbeat({
4969
- origin,
4970
- environment,
4971
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
5127
+ installationId: this.installationId,
5128
+ sdkVersion: SDK_VERSION,
5129
+ state,
5130
+ avatarReady: this.renderer.getRenderState() === "ready",
5131
+ textChatReady: true,
5132
+ environment: this.environment,
5133
+ ...state === "degraded" ? { failureReason: "asset_load_failed" } : {}
4972
5134
  });
4973
5135
  this.lastHeartbeatTime = Date.now();
5136
+ if (heartbeat.ok) this.lastReportedState = state;
5137
+ this.nextHeartbeatAfterMs = Math.max(
5138
+ HEARTBEAT_INTERVAL_MS,
5139
+ heartbeat.nextHeartbeatAfterMs ?? heartbeat.retryAfterMs ?? HEARTBEAT_INTERVAL_MS
5140
+ );
4974
5141
  this.connectionStatus = heartbeat.ok ? "connected" : "disconnected";
4975
- this.verificationStatus = heartbeat.verificationStatus === "verified" ? "connected" : heartbeat.verificationStatus ?? (heartbeat.ok ? "connected" : "not_detected");
5142
+ this.verificationStatus = heartbeat.ok ? "connected" : "not_detected";
4976
5143
  if (heartbeat.ok) {
4977
5144
  if (!previousConnection) {
4978
5145
  this.events.emit("asiyst:runtime:connected", {
@@ -4989,32 +5156,21 @@ var AsiystRuntime = class {
4989
5156
  sdkVersion: SDK_VERSION
4990
5157
  });
4991
5158
  }
4992
- if (heartbeat.verificationStatus === "connected" || heartbeat.verificationStatus === "verified") {
4993
- this.lifecycle.emit("sdk.verified", {
4994
- projectId: this.options.projectId,
4995
- origin,
4996
- environment,
4997
- installationId,
4998
- sdkVersion: SDK_VERSION
4999
- });
5000
- }
5001
- if (heartbeat.versionOutdated) {
5002
- this.lifecycle.emit("sdk.version_outdated", {
5003
- projectId: this.options.projectId,
5004
- origin,
5005
- environment,
5006
- installationId,
5007
- sdkVersion: SDK_VERSION
5008
- });
5009
- }
5159
+ this.lifecycle.emit("sdk.verified", {
5160
+ projectId: this.options.projectId,
5161
+ origin,
5162
+ environment,
5163
+ installationId,
5164
+ sdkVersion: SDK_VERSION
5165
+ });
5010
5166
  return true;
5011
5167
  } else {
5012
- const reason = heartbeat.verificationStatus ?? "unverified";
5168
+ this.lastReportedState = void 0;
5013
5169
  this.lifecycle.emit("sdk.verification_failed", {
5014
5170
  projectId: this.options.projectId,
5015
5171
  origin,
5016
5172
  environment,
5017
- status: reason,
5173
+ status: "heartbeat_failed",
5018
5174
  reason: "heartbeat_failed"
5019
5175
  });
5020
5176
  if (previousConnection) {
@@ -5028,12 +5184,15 @@ var AsiystRuntime = class {
5028
5184
  environment,
5029
5185
  installationId,
5030
5186
  reason: "heartbeat_failed",
5031
- status: reason
5187
+ status: "heartbeat_failed"
5032
5188
  });
5033
5189
  }
5190
+ this.scheduleHeartbeatRetry();
5034
5191
  return false;
5035
5192
  }
5036
5193
  } catch (error) {
5194
+ this.lastHeartbeatTime = Date.now();
5195
+ this.lastReportedState = void 0;
5037
5196
  this.connectionStatus = "offline";
5038
5197
  this.verificationStatus = "error";
5039
5198
  this.lifecycle.emit("sdk.verification_failed", {
@@ -5044,6 +5203,10 @@ var AsiystRuntime = class {
5044
5203
  reason: "heartbeat_failed",
5045
5204
  category: error instanceof AuthenticationError ? "authorization" : "network"
5046
5205
  });
5206
+ this.events.emit("asiyst:error", {
5207
+ code: "runtime_heartbeat_failed",
5208
+ message: error instanceof Error ? error.message : "Asiyst heartbeat failed."
5209
+ });
5047
5210
  if (previousConnection) {
5048
5211
  this.events.emit("asiyst:runtime:disconnected", {
5049
5212
  projectId: this.options.projectId,
@@ -5063,73 +5226,72 @@ var AsiystRuntime = class {
5063
5226
  this.isHeartbeatInFlight = false;
5064
5227
  }
5065
5228
  }
5229
+ scheduleHeartbeatRetry() {
5230
+ if (this.destroyed || this.heartbeatTimer) return;
5231
+ const remaining = Math.max(0, this.nextHeartbeatAfterMs - (Date.now() - this.lastHeartbeatTime));
5232
+ this.heartbeatTimer = setTimeout(() => {
5233
+ this.heartbeatTimer = void 0;
5234
+ void this.sendHeartbeat();
5235
+ }, remaining);
5236
+ }
5066
5237
  async registerInstallation() {
5067
5238
  const origin = window.location.origin;
5068
5239
  const environment = this.environment;
5069
5240
  const installationId = this.installationId;
5070
5241
  if (!installationId) {
5071
- if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
5072
- console.debug("[asiyst] SDK installation identity is unavailable; registration skipped.");
5073
- }
5074
- return;
5242
+ throw new InitializationError("Asiyst could not establish a secure installation identity.");
5075
5243
  }
5076
- let lastError;
5077
- for (let attempt = 0; attempt < 2; attempt += 1) {
5078
- try {
5079
- await this.cloud.registerInstallation({
5080
- project_id: this.options.projectId,
5081
- public_key: this.options.publicKey,
5082
- installation_id: installationId,
5083
- origin,
5084
- environment,
5085
- sdk_version: SDK_VERSION
5086
- });
5087
- this.registrationSucceeded = true;
5088
- return;
5089
- } catch (error) {
5090
- lastError = error;
5091
- if (attempt === 1) {
5092
- if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
5093
- console.debug("[asiyst] SDK installation registration failed.", error);
5094
- }
5095
- this.lifecycle.emit("sdk.verification_failed", {
5096
- projectId: this.options.projectId,
5097
- origin,
5098
- environment,
5099
- installationId,
5100
- reason: "registration_failed",
5101
- category: error instanceof AuthenticationError ? "authorization" : "network"
5102
- });
5103
- return;
5104
- }
5105
- await new Promise((resolve) => setTimeout(resolve, 250));
5244
+ try {
5245
+ const verified = await this.cloud.registerInstallation({
5246
+ projectId: this.options.projectId,
5247
+ publicKey: this.options.publicKey,
5248
+ installationId,
5249
+ origin,
5250
+ environment,
5251
+ sdkVersion: SDK_VERSION
5252
+ });
5253
+ if (!verified.data.installationId) {
5254
+ throw new InitializationError("Asiyst returned no verified installation identifier.");
5106
5255
  }
5256
+ this.installationId = verified.data.installationId;
5257
+ this.runtimeAuth?.setInstallationId(verified.data.installationId);
5258
+ this.registrationSucceeded = true;
5259
+ } catch (error) {
5260
+ if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
5261
+ console.debug("[asiyst] SDK installation verification failed.", error);
5262
+ }
5263
+ this.lifecycle.emit("sdk.verification_failed", {
5264
+ projectId: this.options.projectId,
5265
+ origin,
5266
+ environment,
5267
+ installationId,
5268
+ reason: "registration_failed",
5269
+ category: error instanceof AuthenticationError ? "authorization" : "network"
5270
+ });
5271
+ throw error;
5107
5272
  }
5108
- this.lifecycle.emit("sdk.verification_failed", {
5109
- projectId: this.options.projectId,
5110
- origin,
5111
- environment,
5112
- installationId,
5113
- reason: "registration_failed",
5114
- category: lastError instanceof AuthenticationError ? "authorization" : "network"
5115
- });
5116
5273
  }
5117
5274
  rescan() {
5118
5275
  withIsolation(() => {
5119
5276
  const doc = this.host.host.ownerDocument;
5120
5277
  this.map.replace(inspectDocument(doc));
5121
- void this.cloud.sendWebsiteMap(this.map.snapshot(doc));
5122
5278
  });
5123
5279
  }
5124
5280
  async handleUserMessage(text, doc) {
5125
5281
  this.events.emit("asiyst:conversation:message", { role: "user", text });
5126
5282
  this.avatar.think();
5127
5283
  try {
5128
- const reply = await this.cloud.sendConversationMessage(text, doc.location.href);
5129
- this.panel.append("assistant", reply.message.text);
5284
+ const reply = await this.cloud.sendConversationMessage(
5285
+ text,
5286
+ doc.location.href,
5287
+ this.config.get().maxMessageChars
5288
+ );
5289
+ this.panel.setConversationId(reply.conversationId);
5290
+ this.cloud.setConversationId(reply.conversationId);
5291
+ this.events.emit("asiyst:conversation:started", { conversationId: reply.conversationId });
5292
+ this.panel.append("assistant", reply.message.text, reply.citations);
5130
5293
  this.avatar.speak(reply.message.text);
5131
5294
  this.events.emit("asiyst:conversation:message", { role: "assistant", text: reply.message.text });
5132
- await this.startTaskFromText(text, doc);
5133
5295
  } catch (error) {
5134
5296
  const message = error instanceof Error ? error.message : "Asiyst Cloud is unavailable";
5135
5297
  this.panel.append("assistant", message);
@@ -5153,6 +5315,9 @@ var Asiyst = {
5153
5315
  if (runtime) {
5154
5316
  throw new InitializationError("Asiyst is already initialized");
5155
5317
  }
5318
+ if (typeof document === "undefined" || typeof window === "undefined") {
5319
+ throw new InitializationError("Asiyst SDK can only be initialized in a browser environment.");
5320
+ }
5156
5321
  const credentials = validateInitOptions(options);
5157
5322
  const doc = document;
5158
5323
  const win = window;
@@ -5193,6 +5358,9 @@ var Asiyst = {
5193
5358
  isRuntimeConnected() {
5194
5359
  return requireRuntime().getConnectionStatus() === "connected";
5195
5360
  },
5361
+ getAvatarPerformanceMetrics() {
5362
+ return requireRuntime().getAvatarPerformanceMetrics();
5363
+ },
5196
5364
  avatar: {
5197
5365
  show() {
5198
5366
  withIsolation(() => requireRuntime().avatarApi().show());
@@ -5251,6 +5419,6 @@ var Asiyst = {
5251
5419
  }
5252
5420
  };
5253
5421
 
5254
- export { ActionNotAllowedError, Asiyst, AsiystError, AssetLoader, AuthenticationError, ConfigurationError, CssAvatarRenderer, FbxRenderer, InitializationError, NetworkError, SDK_VERSION, TargetNotFoundError, TaskExecutionError, TaskStatus, anchorToViewport, canNavigateTo, canTransition, computeAvatarDestination, evaluateActionPermission, fallbackConfig, isActionAllowed, isSafeSelector, normalizeProjectConfig, sanitizeText, validateInitOptions, validateWebsiteDomain };
5422
+ export { ActionNotAllowedError, Asiyst, AsiystError, AssetLoader, AuthenticationError, AvatarMetricsTracker, ConfigurationError, CssAvatarRenderer, FbxRenderer, InitializationError, NetworkError, SDK_VERSION, TargetNotFoundError, TaskExecutionError, TaskStatus, anchorToViewport, canNavigateTo, canTransition, computeAvatarDestination, evaluateActionPermission, fallbackConfig, isActionAllowed, isSafeSelector, normalizeProjectConfig, sanitizeText, validateInitOptions, validateWebsiteDomain };
5255
5423
  //# sourceMappingURL=index.js.map
5256
5424
  //# sourceMappingURL=index.js.map