@asiyst/sdk 0.1.29 → 0.1.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -97,7 +97,7 @@ var ALL_ACTION_KINDS = [
97
97
  // src/core/constants.ts
98
98
  function resolveSdkVersion() {
99
99
  {
100
- return "0.1.28";
100
+ return "0.1.29";
101
101
  }
102
102
  }
103
103
  var SDK_VERSION = resolveSdkVersion();
@@ -116,7 +116,7 @@ var AVATAR_TARGET_GAP = 16;
116
116
  var WEBSITE_MAP_TEXT_LIMIT = 80;
117
117
  var CONFIG_CACHE_TTL_MS = 1e3 * 30;
118
118
  var CONFIG_REVALIDATION_INTERVAL_MS = 3e4;
119
- var HEARTBEAT_INTERVAL_MS = 45e3;
119
+ var HEARTBEAT_INTERVAL_MS = 3e5;
120
120
 
121
121
  // src/security/selectors.ts
122
122
  var DANGEROUS_SELECTOR = /javascript:|expression\(|@import|url\s*\(|behavior:|binding:|<script/i;
@@ -378,7 +378,8 @@ function parseAnimations(value) {
378
378
  clipName: typeof item.clipName === "string" ? sanitizeText(item.clipName, 64) : void 0,
379
379
  loopMode: typeof item.loopMode === "string" ? sanitizeText(item.loopMode, 32) : void 0,
380
380
  durationMs: typeof item.durationMs === "number" ? item.durationMs : void 0,
381
- assetUrl: typeof item.assetUrl === "string" ? item.assetUrl : null
381
+ assetUrl: typeof item.assetUrl === "string" ? item.assetUrl : null,
382
+ integrity: typeof item.integrity === "string" ? item.integrity : void 0
382
383
  });
383
384
  }
384
385
  }
@@ -405,6 +406,8 @@ function normalizeProjectConfig(raw) {
405
406
  ) || void 0;
406
407
  const assetUrl = typeof raw.assetUrl === "string" && raw.assetUrl ? raw.assetUrl : typeof rawAvatarRecord?.assetUrl === "string" && rawAvatarRecord.assetUrl ? rawAvatarRecord.assetUrl : typeof rawAvatarRecord?.modelUrl === "string" && rawAvatarRecord.modelUrl ? rawAvatarRecord.modelUrl : typeof rawConfigRecord?.assetUrl === "string" && rawConfigRecord.assetUrl ? rawConfigRecord.assetUrl : typeof rawManifestRecord?.assetUrl === "string" && rawManifestRecord.assetUrl ? rawManifestRecord.assetUrl : typeof rawManifestRecord?.modelUrl === "string" && rawManifestRecord.modelUrl ? rawManifestRecord.modelUrl : void 0;
407
408
  const thumbnailUrl = typeof raw.thumbnailUrl === "string" ? raw.thumbnailUrl : typeof rawAvatarRecord?.thumbnailUrl === "string" ? rawAvatarRecord.thumbnailUrl : typeof rawConfigRecord?.thumbnailUrl === "string" ? rawConfigRecord.thumbnailUrl : typeof rawManifestRecord?.thumbnailUrl === "string" ? rawManifestRecord.thumbnailUrl : rawAvatarRecord?.thumbnailUrl === null ? null : void 0;
409
+ const rawModelFormat = raw.modelFormat ?? rawAvatarRecord?.modelFormat ?? rawConfigRecord?.modelFormat ?? rawManifestRecord?.modelFormat;
410
+ const modelFormat = rawModelFormat === "fbx" || rawModelFormat === "glb" ? rawModelFormat : void 0;
408
411
  const publishedVersion = typeof raw.publishedVersion === "string" ? raw.publishedVersion : typeof rawAvatarRecord?.version === "string" ? rawAvatarRecord.version : typeof rawManifestRecord?.version === "string" ? rawManifestRecord.version : void 0;
409
412
  const animations = parseAnimations(
410
413
  raw.animations ?? rawAvatarRecord?.animations ?? rawConfigRecord?.animations
@@ -424,6 +427,8 @@ function normalizeProjectConfig(raw) {
424
427
  avatar,
425
428
  avatarId,
426
429
  assetUrl,
430
+ modelFormat,
431
+ assetIntegrity: typeof raw.assetIntegrity === "string" ? raw.assetIntegrity : typeof rawAvatarRecord?.assetIntegrity === "string" ? rawAvatarRecord.assetIntegrity : void 0,
427
432
  thumbnailUrl,
428
433
  publishedVersion,
429
434
  animations,
@@ -442,7 +447,8 @@ function normalizeProjectConfig(raw) {
442
447
  blockedRoutes: parseStringList(raw.blockedRoutes ?? raw.blocked_routes),
443
448
  rules: parseRules(raw.rules ?? raw.avatarRules),
444
449
  dataSources: parseDataSources(raw.dataSources ?? raw.enabledDataSources),
445
- elementSelectors: parseElementSelectors(raw.elementSelectors)
450
+ elementSelectors: parseElementSelectors(raw.elementSelectors),
451
+ maxMessageChars: asNumber(raw.maxMessageChars, 4e3, 1, 4e3)
446
452
  };
447
453
  }
448
454
  function validateInitOptions(options) {
@@ -526,7 +532,7 @@ var HttpTransport = class {
526
532
  return this.options.avatarId;
527
533
  }
528
534
  async request(req) {
529
- const url = `${this.options.apiBaseUrl.replace(/\/$/, "")}${req.path}`;
535
+ const url = /^https?:\/\//i.test(req.path) ? req.path : `${this.options.apiBaseUrl.replace(/\/$/, "")}${req.path}`;
530
536
  const requestId = req.requestId || generateRequestId();
531
537
  const timeoutMs = req.timeoutMs ?? this.options.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS;
532
538
  const isSafeOrIdempotent = req.method === "GET" || Boolean(req.idempotent);
@@ -554,36 +560,30 @@ var HttpTransport = class {
554
560
  }
555
561
  try {
556
562
  let response;
557
- try {
558
- response = await fetch(url, {
559
- method: req.method,
560
- headers: {
561
- Accept: "application/json",
562
- "Content-Type": "application/json",
563
- "X-Asiyst-Project-Id": this.options.projectId,
564
- "X-Asiyst-Public-Key": this.options.publicKey,
565
- ...this.options.avatarId ? { "X-Asiyst-Avatar-Id": this.options.avatarId } : {},
566
- "X-Asiyst-SDK-Version": SDK_VERSION,
567
- "X-Asiyst-Request-Id": requestId,
568
- ...req.sessionId ? { "X-Asiyst-Session-Id": req.sessionId } : {},
569
- ...req.conversationId ? { "X-Asiyst-Conversation-Id": req.conversationId } : {},
570
- ...req.authorizationToken ? { Authorization: `Bearer ${req.authorizationToken}` } : {}
571
- },
572
- body: req.body === void 0 ? void 0 : JSON.stringify(req.body),
573
- signal: controller.signal
574
- });
575
- } finally {
576
- clearTimeout(timeoutId);
577
- if (req.signal) {
578
- req.signal.removeEventListener("abort", onExternalAbort);
579
- }
580
- }
563
+ response = await fetch(url, {
564
+ method: req.method,
565
+ headers: req.headers ?? {
566
+ Accept: "application/json",
567
+ "Content-Type": "application/json",
568
+ "X-Asiyst-Project-Id": this.options.projectId,
569
+ "X-Asiyst-Public-Key": this.options.publicKey,
570
+ ...this.options.avatarId ? { "X-Asiyst-Avatar-Id": this.options.avatarId } : {},
571
+ "X-Asiyst-SDK-Version": SDK_VERSION,
572
+ "X-Asiyst-Request-Id": requestId,
573
+ ...req.sessionId ? { "X-Asiyst-Session-Id": req.sessionId } : {},
574
+ ...req.conversationId ? { "X-Asiyst-Conversation-Id": req.conversationId } : {},
575
+ ...req.authorizationToken ? { Authorization: `Bearer ${req.authorizationToken}` } : {}
576
+ },
577
+ body: req.body === void 0 ? void 0 : JSON.stringify(req.body),
578
+ signal: controller.signal
579
+ });
581
580
  if (isSafeOrIdempotent && attempt < maxRetries && [502, 503, 504].includes(response.status)) {
582
581
  continue;
583
582
  }
584
583
  if (response.status === 429 && isSafeOrIdempotent && attempt < maxRetries) {
585
584
  const retryAfterHeader = response.headers.get("retry-after");
586
585
  const retryAfterMs = retryAfterHeader ? Math.min(Number(retryAfterHeader) * 1e3 || 200, 1e3) : 100;
586
+ clearTimeout(timeoutId);
587
587
  await new Promise((resolve) => setTimeout(resolve, retryAfterMs));
588
588
  continue;
589
589
  }
@@ -593,33 +593,87 @@ var HttpTransport = class {
593
593
  try {
594
594
  data = await response.json();
595
595
  } catch {
596
+ if (timedOut) {
597
+ throw new NetworkError("Asiyst Cloud request timed out");
598
+ }
599
+ if (req.signal?.aborted) {
600
+ throw new NetworkError("Asiyst Cloud request was aborted");
601
+ }
596
602
  data = null;
597
603
  }
598
604
  }
599
605
  if (!response.ok) {
600
- return { ok: false, status: response.status, data };
606
+ return { ok: false, status: response.status, data, headers: response.headers };
601
607
  }
602
- return { ok: true, status: response.status, data };
608
+ return { ok: true, status: response.status, data, headers: response.headers };
603
609
  } catch (err) {
604
- clearTimeout(timeoutId);
605
- if (req.signal) {
606
- req.signal.removeEventListener("abort", onExternalAbort);
607
- }
608
610
  if (timedOut) {
609
611
  throw new NetworkError("Asiyst Cloud request timed out");
610
612
  }
613
+ if (req.signal?.aborted) {
614
+ throw new NetworkError("Asiyst Cloud request was aborted");
615
+ }
611
616
  lastError = err;
612
617
  if (isSafeOrIdempotent && attempt < maxRetries) {
613
618
  continue;
614
619
  }
615
620
  throw new NetworkError("Asiyst Cloud is unreachable");
621
+ } finally {
622
+ clearTimeout(timeoutId);
623
+ if (req.signal) {
624
+ req.signal.removeEventListener("abort", onExternalAbort);
625
+ }
616
626
  }
617
627
  }
618
628
  throw lastError instanceof Error ? lastError : new NetworkError("Asiyst Cloud is unreachable");
619
629
  }
620
630
  };
621
631
 
632
+ // ../api-contract.ts
633
+ var API_V1_BASE_PATH = "/api/v1";
634
+ var API_ROUTES = {
635
+ runtimeAvatar: "/runtime/avatar",
636
+ runtimeToken: "/sdk/runtime/token",
637
+ installationRegister: "/sdk/installations/register",
638
+ runtimeHeartbeat: "/sdk/heartbeat",
639
+ chat: "/conversations/messages",
640
+ projectApiKeyVerify: (projectId) => `/projects/${encodeURIComponent(projectId)}/api-key/verify`,
641
+ sdkInstallationVerify: "/sdk/installations/verify"
642
+ };
643
+ var API_LIMITS = {
644
+ configStaleIfErrorMs: 0,
645
+ maxMessageChars: 12e3,
646
+ pageUrlMaxChars: 2048};
647
+ function apiV1Path(route) {
648
+ return `${API_V1_BASE_PATH}${route.startsWith("/") ? route : `/${route}`}`;
649
+ }
650
+ function contractApiBaseUrl(configuredApiBaseUrl) {
651
+ const parsed = new URL(configuredApiBaseUrl);
652
+ if (parsed.pathname.replace(/\/+$/, "").endsWith("/functions/v1/api")) {
653
+ return "https://asiyst.com";
654
+ }
655
+ return parsed.origin;
656
+ }
657
+ function contractApiUrl(configuredApiBaseUrl, route) {
658
+ return `${contractApiBaseUrl(configuredApiBaseUrl).replace(/\/+$/, "")}${apiV1Path(route)}`;
659
+ }
660
+
622
661
  // src/communication/CloudClient.ts
662
+ function newRequestId() {
663
+ const cryptoApi = globalThis.crypto;
664
+ if (typeof cryptoApi?.randomUUID === "function") return cryptoApi.randomUUID();
665
+ if (typeof cryptoApi?.getRandomValues === "function") {
666
+ const bytes = cryptoApi.getRandomValues(new Uint8Array(16));
667
+ bytes[6] = (bytes[6] ?? 0) & 15 | 64;
668
+ bytes[8] = (bytes[8] ?? 0) & 63 | 128;
669
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
670
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
671
+ }
672
+ throw new ConfigurationError("Secure request identifiers are unavailable in this browser.");
673
+ }
674
+ function isUuid(value) {
675
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
676
+ }
623
677
  var CloudClient = class {
624
678
  constructor(transport, projectId, publicKey = "", runtimeAuth, sessionId, avatarId) {
625
679
  this.transport = transport;
@@ -627,6 +681,7 @@ var CloudClient = class {
627
681
  this.publicKey = publicKey;
628
682
  this.runtimeAuth = runtimeAuth;
629
683
  this.avatarId = avatarId;
684
+ this.configMetadata = {};
630
685
  this.inFlightConversations = /* @__PURE__ */ new Map();
631
686
  this.sessionId = sessionId;
632
687
  if (!this.avatarId && typeof transport.getAvatarId === "function") {
@@ -657,243 +712,152 @@ var CloudClient = class {
657
712
  }
658
713
  return DEFAULT_API_BASE_URL;
659
714
  }
660
- async getAuthToken(capability) {
715
+ async getAuthToken() {
661
716
  if (!this.runtimeAuth) return void 0;
662
717
  if (this.tokenRefreshPromise) return this.tokenRefreshPromise;
663
- if (!this.inFlightToken) {
664
- this.inFlightToken = this.runtimeAuth.getToken(capability).then((token) => {
665
- this.activeToken = token;
666
- return token;
667
- }).finally(() => {
668
- this.inFlightToken = void 0;
669
- });
670
- }
671
- return this.inFlightToken;
718
+ this.tokenRefreshPromise = this.runtimeAuth.getToken().then((token) => {
719
+ this.activeToken = token;
720
+ return token;
721
+ }).finally(() => {
722
+ this.tokenRefreshPromise = void 0;
723
+ });
724
+ return this.tokenRefreshPromise;
672
725
  }
673
- async fetchConfig() {
674
- const avatarParam = this.avatarId ? `?avatarId=${encodeURIComponent(this.avatarId)}` : "";
675
- const avatarAndKeyParams = `?projectId=${encodeURIComponent(this.projectId)}&publicKey=${encodeURIComponent(this.publicKey)}${this.avatarId ? `&avatarId=${encodeURIComponent(this.avatarId)}` : ""}`;
676
- const baseUrl = this.getApiBaseUrl();
677
- const resolveAssetUrls = (raw) => {
678
- let canonicalBase = "https://asiyst.com";
679
- try {
680
- if (baseUrl) {
681
- const u = new URL(baseUrl);
682
- canonicalBase = u.origin;
683
- }
684
- } catch {
685
- canonicalBase = "https://asiyst.com";
726
+ getConfigMetadata() {
727
+ return this.configMetadata;
728
+ }
729
+ async fetchConfig(etag, cachedConfig) {
730
+ const response = await this.transport.request({
731
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.runtimeAvatar),
732
+ method: "GET",
733
+ idempotent: true,
734
+ retries: 2,
735
+ headers: {
736
+ Accept: "application/json",
737
+ "X-Asiyst-Public-Key": this.publicKey,
738
+ "X-Asiyst-Project-Id": this.projectId,
739
+ ...this.avatarId ? { "X-Asiyst-Avatar-Id": this.avatarId } : {},
740
+ ...etag ? { "If-None-Match": etag } : {}
686
741
  }
687
- const toAbsolute = (url) => {
688
- if (typeof url === "string" && url.startsWith("/")) {
689
- return new URL(url, canonicalBase).href;
690
- }
691
- return url;
742
+ });
743
+ if (response.status === 304 && cachedConfig) {
744
+ this.configMetadata = {
745
+ etag: response.headers?.get("etag") ?? etag,
746
+ maxAgeMs: 0,
747
+ staleIfErrorMs: 0
692
748
  };
693
- if (raw.avatar && typeof raw.avatar === "object" && !Array.isArray(raw.avatar)) {
694
- const av = { ...raw.avatar };
695
- av.assetUrl = toAbsolute(av.assetUrl);
696
- av.thumbnailUrl = toAbsolute(av.thumbnailUrl);
697
- av.modelUrl = toAbsolute(av.modelUrl);
698
- av.manifestUrl = toAbsolute(av.manifestUrl);
699
- if (Array.isArray(av.animations)) {
700
- av.animations = av.animations.map((item) => {
701
- if (item && typeof item === "object") {
702
- const animObj = item;
703
- return { ...animObj, assetUrl: toAbsolute(animObj.assetUrl) };
704
- }
705
- return item;
706
- });
707
- }
708
- raw.avatar = av;
709
- }
710
- if (raw.config && typeof raw.config === "object" && !Array.isArray(raw.config)) {
711
- const cfg = { ...raw.config };
712
- cfg.assetUrl = toAbsolute(cfg.assetUrl);
713
- cfg.thumbnailUrl = toAbsolute(cfg.thumbnailUrl);
714
- cfg.manifestUrl = toAbsolute(cfg.manifestUrl);
715
- raw.config = cfg;
716
- }
717
- if (raw.manifest && typeof raw.manifest === "object" && !Array.isArray(raw.manifest)) {
718
- const mf = { ...raw.manifest };
719
- mf.assetUrl = toAbsolute(mf.assetUrl);
720
- mf.thumbnailUrl = toAbsolute(mf.thumbnailUrl);
721
- mf.modelUrl = toAbsolute(mf.modelUrl);
722
- raw.manifest = mf;
723
- }
724
- raw.assetUrl = toAbsolute(raw.assetUrl);
725
- raw.thumbnailUrl = toAbsolute(raw.thumbnailUrl);
726
- raw.manifestUrl = toAbsolute(raw.manifestUrl);
727
- if (raw.branding && typeof raw.branding === "object" && !Array.isArray(raw.branding)) {
728
- const br = { ...raw.branding };
729
- br.siteLogoUrl = toAbsolute(br.siteLogoUrl);
730
- raw.branding = br;
731
- }
732
- return raw;
733
- };
734
- let lastError;
735
- try {
736
- const response = await this.runtimeRequest({
737
- path: `/projects/${encodeURIComponent(this.projectId)}/avatar${avatarParam}`,
738
- method: "GET",
739
- idempotent: true
740
- });
741
- if (response.ok && response.data) {
742
- const fullData = response.data && typeof response.data === "object" && !Array.isArray(response.data) ? {
743
- ...response.data,
744
- ...response.data.config && typeof response.data.config === "object" ? response.data.config : {}
745
- } : {};
746
- return normalizeProjectConfig(resolveAssetUrls(fullData));
747
- }
748
- if (response.status === 404) {
749
- lastError = new ConfigurationError(`Project ${this.projectId} or avatar configuration not found`);
750
- }
751
- } catch (err) {
752
- if (err instanceof Error) lastError = err;
749
+ return cachedConfig;
753
750
  }
754
- try {
755
- const runtimeResponse = await this.runtimeRequest({
756
- path: `/api/v1/runtime/avatar${avatarAndKeyParams}`,
757
- method: "GET",
758
- idempotent: true
759
- });
760
- if (runtimeResponse.ok && runtimeResponse.data) {
761
- return normalizeProjectConfig(resolveAssetUrls(runtimeResponse.data));
762
- }
763
- if (runtimeResponse.status === 404) {
764
- lastError = new ConfigurationError(`Avatar ${this.avatarId ?? "active"} not found for project ${this.projectId}`);
751
+ if (!response.ok || !response.data) {
752
+ const body = response.data;
753
+ const code = body?.error?.code ?? `HTTP_${response.status}`;
754
+ if (response.status === 401 || response.status === 403) {
755
+ throw new AuthenticationError(body?.error?.message ?? `Asiyst runtime avatar configuration was rejected (${code}).`);
765
756
  }
766
- } catch (err) {
767
- if (err instanceof Error) lastError = err;
768
- }
769
- try {
770
- const webBase = baseUrl.includes("localhost") || baseUrl.includes("127.0.0.1") ? baseUrl.replace(/\/functions\/v1.*$/, "").replace(/\/api\/v1.*$/, "") : "https://asiyst.com";
771
- const fullUrl = `${webBase.replace(/\/$/, "")}/api/v1/runtime/avatar${avatarAndKeyParams}`;
772
- const res = await fetch(fullUrl, {
773
- headers: {
774
- Accept: "application/json",
775
- "x-asiyst-public-key": this.publicKey
776
- }
777
- });
778
- if (res.ok) {
779
- const body = await res.json();
780
- if (body && typeof body === "object") {
781
- return normalizeProjectConfig(resolveAssetUrls(body));
782
- }
783
- } else {
784
- const errorBody = await res.json().catch(() => ({}));
785
- const errObj = errorBody?.error ?? errorBody;
786
- const code = String(errObj?.code ?? "");
787
- const message = String(errObj?.message ?? `HTTP ${res.status}`);
788
- if (res.status === 404) {
789
- throw new ConfigurationError(code === "AVATAR_NOT_FOUND" ? `Requested avatar not found for project ${this.projectId}` : `Project ${this.projectId} not found`);
790
- } else if (res.status === 401 || res.status === 403) {
791
- throw new AuthenticationError("Asiyst credentials unauthorized for this avatar configuration");
792
- } else if (res.status >= 500) {
793
- throw new NetworkError(`Asiyst Cloud avatar service error (${res.status}): ${message}`);
794
- }
795
- }
796
- } catch (err) {
797
- if (err instanceof ConfigurationError || err instanceof AuthenticationError || err instanceof NetworkError) {
798
- throw err;
799
- }
800
- if (err instanceof Error) lastError = err;
801
- }
802
- if (lastError) {
803
- throw lastError;
804
- }
805
- throw new ConfigurationError(`Failed to resolve avatar configuration for project ${this.projectId}`);
757
+ throw new NetworkError(body?.error?.message ?? `Asiyst runtime avatar configuration is unavailable (${code}).`);
758
+ }
759
+ const data = response.data;
760
+ if (data.success !== true || data.projectId !== this.projectId || typeof data.avatarId !== "string" || !data.config || typeof data.config !== "object" || Array.isArray(data.config)) {
761
+ throw new ConfigurationError("Asiyst returned an invalid runtime configuration response.");
762
+ }
763
+ const rawConfig = data.config;
764
+ const rawAvatar = data.avatar && typeof data.avatar === "object" ? data.avatar : {};
765
+ const manifest = data.manifest && typeof data.manifest === "object" ? data.manifest : {};
766
+ const modelFormat = [data.format, data.modelFormat, rawConfig.modelFormat, rawAvatar.modelFormat].find((format) => typeof format === "string");
767
+ if (modelFormat && modelFormat !== "fbx" && modelFormat !== "glb") {
768
+ throw new ConfigurationError(`Asiyst returned an unsupported avatar format: ${modelFormat}.`);
769
+ }
770
+ const assetUrl = typeof rawConfig.assetUrl === "string" ? rawConfig.assetUrl : typeof rawAvatar.assetUrl === "string" ? rawAvatar.assetUrl : typeof rawAvatar.modelUrl === "string" ? rawAvatar.modelUrl : typeof manifest.assetUrl === "string" ? manifest.assetUrl : void 0;
771
+ const animations = Array.isArray(rawConfig.animations) ? rawConfig.animations : Array.isArray(data.animations) ? data.animations : Array.isArray(rawAvatar.animations) ? rawAvatar.animations : [];
772
+ const revision = typeof data.configRevision === "string" ? data.configRevision : typeof data.publishedVersionId === "string" ? data.publishedVersionId : "0";
773
+ const version = Number.parseInt(revision, 10);
774
+ const config = normalizeProjectConfig({
775
+ ...rawConfig,
776
+ avatarId: data.avatarId,
777
+ avatarName: typeof rawAvatar.name === "string" ? rawAvatar.name : rawConfig.avatarName,
778
+ assetUrl,
779
+ modelFormat,
780
+ publishedVersion: typeof data.publishedVersionId === "string" ? data.publishedVersionId : revision,
781
+ version: Number.isFinite(version) ? version : 0,
782
+ animations,
783
+ theme: rawConfig.theme ?? rawAvatar.theme,
784
+ personality: rawConfig.personality,
785
+ behavior: rawConfig.behavior ?? rawAvatar.behavior,
786
+ maxMessageChars: API_LIMITS.maxMessageChars
787
+ });
788
+ this.configMetadata = {
789
+ etag: response.headers?.get("etag") ?? void 0,
790
+ maxAgeMs: 0,
791
+ staleIfErrorMs: 0
792
+ };
793
+ return config;
806
794
  }
807
795
  async heartbeat(metadata) {
808
- let response = await this.runtimeRequest({
809
- path: "/sdk/heartbeat",
796
+ const response = await this.runtimeRequest({
797
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.runtimeHeartbeat),
810
798
  method: "POST",
811
- idempotent: true,
799
+ canonical: true,
812
800
  body: {
813
- project_id: this.projectId,
814
- public_key: this.publicKey,
815
- sdk_version: SDK_VERSION,
816
- origin: metadata.origin,
817
- environment: metadata.environment,
818
- timestamp: metadata.timestamp
801
+ projectId: this.projectId,
802
+ publicKey: this.publicKey,
803
+ sdkVersion: metadata.sdkVersion,
804
+ environment: metadata.environment
819
805
  }
820
806
  }, "assistant:heartbeat");
821
- if (response.status === 404) {
822
- response = await this.runtimeRequest({
823
- path: "/api/v1/sdk/heartbeat",
824
- method: "POST",
825
- idempotent: true,
826
- body: {
827
- project_id: this.projectId,
828
- public_key: this.publicKey,
829
- sdk_version: SDK_VERSION,
830
- origin: metadata.origin,
831
- environment: metadata.environment,
832
- timestamp: metadata.timestamp
833
- }
834
- }, "assistant:heartbeat");
835
- }
836
- const body = response.data && typeof response.data === "object" && !Array.isArray(response.data) ? response.data : void 0;
837
- const rawStatus = body?.status ?? body?.connectionStatus ?? body?.verificationStatus ?? (body?.verified === true ? "verified" : void 0);
838
- const verificationStatus = rawStatus === "connected" || rawStatus === "verified" || rawStatus === "inactive" || rawStatus === "not_detected" || rawStatus === "error" ? rawStatus : void 0;
839
- const versionOutdated = body?.versionOutdated === true || body?.sdkVersionOutdated === true || rawStatus === "outdated";
807
+ const body = response.data;
808
+ const validResponse = body?.success === true && body.data?.connected === true && body.data.projectId === this.projectId && typeof body.data.versionOutdated === "boolean";
840
809
  return {
841
- ok: response.ok && (verificationStatus === void 0 || verificationStatus === "connected" || verificationStatus === "verified"),
842
- status: response.status,
843
- verificationStatus,
844
- versionOutdated
810
+ ok: response.ok && response.status === 202 && validResponse,
811
+ status: response.status
845
812
  };
846
813
  }
847
814
  async registerInstallation(registration) {
848
- let response = await this.transport.request({
849
- path: "/sdk/installations/register",
815
+ const response = await this.transport.request({
816
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.installationRegister),
850
817
  method: "POST",
851
- body: registration,
852
- idempotent: true,
853
- sessionId: this.sessionId
818
+ headers: {
819
+ Accept: "application/json",
820
+ "Content-Type": "application/json",
821
+ "X-Asiyst-SDK-Version": registration.sdkVersion
822
+ },
823
+ body: {
824
+ projectId: registration.projectId,
825
+ publicKey: registration.publicKey,
826
+ installationId: registration.installationId,
827
+ origin: registration.origin,
828
+ environment: registration.environment,
829
+ sdkVersion: registration.sdkVersion
830
+ }
854
831
  });
855
- if (response.status === 404) {
856
- response = await this.transport.request({
857
- path: "/api/v1/sdk/installations/register",
858
- method: "POST",
859
- body: registration,
860
- idempotent: true,
861
- sessionId: this.sessionId
862
- });
863
- }
864
- if (!response.ok) {
865
- throw new NetworkError(`SDK installation registration failed (${response.status}).`);
832
+ const body = response.data;
833
+ if (!response.ok || body?.success !== true || body.data?.registered !== true || typeof body.data.installationId !== "string" || body.data.projectId !== registration.projectId || body.data.status === "revoked") {
834
+ const error = response.data && typeof response.data === "object" ? response.data.error : void 0;
835
+ if (response.status === 403 || body?.data?.status === "revoked") {
836
+ throw new AuthenticationError(error?.message ?? `SDK installation is not authorized (${error?.code ?? response.status}).`);
837
+ }
838
+ throw new NetworkError(error?.message ?? `SDK installation registration failed (${response.status}).`);
866
839
  }
867
- return response.data ?? {};
840
+ return body;
868
841
  }
869
842
  async requestTask(userText, pageUrl) {
870
- const response = await this.runtimeRequest({
871
- path: "/tasks",
872
- method: "POST",
873
- body: {
874
- projectId: this.projectId,
875
- text: userText,
876
- pageUrl
877
- }
878
- }, "assistant:conversation");
879
- if (!response.ok || !response.data?.task?.id || !Array.isArray(response.data.task.steps)) {
880
- throw new NetworkError("Task planning is unavailable");
881
- }
882
- return response.data.task;
843
+ throw new ConfigurationError("Cloud task planning is not defined by the approved SDK API contract.");
883
844
  }
884
845
  async fetchWorkflow(workflowId) {
885
- const response = await this.runtimeRequest({
886
- path: `/workflows/${encodeURIComponent(workflowId)}`,
887
- method: "GET",
888
- idempotent: true
889
- }, "assistant:conversation");
890
- if (!response.ok || !response.data?.workflow?.id || !Array.isArray(response.data.workflow.steps)) {
891
- throw new NetworkError("Workflow is unavailable");
892
- }
893
- return response.data.workflow;
846
+ throw new ConfigurationError("Cloud workflows are not defined by the approved SDK API contract.");
894
847
  }
895
- async sendConversationMessage(text, pageUrl) {
848
+ async sendConversationMessage(text, pageUrl, maxMessageChars = API_LIMITS.maxMessageChars) {
896
849
  const trimmed = text.trim();
850
+ if (!trimmed) throw new ConfigurationError("Message cannot be empty.");
851
+ if (trimmed.length > maxMessageChars) {
852
+ throw new ConfigurationError(`Message exceeds the ${maxMessageChars}-character limit.`);
853
+ }
854
+ if (pageUrl.length > API_LIMITS.pageUrlMaxChars) {
855
+ throw new ConfigurationError("Page URL exceeds the supported length.");
856
+ }
857
+ const sessionId = this.sessionId ?? newRequestId();
858
+ if (sessionId.length < 16 || sessionId.length > 128 || !/^[A-Za-z0-9_-]+$/.test(sessionId)) {
859
+ throw new ConfigurationError("Visitor session ID must be an opaque 16-128 character identifier.");
860
+ }
897
861
  const dedupeKey2 = `${this.conversationId ?? ""}:${trimmed}:${pageUrl}`;
898
862
  const existing = this.inFlightConversations.get(dedupeKey2);
899
863
  if (existing) {
@@ -901,19 +865,72 @@ var CloudClient = class {
901
865
  }
902
866
  const conversationPromise = (async () => {
903
867
  try {
868
+ const requestConversationId = this.conversationId && isUuid(this.conversationId) ? this.conversationId : void 0;
904
869
  const response = await this.runtimeRequest({
905
- path: "/conversations/messages",
870
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.chat),
906
871
  method: "POST",
907
- body: { projectId: this.projectId, text: trimmed, pageUrl },
908
- conversationId: this.conversationId
872
+ body: {
873
+ projectId: this.projectId,
874
+ text: trimmed,
875
+ ...requestConversationId ? { conversationId: requestConversationId } : {},
876
+ sessionId,
877
+ pageUrl
878
+ }
909
879
  }, "assistant:conversation");
910
- if (!response.ok || !response.data?.message?.text) {
911
- if (response.status === 401 || response.status === 403) {
912
- throw new NetworkError("AI request authorization failed. The project credentials may be inactive, revoked, or inaccessible.");
880
+ if (response.ok && response.data?.success === true) {
881
+ const body = response.data;
882
+ const message = body.message && typeof body.message === "object" ? body.message : void 0;
883
+ const conversationId = body.conversationId;
884
+ const messageText = message?.text ?? body.response ?? body.answer;
885
+ if (body.success !== true || typeof conversationId !== "string" || typeof messageText !== "string" || !messageText.trim() || message && message.role !== "assistant") {
886
+ throw new NetworkError("Asiyst returned an unsupported conversation response.");
913
887
  }
914
- throw new NetworkError("Conversation service is unavailable");
888
+ this.conversationId = conversationId;
889
+ const rawCitations = Array.isArray(body.sources) ? body.sources : [];
890
+ return {
891
+ requestId: typeof body.requestId === "string" ? body.requestId : void 0,
892
+ conversationId,
893
+ message: {
894
+ ...typeof message?.id === "string" ? { id: message.id } : {},
895
+ role: "assistant",
896
+ text: messageText
897
+ },
898
+ citations: rawCitations.flatMap((citation) => {
899
+ if (!citation || typeof citation !== "object") return [];
900
+ const item = citation;
901
+ const sourceId = item.source_id ?? item.id;
902
+ if (typeof sourceId !== "string" || typeof item.title !== "string") return [];
903
+ return [{
904
+ sourceId,
905
+ title: item.title,
906
+ ...typeof item.url === "string" ? { url: item.url } : {}
907
+ }];
908
+ }),
909
+ finishReason: void 0,
910
+ createdAt: void 0
911
+ };
912
+ }
913
+ const errorRecord = response.data && typeof response.data === "object" ? response.data.error : void 0;
914
+ const errorBody = errorRecord && typeof errorRecord === "object" ? errorRecord : void 0;
915
+ const code = typeof errorBody?.code === "string" ? errorBody.code : typeof errorRecord === "string" ? errorRecord : `HTTP_${response.status}`;
916
+ if (response.status === 401 || response.status === 403) {
917
+ throw new AuthenticationError("Asiyst runtime authorization was rejected.");
918
+ }
919
+ if (response.status === 429) {
920
+ throw new NetworkError("The assistant is rate limited. Wait before sending another message.");
915
921
  }
916
- return response.data;
922
+ if (response.status === 409) {
923
+ throw new NetworkError(`The conversation request conflicted (${code}); it was not retried.`);
924
+ }
925
+ if (response.status === 504 || code === "AI_PROVIDER_TIMEOUT") {
926
+ throw new NetworkError("The assistant timed out. The request was not retried to avoid duplicate work.");
927
+ }
928
+ if (code === "assistant_unavailable") {
929
+ throw new NetworkError("The assistant is temporarily unavailable.");
930
+ }
931
+ throw new NetworkError(
932
+ typeof errorBody?.message === "string" ? errorBody.message : typeof response.data?.message === "string" ? response.data.message : "Conversation service is unavailable."
933
+ );
917
934
  } finally {
918
935
  this.inFlightConversations.delete(dedupeKey2);
919
936
  }
@@ -922,63 +939,16 @@ var CloudClient = class {
922
939
  return conversationPromise;
923
940
  }
924
941
  async sendWebsiteMap(snapshot) {
925
- await this.safePost("/website-maps", snapshot);
942
+ throw new ConfigurationError("Website-map upload is not defined by the approved SDK API contract.");
926
943
  }
927
944
  async sendAnalytics(events) {
928
- await this.safePost("/analytics", { events });
945
+ throw new ConfigurationError("Analytics upload is not defined by the approved SDK API contract.");
929
946
  }
930
947
  async sendTelemetryEvent(eventType, metadata = {}) {
931
- try {
932
- const origin = typeof window !== "undefined" ? window.location.origin : void 0;
933
- const installationId = this.runtimeAuth ? this.runtimeAuth.options?.installationId : void 0;
934
- const sanitizedMeta = {
935
- sdkVersion: SDK_VERSION
936
- };
937
- for (const [key, val] of Object.entries(metadata)) {
938
- if (/(token|secret|cookie|session|api.?key|password|bearer|authorization)/i.test(key)) {
939
- continue;
940
- }
941
- if (typeof val === "string") {
942
- sanitizedMeta[key] = sanitizeText(val, 512);
943
- } else if (typeof val === "number" || typeof val === "boolean") {
944
- sanitizedMeta[key] = val;
945
- } else if (val && typeof val === "object" && !Array.isArray(val)) {
946
- sanitizedMeta[key] = val;
947
- }
948
- }
949
- const payload = {
950
- projectId: this.projectId,
951
- publicKey: this.publicKey,
952
- eventType,
953
- installationId,
954
- origin,
955
- metadata: sanitizedMeta
956
- };
957
- const baseUrl = this.getApiBaseUrl();
958
- const targetUrl = baseUrl.includes("localhost") || baseUrl.includes("127.0.0.1") ? `${baseUrl.replace(/\/functions\/v1.*$/, "").replace(/\/api\/v1.*$/, "")}/api/v1/events` : "https://asiyst.com/api/v1/events";
959
- await fetch(targetUrl, {
960
- method: "POST",
961
- headers: {
962
- "Content-Type": "application/json",
963
- Accept: "application/json",
964
- "x-asiyst-public-key": this.publicKey
965
- },
966
- body: JSON.stringify(payload)
967
- });
968
- } catch {
969
- }
948
+ throw new ConfigurationError("Telemetry upload is not defined by the approved SDK API contract.");
970
949
  }
971
950
  async sendTaskUpdate(taskId, status, stepId) {
972
- await this.safePost(`/tasks/${encodeURIComponent(taskId)}/events`, {
973
- status,
974
- stepId
975
- });
976
- }
977
- async safePost(path, body) {
978
- try {
979
- await this.runtimeRequest({ path, method: "POST", body, idempotent: true }, "assistant:telemetry");
980
- } catch {
981
- }
951
+ throw new ConfigurationError("Cloud task updates are not defined by the approved SDK API contract.");
982
952
  }
983
953
  async runtimeRequest(request, capability = "assistant:config") {
984
954
  const fullRequest = {
@@ -987,14 +957,32 @@ var CloudClient = class {
987
957
  conversationId: request.conversationId ?? this.conversationId
988
958
  };
989
959
  if (!this.runtimeAuth) {
960
+ if (capability === "assistant:conversation" || capability === "assistant:heartbeat") {
961
+ throw new AuthenticationError("AI request authorization failed because no runtime token is available.");
962
+ }
990
963
  return this.transport.request(fullRequest);
991
964
  }
992
- let token = await this.getAuthToken(capability);
993
- let response = await this.transport.request({ ...fullRequest, authorizationToken: token });
965
+ let token = await this.getAuthToken();
966
+ const withToken = (value) => {
967
+ const headers = new Headers({
968
+ Accept: "application/json",
969
+ "Content-Type": "application/json"
970
+ });
971
+ if (fullRequest.headers) {
972
+ new Headers(fullRequest.headers).forEach((headerValue, key) => headers.set(key, headerValue));
973
+ }
974
+ if (value) headers.set("Authorization", `Bearer ${value}`);
975
+ return this.transport.request({
976
+ ...fullRequest,
977
+ headers,
978
+ canonical: true
979
+ });
980
+ };
981
+ let response = await withToken(token);
994
982
  if (response.status === 401) {
995
983
  if (!this.tokenRefreshPromise) {
996
984
  this.runtimeAuth.invalidate();
997
- this.tokenRefreshPromise = this.runtimeAuth.getToken(capability).then((newToken) => {
985
+ this.tokenRefreshPromise = this.runtimeAuth.getToken().then((newToken) => {
998
986
  this.activeToken = newToken;
999
987
  return newToken;
1000
988
  }).finally(() => {
@@ -1004,7 +992,7 @@ var CloudClient = class {
1004
992
  });
1005
993
  }
1006
994
  token = await this.tokenRefreshPromise ?? this.activeToken;
1007
- response = await this.transport.request({ ...fullRequest, authorizationToken: token });
995
+ response = await withToken(token);
1008
996
  }
1009
997
  return response;
1010
998
  }
@@ -1071,7 +1059,8 @@ var ConfigCache = class {
1071
1059
  if (parsed.schemaVersion !== CONFIG_SCHEMA_VERSION || parsed.projectId !== projectId) {
1072
1060
  return null;
1073
1061
  }
1074
- if (!ignoreTtl && Date.now() - parsed.fetchedAt > CONFIG_CACHE_TTL_MS) {
1062
+ const maxAgeMs = parsed.maxAgeMs ?? CONFIG_CACHE_TTL_MS;
1063
+ if (!ignoreTtl && Date.now() - parsed.fetchedAt > maxAgeMs) {
1075
1064
  return null;
1076
1065
  }
1077
1066
  return normalizeProjectConfig(parsed.config);
@@ -1101,6 +1090,8 @@ var ConfigCache = class {
1101
1090
  fetchedAt: Date.now(),
1102
1091
  etag: meta?.etag,
1103
1092
  revision: meta?.revision ?? config.version,
1093
+ maxAgeMs: meta?.maxAgeMs,
1094
+ staleIfErrorMs: meta?.staleIfErrorMs,
1104
1095
  config
1105
1096
  };
1106
1097
  this.storage.write("config", JSON.stringify(envelope));
@@ -1142,19 +1133,26 @@ var ConfigManager = class {
1142
1133
  async executeRefresh(_options) {
1143
1134
  const prev = this.current;
1144
1135
  try {
1145
- const remote = await this.cloud.fetchConfig();
1146
- const normalized = normalizeProjectConfig(remote);
1136
+ const cached = this.cache.getEnvelope(this.options.projectId);
1137
+ const normalized = normalizeProjectConfig(await this.cloud.fetchConfig(cached?.etag, cached?.config));
1138
+ const receivedMetadata = this.cloud.getConfigMetadata?.() ?? {};
1139
+ const metadata = {
1140
+ ...receivedMetadata,
1141
+ maxAgeMs: receivedMetadata.maxAgeMs ?? cached?.maxAgeMs,
1142
+ staleIfErrorMs: receivedMetadata.staleIfErrorMs ?? cached?.staleIfErrorMs
1143
+ };
1147
1144
  this.current = normalized;
1148
- this.cache.write(this.options.projectId, normalized);
1145
+ this.cache.write(this.options.projectId, normalized, metadata);
1149
1146
  const hasChanged = prev.version !== normalized.version || prev.avatarName !== normalized.avatarName || prev.position !== normalized.position || prev.size !== normalized.size || prev.assetUrl !== normalized.assetUrl || prev.thumbnailUrl !== normalized.thumbnailUrl || JSON.stringify(prev.theme) !== JSON.stringify(normalized.theme) || JSON.stringify(prev.animations) !== JSON.stringify(normalized.animations);
1150
1147
  if (hasChanged && this.onConfigUpdated) {
1151
1148
  this.onConfigUpdated(normalized, prev);
1152
1149
  }
1153
1150
  return this.current;
1154
1151
  } catch (error) {
1155
- const lastKnownGood = this.cache.read(this.options.projectId, true);
1156
- if (lastKnownGood) {
1157
- this.current = lastKnownGood;
1152
+ const cached = this.cache.getEnvelope(this.options.projectId);
1153
+ const staleIfErrorMs = cached?.staleIfErrorMs ?? API_LIMITS.configStaleIfErrorMs;
1154
+ if (cached && staleIfErrorMs > 0 && Date.now() - cached.fetchedAt <= staleIfErrorMs) {
1155
+ this.current = normalizeProjectConfig(cached.config);
1158
1156
  }
1159
1157
  this.events.emit("asiyst:error", {
1160
1158
  code: "config_refresh_failed",
@@ -1831,7 +1829,7 @@ var CHUNK_TYPE_JSON = 1313821514;
1831
1829
  var CHUNK_TYPE_BIN = 5130562;
1832
1830
  var AssetLoader = class {
1833
1831
  constructor() {
1834
- this.inFlightController = null;
1832
+ this.inFlightControllers = /* @__PURE__ */ new Set();
1835
1833
  this.createdObjectUrls = [];
1836
1834
  this.inFlightLoads = /* @__PURE__ */ new Map();
1837
1835
  this.cachedAssets = /* @__PURE__ */ new Map();
@@ -1841,31 +1839,42 @@ var AssetLoader = class {
1841
1839
  if (!sanitizedUrl) {
1842
1840
  throw new Error("Asset URL is required");
1843
1841
  }
1844
- const cached = this.cachedAssets.get(sanitizedUrl);
1842
+ let parsedUrl;
1843
+ try {
1844
+ parsedUrl = new URL(sanitizedUrl, typeof location === "undefined" ? void 0 : location.href);
1845
+ } catch {
1846
+ throw new Error("Avatar asset URL is invalid");
1847
+ }
1848
+ if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:" || parsedUrl.username || parsedUrl.password) {
1849
+ throw new Error("Avatar asset URL must use HTTP or HTTPS without embedded credentials");
1850
+ }
1851
+ const cacheKey = `${sanitizedUrl}\0${options?.integrity ?? ""}\0${options?.expectedFormat ?? ""}`;
1852
+ const cached = this.cachedAssets.get(cacheKey);
1845
1853
  if (cached) {
1846
1854
  return cached;
1847
1855
  }
1848
- const inFlight = this.inFlightLoads.get(sanitizedUrl);
1856
+ const inFlight = this.inFlightLoads.get(cacheKey);
1849
1857
  if (inFlight) {
1850
1858
  return inFlight;
1851
1859
  }
1852
1860
  const loadPromise = this.performLoad(sanitizedUrl, options);
1853
- this.inFlightLoads.set(sanitizedUrl, loadPromise);
1861
+ this.inFlightLoads.set(cacheKey, loadPromise);
1854
1862
  try {
1855
1863
  const asset = await loadPromise;
1856
- this.cachedAssets.set(sanitizedUrl, asset);
1864
+ this.cachedAssets.set(cacheKey, asset);
1857
1865
  return asset;
1858
1866
  } finally {
1859
- this.inFlightLoads.delete(sanitizedUrl);
1867
+ this.inFlightLoads.delete(cacheKey);
1860
1868
  }
1861
1869
  }
1862
1870
  async performLoad(sanitizedUrl, options) {
1863
1871
  const startTime = Date.now();
1864
- this.inFlightController = new AbortController();
1865
- const abortSignal = options?.signal ? anySignal([this.inFlightController.signal, options.signal]) : this.inFlightController.signal;
1872
+ const controller = new AbortController();
1873
+ this.inFlightControllers.add(controller);
1874
+ const abortSignal = options?.signal ? anySignal([controller.signal, options.signal]) : controller.signal;
1866
1875
  const timeoutMs = options?.timeoutMs ?? 6e4;
1867
1876
  const timeoutId = setTimeout(() => {
1868
- this.inFlightController?.abort();
1877
+ controller.abort();
1869
1878
  }, timeoutMs);
1870
1879
  try {
1871
1880
  const cleanPath = (sanitizedUrl.split("?")[0] ?? "").toLowerCase();
@@ -1939,12 +1948,25 @@ var AssetLoader = class {
1939
1948
  if (arrayBuffer.byteLength < 12) {
1940
1949
  throw new Error("Avatar asset payload is too small to be a valid 3D container");
1941
1950
  }
1951
+ if (options?.integrity) {
1952
+ await verifyIntegrity(arrayBuffer, options.integrity);
1953
+ }
1942
1954
  const headerBytes = new Uint8Array(arrayBuffer, 0, Math.min(256, arrayBuffer.byteLength));
1943
1955
  const headerStr = new TextDecoder("utf-8", { fatal: false }).decode(headerBytes).trim();
1944
1956
  if (/^<!DOCTYPE\s+html/i.test(headerStr) || /^<html/i.test(headerStr)) {
1945
1957
  throw new Error(`Avatar asset payload contains HTML error page instead of binary 3D container from ${sanitizedUrl}`);
1946
1958
  }
1947
- if (isFbxExtension || this.isFbxBuffer(arrayBuffer) || !isGlbExtension && !this.isGlbBuffer(arrayBuffer)) {
1959
+ const hasFbxSignature = this.isFbxBuffer(arrayBuffer);
1960
+ const hasGlbSignature = this.isGlbBuffer(arrayBuffer);
1961
+ const isFbx = hasFbxSignature || !hasGlbSignature && isFbxExtension;
1962
+ const isGlb = hasGlbSignature || !hasFbxSignature && isGlbExtension;
1963
+ if (isFbx && isGlb) {
1964
+ throw new Error("Avatar asset format is ambiguous");
1965
+ }
1966
+ if (isFbx) {
1967
+ if (options?.expectedFormat && options.expectedFormat !== "fbx") {
1968
+ throw new Error(`Avatar asset format mismatch: expected ${options.expectedFormat}, received fbx`);
1969
+ }
1948
1970
  const fbxHeader = this.parseFbxHeader(arrayBuffer);
1949
1971
  const resourcePath = sanitizedUrl.includes("/") ? sanitizedUrl.substring(0, sanitizedUrl.lastIndexOf("/") + 1) : "";
1950
1972
  return {
@@ -1957,6 +1979,12 @@ var AssetLoader = class {
1957
1979
  durationMs: Date.now() - startTime
1958
1980
  };
1959
1981
  }
1982
+ if (!isGlb) {
1983
+ throw new Error("Avatar asset format is unsupported; expected FBX or GLB");
1984
+ }
1985
+ if (options?.expectedFormat && options.expectedFormat !== "glb") {
1986
+ throw new Error(`Avatar asset format mismatch: expected ${options.expectedFormat}, received glb`);
1987
+ }
1960
1988
  const parsedGlb = this.parseGlb(arrayBuffer);
1961
1989
  return {
1962
1990
  format: "glb",
@@ -1969,7 +1997,7 @@ var AssetLoader = class {
1969
1997
  };
1970
1998
  } finally {
1971
1999
  clearTimeout(timeoutId);
1972
- this.inFlightController = null;
2000
+ this.inFlightControllers.delete(controller);
1973
2001
  }
1974
2002
  }
1975
2003
  isFbxBuffer(buffer) {
@@ -2185,10 +2213,8 @@ var AssetLoader = class {
2185
2213
  };
2186
2214
  }
2187
2215
  destroy() {
2188
- if (this.inFlightController) {
2189
- this.inFlightController.abort();
2190
- this.inFlightController = null;
2191
- }
2216
+ for (const controller of this.inFlightControllers) controller.abort();
2217
+ this.inFlightControllers.clear();
2192
2218
  this.inFlightLoads.clear();
2193
2219
  this.cachedAssets.clear();
2194
2220
  if (typeof URL !== "undefined" && typeof URL.revokeObjectURL === "function") {
@@ -2202,6 +2228,20 @@ var AssetLoader = class {
2202
2228
  this.createdObjectUrls.length = 0;
2203
2229
  }
2204
2230
  };
2231
+ async function verifyIntegrity(buffer, integrity) {
2232
+ const [algorithm, expected] = integrity.split("-", 2);
2233
+ if (algorithm !== "sha256" || !expected) {
2234
+ throw new Error("Avatar asset integrity metadata is invalid");
2235
+ }
2236
+ const cryptoApi = globalThis.crypto;
2237
+ if (!cryptoApi?.subtle) return;
2238
+ const digest = new Uint8Array(await cryptoApi.subtle.digest("SHA-256", buffer));
2239
+ let binary = "";
2240
+ for (const byte of digest) binary += String.fromCharCode(byte);
2241
+ if (btoa(binary) !== expected) {
2242
+ throw new Error("Avatar asset integrity verification failed");
2243
+ }
2244
+ }
2205
2245
  function anySignal(signals) {
2206
2246
  const controller = new AbortController();
2207
2247
  for (const sig of signals) {
@@ -2442,47 +2482,6 @@ var FbxRenderer = class {
2442
2482
  if (this.playAnimation(pose)) {
2443
2483
  return;
2444
2484
  }
2445
- if (this.mixer && this.allAnimations.length > 0) {
2446
- let targetClip;
2447
- if (pose === "speak") {
2448
- targetClip = this.allAnimations.find(
2449
- (c) => c.name.toLowerCase().includes("talk") || c.name.toLowerCase().includes("speak")
2450
- );
2451
- } else if (pose === "think") {
2452
- targetClip = this.allAnimations.find(
2453
- (c) => c.name.toLowerCase().includes("think")
2454
- );
2455
- } else if (pose === "walk") {
2456
- targetClip = this.allAnimations.find(
2457
- (c) => c.name.toLowerCase().includes("walk") || c.name.toLowerCase().includes("run")
2458
- );
2459
- } else if (pose === "point") {
2460
- targetClip = this.allAnimations.find(
2461
- (c) => c.name.toLowerCase().includes("point")
2462
- );
2463
- } else if (pose === "celebrate") {
2464
- targetClip = this.allAnimations.find(
2465
- (c) => c.name.toLowerCase().includes("celebrat") || c.name.toLowerCase().includes("wave") || c.name.toLowerCase().includes("cheer") || c.name.toLowerCase().includes("jump")
2466
- );
2467
- } else {
2468
- targetClip = this.allAnimations.find((c) => c.name.toLowerCase().includes("idle")) || this.animationMetadataList[0]?.clip || this.allAnimations[0];
2469
- }
2470
- if (targetClip) {
2471
- const newAction = this.mixer.clipAction(targetClip);
2472
- if (newAction !== this.currentAction) {
2473
- newAction.reset().fadeIn(0.25).play();
2474
- if (this.currentAction) {
2475
- this.currentAction.fadeOut(0.25);
2476
- }
2477
- this.currentAction = newAction;
2478
- return;
2479
- } else if (!this.currentAction?.isRunning()) {
2480
- this.currentAction?.play();
2481
- return;
2482
- }
2483
- return;
2484
- }
2485
- }
2486
2485
  if (!this.modelRoot) return;
2487
2486
  this.modelRoot.scale.setScalar(this.baseScale);
2488
2487
  switch (pose) {
@@ -2527,13 +2526,13 @@ var FbxRenderer = class {
2527
2526
  return true;
2528
2527
  }
2529
2528
  const idleByName = this.animationMetadataList.find(
2530
- (m) => m.name.toLowerCase().includes("idle") || m.clipName && m.clipName.toLowerCase().includes("idle")
2529
+ (m) => m.name.toLowerCase() === "idle" || m.clipName?.toLowerCase() === "idle"
2531
2530
  );
2532
2531
  if (idleByName && this.playAnimation(idleByName.id || idleByName.name)) {
2533
2532
  return true;
2534
2533
  }
2535
2534
  const embeddedIdle = this.allAnimations.find(
2536
- (c) => c.name.toLowerCase().includes("idle")
2535
+ (c) => c.name.toLowerCase() === "idle"
2537
2536
  );
2538
2537
  if (embeddedIdle) {
2539
2538
  const action = this.mixer.clipAction(embeddedIdle);
@@ -2544,22 +2543,6 @@ var FbxRenderer = class {
2544
2543
  }
2545
2544
  return true;
2546
2545
  }
2547
- if (this.animationMetadataList.length > 0) {
2548
- const firstMeta = this.animationMetadataList[0];
2549
- if (this.playAnimation(firstMeta.id || firstMeta.name)) {
2550
- return true;
2551
- }
2552
- }
2553
- if (this.allAnimations.length > 0) {
2554
- const firstClip = this.allAnimations[0];
2555
- const action = this.mixer.clipAction(firstClip);
2556
- if (this.currentAction !== action) {
2557
- action.reset().fadeIn(0.25).play();
2558
- if (this.currentAction) this.currentAction.fadeOut(0.25);
2559
- this.currentAction = action;
2560
- }
2561
- return true;
2562
- }
2563
2546
  return false;
2564
2547
  }
2565
2548
  async loadExternalAnimations(animations, targetAnimationName) {
@@ -2577,7 +2560,7 @@ var FbxRenderer = class {
2577
2560
  await Promise.allSettled(
2578
2561
  pending.map(async (anim) => {
2579
2562
  try {
2580
- const loaded = await this.assetLoader.load(anim.assetUrl);
2563
+ const loaded = await this.assetLoader.load(anim.assetUrl, { integrity: anim.integrity });
2581
2564
  let extractedClips = [];
2582
2565
  if (loaded.format === "fbx") {
2583
2566
  const loader = new FBXLoader_js.FBXLoader();
@@ -2703,13 +2686,13 @@ var FbxRenderer = class {
2703
2686
  clip = this.allAnimations.find((c) => c.name.toLowerCase() === query);
2704
2687
  }
2705
2688
  if (!clip) {
2706
- clip = this.allAnimations.find((c) => c.name.toLowerCase().includes(query));
2689
+ clip = this.allAnimations.find((c) => c.name.toLowerCase() === query);
2707
2690
  }
2708
2691
  if (!clip) {
2709
2692
  return false;
2710
2693
  }
2711
2694
  const action = this.mixer.clipAction(clip);
2712
- const effectiveLoop = loopMode || matched?.loopMode || "repeat";
2695
+ const effectiveLoop = (loopMode || matched?.loopMode || "loop").toLowerCase();
2713
2696
  if (effectiveLoop === "once") {
2714
2697
  action.setLoop(THREE__namespace.LoopOnce, 1);
2715
2698
  action.clampWhenFinished = true;
@@ -3282,7 +3265,11 @@ var CssAvatarRenderer = class {
3282
3265
  }
3283
3266
  try {
3284
3267
  this.metricsTracker?.record("assetRequestStart");
3285
- const asset = await this.assetLoader.load(assetUrl, { timeoutMs: 6e4 });
3268
+ const asset = await this.assetLoader.load(assetUrl, {
3269
+ timeoutMs: 6e4,
3270
+ integrity: config.assetIntegrity,
3271
+ expectedFormat: config.assetUrl ? config.modelFormat : void 0
3272
+ });
3286
3273
  this.metricsTracker?.record("assetDownloadComplete");
3287
3274
  const byteSize = asset.buffer?.byteLength ?? asset.bin?.byteLength ?? asset.size;
3288
3275
  this.metricsTracker?.setAssetInfo({
@@ -3383,7 +3370,10 @@ var CssAvatarRenderer = class {
3383
3370
  const thumb = typeof asset.manifest.thumbnailUrl === "string" ? asset.manifest.thumbnailUrl : void 0;
3384
3371
  const modelUrl = typeof asset.manifest.assetUrl === "string" ? asset.manifest.assetUrl : typeof asset.manifest.modelUrl === "string" ? asset.manifest.modelUrl : void 0;
3385
3372
  if (modelUrl) {
3386
- const subAsset = await this.assetLoader.load(modelUrl, { timeoutMs: 6e4 });
3373
+ const subAsset = await this.assetLoader.load(modelUrl, {
3374
+ timeoutMs: 6e4,
3375
+ expectedFormat: config.modelFormat
3376
+ });
3387
3377
  await this.renderLoadedAsset(subAsset, config);
3388
3378
  } else if (thumb) {
3389
3379
  this.viewport.replaceChildren();
@@ -4177,11 +4167,10 @@ function transition(from, to) {
4177
4167
 
4178
4168
  // src/task/TaskEngine.ts
4179
4169
  var TaskEngine = class {
4180
- constructor(interaction, events, analytics, cloud) {
4170
+ constructor(interaction, events, analytics) {
4181
4171
  this.interaction = interaction;
4182
4172
  this.events = events;
4183
4173
  this.analytics = analytics;
4184
- this.cloud = cloud;
4185
4174
  this.status = TaskStatus.Idle;
4186
4175
  this.abort = false;
4187
4176
  }
@@ -4197,7 +4186,6 @@ var TaskEngine = class {
4197
4186
  this.events.emit("asiyst:task:started", { taskId: task.id });
4198
4187
  this.analytics.track("task_started", { taskId: task.id });
4199
4188
  this.analytics.track("guide_started", { taskId: task.id });
4200
- void this.cloud.sendTaskUpdate(task.id, this.status);
4201
4189
  try {
4202
4190
  for (const [index, step] of task.steps.entries()) {
4203
4191
  if (this.abort) {
@@ -4232,13 +4220,11 @@ var TaskEngine = class {
4232
4220
  }
4233
4221
  this.move(TaskStatus.StepCompleted);
4234
4222
  this.events.emit("asiyst:task:step-completed", { taskId: task.id, stepId: step.id });
4235
- void this.cloud.sendTaskUpdate(task.id, this.status, step.id);
4236
4223
  }
4237
4224
  this.move(TaskStatus.TaskCompleted);
4238
4225
  this.events.emit("asiyst:task:completed", { taskId: task.id });
4239
4226
  this.analytics.track("task_completed", { taskId: task.id });
4240
4227
  this.analytics.track("guide_completed", { taskId: task.id });
4241
- void this.cloud.sendTaskUpdate(task.id, this.status);
4242
4228
  this.move(TaskStatus.Idle);
4243
4229
  return TaskStatus.TaskCompleted;
4244
4230
  } catch (error) {
@@ -4313,6 +4299,7 @@ var ConversationPanel = class {
4313
4299
  this.onToggle = onToggle;
4314
4300
  this.conversationId = "";
4315
4301
  this.openState = false;
4302
+ this.submitting = false;
4316
4303
  const doc = root.ownerDocument;
4317
4304
  this.style = doc.createElement("style");
4318
4305
  this.style.textContent = `
@@ -4410,6 +4397,9 @@ var ConversationPanel = class {
4410
4397
  getConversationId() {
4411
4398
  return this.conversationId;
4412
4399
  }
4400
+ setConversationId(conversationId) {
4401
+ this.conversationId = conversationId;
4402
+ }
4413
4403
  open() {
4414
4404
  if (!this.conversationId) {
4415
4405
  this.conversationId = `conv_${Date.now().toString(36)}`;
@@ -4424,22 +4414,51 @@ var ConversationPanel = class {
4424
4414
  this.panel.hidden = true;
4425
4415
  this.onToggle(false);
4426
4416
  }
4427
- append(role, text) {
4417
+ append(role, text, citations = []) {
4428
4418
  const item = this.log.ownerDocument.createElement("div");
4429
4419
  item.className = "asiyst-msg";
4430
4420
  item.setAttribute("data-role", role);
4431
4421
  renderSafeText(item, text);
4422
+ for (const citation of citations) {
4423
+ if (!citation.url) continue;
4424
+ let url;
4425
+ try {
4426
+ url = new URL(citation.url);
4427
+ } catch {
4428
+ continue;
4429
+ }
4430
+ if (url.protocol !== "https:") continue;
4431
+ const link = this.log.ownerDocument.createElement("a");
4432
+ link.href = url.href;
4433
+ link.rel = "noopener noreferrer";
4434
+ link.target = "_blank";
4435
+ link.textContent = sanitizeText(citation.title, 160);
4436
+ const wrapper = this.log.ownerDocument.createElement("div");
4437
+ wrapper.appendChild(link);
4438
+ item.appendChild(wrapper);
4439
+ }
4432
4440
  this.log.appendChild(item);
4433
4441
  this.log.scrollTop = this.log.scrollHeight;
4434
4442
  }
4435
4443
  async submit() {
4444
+ if (this.submitting) return;
4436
4445
  const text = sanitizeText(this.input.value);
4437
4446
  if (!text) {
4438
4447
  return;
4439
4448
  }
4449
+ this.submitting = true;
4450
+ this.input.disabled = true;
4451
+ this.form.querySelector("button")?.setAttribute("disabled", "true");
4440
4452
  this.input.value = "";
4441
4453
  this.append("user", text);
4442
- await this.onSubmit(text);
4454
+ try {
4455
+ await this.onSubmit(text);
4456
+ } finally {
4457
+ this.submitting = false;
4458
+ this.input.disabled = false;
4459
+ this.form.querySelector("button")?.removeAttribute("disabled");
4460
+ this.input.focus();
4461
+ }
4443
4462
  }
4444
4463
  destroy() {
4445
4464
  if (this.keydownListener) {
@@ -4502,19 +4521,15 @@ function loadOrCreateInstallationId(projectId) {
4502
4521
  }
4503
4522
 
4504
4523
  // src/communication/RuntimeAuth.ts
4505
- var RUNTIME_AUDIENCE = "asiyst-sdk-runtime";
4506
- var RUNTIME_CAPABILITIES = [
4507
- "assistant:config",
4508
- "assistant:conversation",
4509
- "assistant:telemetry",
4510
- "assistant:heartbeat"
4511
- ];
4512
4524
  var RuntimeAuth = class {
4513
4525
  constructor(options) {
4514
4526
  this.options = options;
4515
4527
  }
4516
- async getToken(capability) {
4517
- if (this.token && this.isUsable(this.token) && this.token.capabilities.has(capability)) {
4528
+ setInstallationId(installationId) {
4529
+ this.options.installationId = installationId;
4530
+ }
4531
+ async getToken() {
4532
+ if (this.token && this.isUsable(this.token) && Date.now() < this.token.refreshAfter) {
4518
4533
  return this.token.value;
4519
4534
  }
4520
4535
  if (!this.requestInFlight) {
@@ -4523,33 +4538,38 @@ var RuntimeAuth = class {
4523
4538
  });
4524
4539
  }
4525
4540
  const token = await this.requestInFlight;
4526
- if (!token.capabilities.has(capability)) {
4527
- throw new AuthenticationError("ASIYST runtime authorization does not allow this operation.");
4528
- }
4529
4541
  return token.value;
4530
4542
  }
4531
4543
  invalidate() {
4532
4544
  this.token = void 0;
4533
4545
  }
4534
4546
  isUsable(token) {
4535
- return token.expiresAt - Date.now() > 3e4;
4547
+ return token.expiresAt > Date.now();
4536
4548
  }
4537
4549
  async issueToken() {
4550
+ const installationId = this.options.installationId;
4551
+ if (!installationId) {
4552
+ throw new AuthenticationError("ASIYST installation has not been verified.");
4553
+ }
4538
4554
  const controller = new AbortController();
4539
- const timeout = setTimeout(() => controller.abort(), 1e4);
4555
+ let timedOut = false;
4556
+ const timeout = setTimeout(() => {
4557
+ timedOut = true;
4558
+ controller.abort();
4559
+ }, 1e4);
4540
4560
  let response;
4541
4561
  try {
4542
4562
  const baseUrl = this.options.apiBaseUrl.replace(/\/$/, "");
4543
4563
  const payload = JSON.stringify({
4544
4564
  projectId: this.options.projectId,
4545
4565
  publicKey: this.options.publicKey,
4546
- installationId: this.options.installationId,
4566
+ installationId,
4547
4567
  origin: this.options.origin,
4548
- environment: this.options.environment,
4549
4568
  sdkVersion: SDK_VERSION,
4550
- capabilities: [...RUNTIME_CAPABILITIES]
4569
+ environment: this.options.environment,
4570
+ capabilities: ["assistant:config", "assistant:conversation", "assistant:heartbeat"]
4551
4571
  });
4552
- response = await fetch(`${baseUrl}/sdk/runtime/token`, {
4572
+ response = await fetch(contractApiUrl(baseUrl, API_ROUTES.runtimeToken), {
4553
4573
  method: "POST",
4554
4574
  headers: {
4555
4575
  Accept: "application/json",
@@ -4558,19 +4578,8 @@ var RuntimeAuth = class {
4558
4578
  body: payload,
4559
4579
  signal: controller.signal
4560
4580
  });
4561
- if (response.status === 404) {
4562
- response = await fetch(`${baseUrl}/api/v1/sdk/runtime/token`, {
4563
- method: "POST",
4564
- headers: {
4565
- Accept: "application/json",
4566
- "Content-Type": "application/json"
4567
- },
4568
- body: payload,
4569
- signal: controller.signal
4570
- });
4571
- }
4572
4581
  } catch {
4573
- throw new NetworkError("ASIYST runtime authentication is unavailable.");
4582
+ throw new NetworkError(timedOut ? "ASIYST runtime authentication request timed out." : "ASIYST runtime authentication is unavailable.");
4574
4583
  } finally {
4575
4584
  clearTimeout(timeout);
4576
4585
  }
@@ -4587,10 +4596,13 @@ var RuntimeAuth = class {
4587
4596
  if (response.status === 429) {
4588
4597
  throw new NetworkError("ASIYST runtime authentication is rate limited.");
4589
4598
  }
4599
+ if (response.status === 503) {
4600
+ throw new NetworkError("ASIYST runtime authentication is unavailable.");
4601
+ }
4590
4602
  throw new NetworkError("ASIYST runtime authentication is unavailable.");
4591
4603
  }
4592
4604
  const data = body?.data;
4593
- if (!data || body?.success !== true || typeof data.token !== "string" || data.token.length < 20 || data.tokenType !== "Bearer" || data.audience !== RUNTIME_AUDIENCE || typeof data.expiresIn !== "number" || !Number.isFinite(data.expiresIn) || data.expiresIn <= 0 || typeof data.expiresAt !== "string" || !Array.isArray(data.capabilities) || data.capabilities.some((capability) => !RUNTIME_CAPABILITIES.includes(capability))) {
4605
+ if (body?.success !== true || !data || typeof data.token !== "string" || data.token.length < 20 || data.tokenType !== "Bearer" || data.audience !== "asiyst-sdk-runtime" || typeof data.expiresAt !== "string" || data.expiresIn !== 300 || !Array.isArray(data.capabilities) || !data.capabilities.includes("assistant:config") || !data.capabilities.includes("assistant:conversation") || !data.capabilities.includes("assistant:heartbeat")) {
4594
4606
  throw new AuthenticationError("ASIYST returned an invalid runtime authorization response.");
4595
4607
  }
4596
4608
  const expiresAt = Date.parse(data.expiresAt);
@@ -4600,7 +4612,7 @@ var RuntimeAuth = class {
4600
4612
  const token = {
4601
4613
  value: data.token,
4602
4614
  expiresAt,
4603
- capabilities: new Set(data.capabilities)
4615
+ refreshAfter: expiresAt
4604
4616
  };
4605
4617
  this.token = token;
4606
4618
  return token;
@@ -4766,6 +4778,7 @@ var AsiystRuntime = class {
4766
4778
  this.rescanDebounced = debounce(() => this.rescan(), DOM_SCAN_DEBOUNCE_MS);
4767
4779
  this.isHeartbeatInFlight = false;
4768
4780
  this.lastHeartbeatTime = 0;
4781
+ this.nextHeartbeatAfterMs = HEARTBEAT_INTERVAL_MS;
4769
4782
  this.registrationSucceeded = false;
4770
4783
  if (!doc.body) {
4771
4784
  throw new InitializationError("document.body is not available");
@@ -4785,10 +4798,11 @@ var AsiystRuntime = class {
4785
4798
  apiBaseUrl: options.apiBaseUrl ?? DEFAULT_API_BASE_URL,
4786
4799
  projectId: options.projectId,
4787
4800
  publicKey: options.publicKey,
4788
- installationId: this.installationId,
4801
+ installationId: void 0,
4789
4802
  origin: win.location.origin,
4790
4803
  environment: this.environment
4791
4804
  }) : void 0;
4805
+ this.runtimeAuth = runtimeAuth;
4792
4806
  this.cloud = new CloudClient(transport, options.projectId, options.publicKey, runtimeAuth, this.visitorSessionId, options.avatarId);
4793
4807
  this.config = new ConfigManager(options, this.cloud, this.events);
4794
4808
  this.config.onConfigUpdated = (newConfig, prevConfig) => {
@@ -4820,21 +4834,19 @@ var AsiystRuntime = class {
4820
4834
  () => this.config.get()
4821
4835
  );
4822
4836
  const interaction = new InteractionEngine(this.avatar, this.resolver, () => this.config.get(), win);
4823
- this.tasks = new TaskEngine(interaction, this.events, this.analytics, this.cloud);
4837
+ this.tasks = new TaskEngine(interaction, this.events, this.analytics);
4824
4838
  this.workflows = new WorkflowEngine(this.cloud, this.tasks);
4825
4839
  this.panel = new ConversationPanel(
4826
4840
  this.host.chrome,
4827
4841
  (text) => this.handleUserMessage(text, doc),
4828
4842
  (open) => {
4829
- const convId = this.panel.getConversationId();
4830
- this.cloud.setConversationId(convId);
4831
4843
  this.renderer.setPanelOpen(open);
4832
4844
  if (open) {
4833
4845
  this.analytics.track("assistant_opened");
4834
- this.events.emit("asiyst:conversation:started", { conversationId: convId });
4835
4846
  } else {
4836
4847
  this.analytics.track("assistant_closed");
4837
- this.events.emit("asiyst:conversation:closed", { conversationId: convId });
4848
+ const conversationId = this.panel.getConversationId();
4849
+ if (conversationId) this.events.emit("asiyst:conversation:closed", { conversationId });
4838
4850
  }
4839
4851
  }
4840
4852
  );
@@ -4843,22 +4855,35 @@ var AsiystRuntime = class {
4843
4855
  this.observer.start(doc.documentElement);
4844
4856
  this.highlights.start();
4845
4857
  this.movement.start();
4846
- this.analytics.start();
4847
4858
  this.rescan();
4848
4859
  const figure = this.renderer.getFigure();
4849
4860
  if (figure) {
4850
4861
  this.figureClickListener = () => this.open();
4851
4862
  figure.addEventListener("click", this.figureClickListener);
4852
4863
  }
4853
- this.pagehideListener = () => {
4854
- void this.analytics.flush();
4855
- };
4856
- win.addEventListener("pagehide", this.pagehideListener);
4857
4864
  }
4858
4865
  async start() {
4859
4866
  this.events.emit("asiyst:initialized", { projectId: this.options.projectId });
4860
4867
  this.avatar.show();
4861
4868
  this.movement.goToAnchor();
4869
+ this.lifecycle.emit("sdk.verification_started", {
4870
+ projectId: this.options.projectId,
4871
+ origin: window.location.origin,
4872
+ environment: this.environment,
4873
+ installationId: this.installationId,
4874
+ sdkVersion: SDK_VERSION
4875
+ });
4876
+ try {
4877
+ await this.registerInstallation();
4878
+ } catch (error) {
4879
+ this.connectionStatus = "offline";
4880
+ this.verificationStatus = "error";
4881
+ this.events.emit("asiyst:error", {
4882
+ code: "runtime_connection_failed",
4883
+ message: error instanceof Error ? error.message : "Asiyst runtime connection failed."
4884
+ });
4885
+ return;
4886
+ }
4862
4887
  const cfg = await isolateAsync(() => this.config.refresh(), this.config.get());
4863
4888
  this.metricsTracker.record("configRetrieved");
4864
4889
  const domainCheck = validateWebsiteDomain(cfg, window.location.href);
@@ -4873,28 +4898,7 @@ var AsiystRuntime = class {
4873
4898
  }
4874
4899
  this.avatar.applyConfig(cfg);
4875
4900
  this.movement.goToAnchor();
4876
- this.lifecycle.emit("sdk.verification_started", {
4877
- projectId: this.options.projectId,
4878
- origin: window.location.origin,
4879
- environment: this.environment,
4880
- installationId: this.installationId,
4881
- sdkVersion: SDK_VERSION
4882
- });
4883
- void (async () => {
4884
- try {
4885
- await this.registerInstallation();
4886
- await this.sendHeartbeat();
4887
- const doc = this.host.host.ownerDocument;
4888
- this.startHeartbeatScheduler(doc);
4889
- } catch {
4890
- }
4891
- })();
4892
4901
  this.events.emit("asiyst:ready", { projectId: this.options.projectId, configVersion: cfg.version });
4893
- void this.cloud.sendTelemetryEvent("avatar_runtime_initialized", {
4894
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4895
- avatarName: cfg.avatarName,
4896
- publishedVersion: cfg.publishedVersion
4897
- });
4898
4902
  const assetTarget = cfg.assetUrl ?? cfg.thumbnailUrl;
4899
4903
  if (assetTarget) {
4900
4904
  try {
@@ -4907,6 +4911,16 @@ var AsiystRuntime = class {
4907
4911
  this.avatar.show();
4908
4912
  this.movement.goToAnchor();
4909
4913
  }
4914
+ try {
4915
+ await this.sendHeartbeat();
4916
+ } catch (error) {
4917
+ this.connectionStatus = "offline";
4918
+ this.verificationStatus = "error";
4919
+ this.events.emit("asiyst:error", {
4920
+ code: "runtime_connection_failed",
4921
+ message: error instanceof Error ? error.message : "Asiyst runtime connection failed."
4922
+ });
4923
+ }
4910
4924
  this.startConfigRevalidationScheduler();
4911
4925
  }
4912
4926
  async loadAvatarAsset(cfg, assetTarget) {
@@ -4914,10 +4928,6 @@ var AsiystRuntime = class {
4914
4928
  avatarId: this.options.avatarId ?? cfg.avatarId,
4915
4929
  assetUrl: assetTarget
4916
4930
  });
4917
- void this.cloud.sendTelemetryEvent("avatar_asset_loading_started", {
4918
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4919
- assetUrl: assetTarget
4920
- });
4921
4931
  try {
4922
4932
  const loaded = await this.renderer.loadAsset(cfg, this.metricsTracker);
4923
4933
  if (loaded) {
@@ -4930,13 +4940,6 @@ var AsiystRuntime = class {
4930
4940
  assetUrl,
4931
4941
  format
4932
4942
  });
4933
- void this.cloud.sendTelemetryEvent("avatar_asset_loaded", {
4934
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4935
- avatarName: cfg.avatarName,
4936
- assetUrl,
4937
- format,
4938
- publishedVersion: cfg.publishedVersion
4939
- });
4940
4943
  if (isRendered) {
4941
4944
  const metrics = this.metricsTracker.getMetrics();
4942
4945
  const durationMs = metrics?.durations.timeToFirstVisibleMs;
@@ -4945,13 +4948,6 @@ var AsiystRuntime = class {
4945
4948
  format,
4946
4949
  durationMs
4947
4950
  });
4948
- void this.cloud.sendTelemetryEvent("avatar_rendered", {
4949
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4950
- avatarName: cfg.avatarName,
4951
- format,
4952
- publishedVersion: cfg.publishedVersion,
4953
- durationMs
4954
- });
4955
4951
  }
4956
4952
  return true;
4957
4953
  } else {
@@ -4961,11 +4957,6 @@ var AsiystRuntime = class {
4961
4957
  error: err,
4962
4958
  stage: "renderer_init"
4963
4959
  });
4964
- void this.cloud.sendTelemetryEvent("avatar_render_failed", {
4965
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4966
- error: err,
4967
- stage: "renderer_init"
4968
- });
4969
4960
  return false;
4970
4961
  }
4971
4962
  } catch (error) {
@@ -4975,11 +4966,6 @@ var AsiystRuntime = class {
4975
4966
  error: err,
4976
4967
  stage: "asset_fetch"
4977
4968
  });
4978
- void this.cloud.sendTelemetryEvent("avatar_render_failed", {
4979
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4980
- error: err,
4981
- stage: "asset_fetch"
4982
- });
4983
4969
  return false;
4984
4970
  }
4985
4971
  }
@@ -5026,6 +5012,7 @@ var AsiystRuntime = class {
5026
5012
  config: newConfig,
5027
5013
  previousVersion: prevConfig?.version
5028
5014
  });
5015
+ void this.sendHeartbeat();
5029
5016
  }
5030
5017
  async reloadConfig() {
5031
5018
  const updated = await this.config.refresh({ force: true });
@@ -5115,15 +5102,11 @@ var AsiystRuntime = class {
5115
5102
  clearInterval(this.configRevalidationTimer);
5116
5103
  this.configRevalidationTimer = void 0;
5117
5104
  }
5118
- const doc = this.host.host.ownerDocument;
5119
- if (doc && this.visibilityListener) {
5120
- doc.removeEventListener("visibilitychange", this.visibilityListener);
5121
- this.visibilityListener = void 0;
5105
+ if (this.heartbeatTimer) {
5106
+ clearTimeout(this.heartbeatTimer);
5107
+ this.heartbeatTimer = void 0;
5122
5108
  }
5123
5109
  this.isHeartbeatInFlight = false;
5124
- if (this.pagehideListener) {
5125
- win.removeEventListener("pagehide", this.pagehideListener);
5126
- }
5127
5110
  const figure = this.renderer.getFigure();
5128
5111
  if (figure && this.figureClickListener) {
5129
5112
  figure.removeEventListener("click", this.figureClickListener);
@@ -5140,26 +5123,20 @@ var AsiystRuntime = class {
5140
5123
  this.events.removeAll();
5141
5124
  await this.analytics.destroy();
5142
5125
  }
5143
- startHeartbeatScheduler(doc) {
5144
- if (this.heartbeatTimer) {
5145
- clearInterval(this.heartbeatTimer);
5126
+ async sendHeartbeat() {
5127
+ if (this.destroyed || this.isHeartbeatInFlight || !this.registrationSucceeded || !this.installationId) {
5128
+ return false;
5146
5129
  }
5147
- this.heartbeatTimer = setInterval(() => {
5148
- if (!this.destroyed) {
5149
- void this.sendHeartbeat(true);
5130
+ const state = this.renderer.getRenderState() === "error" ? "degraded" : "ready";
5131
+ if (this.lastReportedState === state) return true;
5132
+ const elapsed = Date.now() - this.lastHeartbeatTime;
5133
+ if (this.lastHeartbeatTime && elapsed < this.nextHeartbeatAfterMs) {
5134
+ if (!this.heartbeatTimer) {
5135
+ this.heartbeatTimer = setTimeout(() => {
5136
+ this.heartbeatTimer = void 0;
5137
+ void this.sendHeartbeat();
5138
+ }, this.nextHeartbeatAfterMs - elapsed);
5150
5139
  }
5151
- }, HEARTBEAT_INTERVAL_MS);
5152
- if (doc && typeof doc.addEventListener === "function") {
5153
- this.visibilityListener = () => {
5154
- if (!this.destroyed && doc.visibilityState === "visible" && Date.now() - this.lastHeartbeatTime > 3e4) {
5155
- void this.sendHeartbeat(true);
5156
- }
5157
- };
5158
- doc.addEventListener("visibilitychange", this.visibilityListener);
5159
- }
5160
- }
5161
- async sendHeartbeat(_isPeriodic = false) {
5162
- if (this.destroyed || this.isHeartbeatInFlight) {
5163
5140
  return false;
5164
5141
  }
5165
5142
  this.isHeartbeatInFlight = true;
@@ -5168,17 +5145,23 @@ var AsiystRuntime = class {
5168
5145
  const environment = this.environment;
5169
5146
  const installationId = this.installationId;
5170
5147
  try {
5171
- if (!this.registrationSucceeded && installationId) {
5172
- await this.registerInstallation();
5173
- }
5174
5148
  const heartbeat = await this.cloud.heartbeat({
5175
- origin,
5176
- environment,
5177
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
5149
+ installationId: this.installationId,
5150
+ sdkVersion: SDK_VERSION,
5151
+ state,
5152
+ avatarReady: this.renderer.getRenderState() === "ready",
5153
+ textChatReady: true,
5154
+ environment: this.environment,
5155
+ ...state === "degraded" ? { failureReason: "asset_load_failed" } : {}
5178
5156
  });
5179
5157
  this.lastHeartbeatTime = Date.now();
5158
+ if (heartbeat.ok) this.lastReportedState = state;
5159
+ this.nextHeartbeatAfterMs = Math.max(
5160
+ HEARTBEAT_INTERVAL_MS,
5161
+ heartbeat.nextHeartbeatAfterMs ?? heartbeat.retryAfterMs ?? HEARTBEAT_INTERVAL_MS
5162
+ );
5180
5163
  this.connectionStatus = heartbeat.ok ? "connected" : "disconnected";
5181
- this.verificationStatus = heartbeat.verificationStatus === "verified" ? "connected" : heartbeat.verificationStatus ?? (heartbeat.ok ? "connected" : "not_detected");
5164
+ this.verificationStatus = heartbeat.ok ? "connected" : "not_detected";
5182
5165
  if (heartbeat.ok) {
5183
5166
  if (!previousConnection) {
5184
5167
  this.events.emit("asiyst:runtime:connected", {
@@ -5195,32 +5178,21 @@ var AsiystRuntime = class {
5195
5178
  sdkVersion: SDK_VERSION
5196
5179
  });
5197
5180
  }
5198
- if (heartbeat.verificationStatus === "connected" || heartbeat.verificationStatus === "verified") {
5199
- this.lifecycle.emit("sdk.verified", {
5200
- projectId: this.options.projectId,
5201
- origin,
5202
- environment,
5203
- installationId,
5204
- sdkVersion: SDK_VERSION
5205
- });
5206
- }
5207
- if (heartbeat.versionOutdated) {
5208
- this.lifecycle.emit("sdk.version_outdated", {
5209
- projectId: this.options.projectId,
5210
- origin,
5211
- environment,
5212
- installationId,
5213
- sdkVersion: SDK_VERSION
5214
- });
5215
- }
5181
+ this.lifecycle.emit("sdk.verified", {
5182
+ projectId: this.options.projectId,
5183
+ origin,
5184
+ environment,
5185
+ installationId,
5186
+ sdkVersion: SDK_VERSION
5187
+ });
5216
5188
  return true;
5217
5189
  } else {
5218
- const reason = heartbeat.verificationStatus ?? "unverified";
5190
+ this.lastReportedState = void 0;
5219
5191
  this.lifecycle.emit("sdk.verification_failed", {
5220
5192
  projectId: this.options.projectId,
5221
5193
  origin,
5222
5194
  environment,
5223
- status: reason,
5195
+ status: "heartbeat_failed",
5224
5196
  reason: "heartbeat_failed"
5225
5197
  });
5226
5198
  if (previousConnection) {
@@ -5234,12 +5206,15 @@ var AsiystRuntime = class {
5234
5206
  environment,
5235
5207
  installationId,
5236
5208
  reason: "heartbeat_failed",
5237
- status: reason
5209
+ status: "heartbeat_failed"
5238
5210
  });
5239
5211
  }
5212
+ this.scheduleHeartbeatRetry();
5240
5213
  return false;
5241
5214
  }
5242
5215
  } catch (error) {
5216
+ this.lastHeartbeatTime = Date.now();
5217
+ this.lastReportedState = void 0;
5243
5218
  this.connectionStatus = "offline";
5244
5219
  this.verificationStatus = "error";
5245
5220
  this.lifecycle.emit("sdk.verification_failed", {
@@ -5250,6 +5225,10 @@ var AsiystRuntime = class {
5250
5225
  reason: "heartbeat_failed",
5251
5226
  category: error instanceof AuthenticationError ? "authorization" : "network"
5252
5227
  });
5228
+ this.events.emit("asiyst:error", {
5229
+ code: "runtime_heartbeat_failed",
5230
+ message: error instanceof Error ? error.message : "Asiyst heartbeat failed."
5231
+ });
5253
5232
  if (previousConnection) {
5254
5233
  this.events.emit("asiyst:runtime:disconnected", {
5255
5234
  projectId: this.options.projectId,
@@ -5269,73 +5248,72 @@ var AsiystRuntime = class {
5269
5248
  this.isHeartbeatInFlight = false;
5270
5249
  }
5271
5250
  }
5251
+ scheduleHeartbeatRetry() {
5252
+ if (this.destroyed || this.heartbeatTimer) return;
5253
+ const remaining = Math.max(0, this.nextHeartbeatAfterMs - (Date.now() - this.lastHeartbeatTime));
5254
+ this.heartbeatTimer = setTimeout(() => {
5255
+ this.heartbeatTimer = void 0;
5256
+ void this.sendHeartbeat();
5257
+ }, remaining);
5258
+ }
5272
5259
  async registerInstallation() {
5273
5260
  const origin = window.location.origin;
5274
5261
  const environment = this.environment;
5275
5262
  const installationId = this.installationId;
5276
5263
  if (!installationId) {
5277
- if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
5278
- console.debug("[asiyst] SDK installation identity is unavailable; registration skipped.");
5279
- }
5280
- return;
5264
+ throw new InitializationError("Asiyst could not establish a secure installation identity.");
5281
5265
  }
5282
- let lastError;
5283
- for (let attempt = 0; attempt < 2; attempt += 1) {
5284
- try {
5285
- await this.cloud.registerInstallation({
5286
- project_id: this.options.projectId,
5287
- public_key: this.options.publicKey,
5288
- installation_id: installationId,
5289
- origin,
5290
- environment,
5291
- sdk_version: SDK_VERSION
5292
- });
5293
- this.registrationSucceeded = true;
5294
- return;
5295
- } catch (error) {
5296
- lastError = error;
5297
- if (attempt === 1) {
5298
- if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
5299
- console.debug("[asiyst] SDK installation registration failed.", error);
5300
- }
5301
- this.lifecycle.emit("sdk.verification_failed", {
5302
- projectId: this.options.projectId,
5303
- origin,
5304
- environment,
5305
- installationId,
5306
- reason: "registration_failed",
5307
- category: error instanceof AuthenticationError ? "authorization" : "network"
5308
- });
5309
- return;
5310
- }
5311
- await new Promise((resolve) => setTimeout(resolve, 250));
5266
+ try {
5267
+ const verified = await this.cloud.registerInstallation({
5268
+ projectId: this.options.projectId,
5269
+ publicKey: this.options.publicKey,
5270
+ installationId,
5271
+ origin,
5272
+ environment,
5273
+ sdkVersion: SDK_VERSION
5274
+ });
5275
+ if (!verified.data.installationId) {
5276
+ throw new InitializationError("Asiyst returned no verified installation identifier.");
5312
5277
  }
5278
+ this.installationId = verified.data.installationId;
5279
+ this.runtimeAuth?.setInstallationId(verified.data.installationId);
5280
+ this.registrationSucceeded = true;
5281
+ } catch (error) {
5282
+ if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
5283
+ console.debug("[asiyst] SDK installation verification failed.", error);
5284
+ }
5285
+ this.lifecycle.emit("sdk.verification_failed", {
5286
+ projectId: this.options.projectId,
5287
+ origin,
5288
+ environment,
5289
+ installationId,
5290
+ reason: "registration_failed",
5291
+ category: error instanceof AuthenticationError ? "authorization" : "network"
5292
+ });
5293
+ throw error;
5313
5294
  }
5314
- this.lifecycle.emit("sdk.verification_failed", {
5315
- projectId: this.options.projectId,
5316
- origin,
5317
- environment,
5318
- installationId,
5319
- reason: "registration_failed",
5320
- category: lastError instanceof AuthenticationError ? "authorization" : "network"
5321
- });
5322
5295
  }
5323
5296
  rescan() {
5324
5297
  withIsolation(() => {
5325
5298
  const doc = this.host.host.ownerDocument;
5326
5299
  this.map.replace(inspectDocument(doc));
5327
- void this.cloud.sendWebsiteMap(this.map.snapshot(doc));
5328
5300
  });
5329
5301
  }
5330
5302
  async handleUserMessage(text, doc) {
5331
5303
  this.events.emit("asiyst:conversation:message", { role: "user", text });
5332
5304
  this.avatar.think();
5333
5305
  try {
5334
- const reply = await this.cloud.sendConversationMessage(text, doc.location.href);
5335
- this.panel.append("assistant", reply.message.text);
5306
+ const reply = await this.cloud.sendConversationMessage(
5307
+ text,
5308
+ doc.location.href,
5309
+ this.config.get().maxMessageChars
5310
+ );
5311
+ this.panel.setConversationId(reply.conversationId);
5312
+ this.cloud.setConversationId(reply.conversationId);
5313
+ this.events.emit("asiyst:conversation:started", { conversationId: reply.conversationId });
5314
+ this.panel.append("assistant", reply.message.text, reply.citations);
5336
5315
  this.avatar.speak(reply.message.text);
5337
5316
  this.events.emit("asiyst:conversation:message", { role: "assistant", text: reply.message.text });
5338
- await this.startTaskFromText(text, doc);
5339
5317
  } catch (error) {
5340
5318
  const message = error instanceof Error ? error.message : "Asiyst Cloud is unavailable";
5341
5319
  this.panel.append("assistant", message);
@@ -5359,6 +5337,9 @@ var Asiyst = {
5359
5337
  if (runtime) {
5360
5338
  throw new InitializationError("Asiyst is already initialized");
5361
5339
  }
5340
+ if (typeof document === "undefined" || typeof window === "undefined") {
5341
+ throw new InitializationError("Asiyst SDK can only be initialized in a browser environment.");
5342
+ }
5362
5343
  const credentials = validateInitOptions(options);
5363
5344
  const doc = document;
5364
5345
  const win = window;