@asiyst/sdk 0.1.29 → 0.1.31

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.31";
101
101
  }
102
102
  }
103
103
  var SDK_VERSION = resolveSdkVersion();
@@ -116,7 +116,7 @@ var AVATAR_TARGET_GAP = 16;
116
116
  var WEBSITE_MAP_TEXT_LIMIT = 80;
117
117
  var CONFIG_CACHE_TTL_MS = 1e3 * 30;
118
118
  var CONFIG_REVALIDATION_INTERVAL_MS = 3e4;
119
- var HEARTBEAT_INTERVAL_MS = 45e3;
119
+ var HEARTBEAT_INTERVAL_MS = 3e5;
120
120
 
121
121
  // src/security/selectors.ts
122
122
  var DANGEROUS_SELECTOR = /javascript:|expression\(|@import|url\s*\(|behavior:|binding:|<script/i;
@@ -378,7 +378,8 @@ function parseAnimations(value) {
378
378
  clipName: typeof item.clipName === "string" ? sanitizeText(item.clipName, 64) : void 0,
379
379
  loopMode: typeof item.loopMode === "string" ? sanitizeText(item.loopMode, 32) : void 0,
380
380
  durationMs: typeof item.durationMs === "number" ? item.durationMs : void 0,
381
- assetUrl: typeof item.assetUrl === "string" ? item.assetUrl : null
381
+ assetUrl: typeof item.assetUrl === "string" ? item.assetUrl : null,
382
+ integrity: typeof item.integrity === "string" ? item.integrity : void 0
382
383
  });
383
384
  }
384
385
  }
@@ -405,6 +406,8 @@ function normalizeProjectConfig(raw) {
405
406
  ) || void 0;
406
407
  const assetUrl = typeof raw.assetUrl === "string" && raw.assetUrl ? raw.assetUrl : typeof rawAvatarRecord?.assetUrl === "string" && rawAvatarRecord.assetUrl ? rawAvatarRecord.assetUrl : typeof rawAvatarRecord?.modelUrl === "string" && rawAvatarRecord.modelUrl ? rawAvatarRecord.modelUrl : typeof rawConfigRecord?.assetUrl === "string" && rawConfigRecord.assetUrl ? rawConfigRecord.assetUrl : typeof rawManifestRecord?.assetUrl === "string" && rawManifestRecord.assetUrl ? rawManifestRecord.assetUrl : typeof rawManifestRecord?.modelUrl === "string" && rawManifestRecord.modelUrl ? rawManifestRecord.modelUrl : void 0;
407
408
  const thumbnailUrl = typeof raw.thumbnailUrl === "string" ? raw.thumbnailUrl : typeof rawAvatarRecord?.thumbnailUrl === "string" ? rawAvatarRecord.thumbnailUrl : typeof rawConfigRecord?.thumbnailUrl === "string" ? rawConfigRecord.thumbnailUrl : typeof rawManifestRecord?.thumbnailUrl === "string" ? rawManifestRecord.thumbnailUrl : rawAvatarRecord?.thumbnailUrl === null ? null : void 0;
409
+ const rawModelFormat = raw.modelFormat ?? rawAvatarRecord?.modelFormat ?? rawConfigRecord?.modelFormat ?? rawManifestRecord?.modelFormat;
410
+ const modelFormat = rawModelFormat === "fbx" || rawModelFormat === "glb" ? rawModelFormat : void 0;
408
411
  const publishedVersion = typeof raw.publishedVersion === "string" ? raw.publishedVersion : typeof rawAvatarRecord?.version === "string" ? rawAvatarRecord.version : typeof rawManifestRecord?.version === "string" ? rawManifestRecord.version : void 0;
409
412
  const animations = parseAnimations(
410
413
  raw.animations ?? rawAvatarRecord?.animations ?? rawConfigRecord?.animations
@@ -424,6 +427,8 @@ function normalizeProjectConfig(raw) {
424
427
  avatar,
425
428
  avatarId,
426
429
  assetUrl,
430
+ modelFormat,
431
+ assetIntegrity: typeof raw.assetIntegrity === "string" ? raw.assetIntegrity : typeof rawAvatarRecord?.assetIntegrity === "string" ? rawAvatarRecord.assetIntegrity : void 0,
427
432
  thumbnailUrl,
428
433
  publishedVersion,
429
434
  animations,
@@ -442,7 +447,8 @@ function normalizeProjectConfig(raw) {
442
447
  blockedRoutes: parseStringList(raw.blockedRoutes ?? raw.blocked_routes),
443
448
  rules: parseRules(raw.rules ?? raw.avatarRules),
444
449
  dataSources: parseDataSources(raw.dataSources ?? raw.enabledDataSources),
445
- elementSelectors: parseElementSelectors(raw.elementSelectors)
450
+ elementSelectors: parseElementSelectors(raw.elementSelectors),
451
+ maxMessageChars: asNumber(raw.maxMessageChars, 4e3, 1, 4e3)
446
452
  };
447
453
  }
448
454
  function validateInitOptions(options) {
@@ -526,7 +532,7 @@ var HttpTransport = class {
526
532
  return this.options.avatarId;
527
533
  }
528
534
  async request(req) {
529
- const url = `${this.options.apiBaseUrl.replace(/\/$/, "")}${req.path}`;
535
+ const url = /^https?:\/\//i.test(req.path) ? req.path : `${this.options.apiBaseUrl.replace(/\/$/, "")}${req.path}`;
530
536
  const requestId = req.requestId || generateRequestId();
531
537
  const timeoutMs = req.timeoutMs ?? this.options.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS;
532
538
  const isSafeOrIdempotent = req.method === "GET" || Boolean(req.idempotent);
@@ -554,36 +560,30 @@ var HttpTransport = class {
554
560
  }
555
561
  try {
556
562
  let response;
557
- try {
558
- response = await fetch(url, {
559
- method: req.method,
560
- headers: {
561
- Accept: "application/json",
562
- "Content-Type": "application/json",
563
- "X-Asiyst-Project-Id": this.options.projectId,
564
- "X-Asiyst-Public-Key": this.options.publicKey,
565
- ...this.options.avatarId ? { "X-Asiyst-Avatar-Id": this.options.avatarId } : {},
566
- "X-Asiyst-SDK-Version": SDK_VERSION,
567
- "X-Asiyst-Request-Id": requestId,
568
- ...req.sessionId ? { "X-Asiyst-Session-Id": req.sessionId } : {},
569
- ...req.conversationId ? { "X-Asiyst-Conversation-Id": req.conversationId } : {},
570
- ...req.authorizationToken ? { Authorization: `Bearer ${req.authorizationToken}` } : {}
571
- },
572
- body: req.body === void 0 ? void 0 : JSON.stringify(req.body),
573
- signal: controller.signal
574
- });
575
- } finally {
576
- clearTimeout(timeoutId);
577
- if (req.signal) {
578
- req.signal.removeEventListener("abort", onExternalAbort);
579
- }
580
- }
563
+ response = await fetch(url, {
564
+ method: req.method,
565
+ headers: req.headers ?? {
566
+ Accept: "application/json",
567
+ "Content-Type": "application/json",
568
+ "X-Asiyst-Project-Id": this.options.projectId,
569
+ "X-Asiyst-Public-Key": this.options.publicKey,
570
+ ...this.options.avatarId ? { "X-Asiyst-Avatar-Id": this.options.avatarId } : {},
571
+ "X-Asiyst-SDK-Version": SDK_VERSION,
572
+ "X-Asiyst-Request-Id": requestId,
573
+ ...req.sessionId ? { "X-Asiyst-Session-Id": req.sessionId } : {},
574
+ ...req.conversationId ? { "X-Asiyst-Conversation-Id": req.conversationId } : {},
575
+ ...req.authorizationToken ? { Authorization: `Bearer ${req.authorizationToken}` } : {}
576
+ },
577
+ body: req.body === void 0 ? void 0 : JSON.stringify(req.body),
578
+ signal: controller.signal
579
+ });
581
580
  if (isSafeOrIdempotent && attempt < maxRetries && [502, 503, 504].includes(response.status)) {
582
581
  continue;
583
582
  }
584
583
  if (response.status === 429 && isSafeOrIdempotent && attempt < maxRetries) {
585
584
  const retryAfterHeader = response.headers.get("retry-after");
586
585
  const retryAfterMs = retryAfterHeader ? Math.min(Number(retryAfterHeader) * 1e3 || 200, 1e3) : 100;
586
+ clearTimeout(timeoutId);
587
587
  await new Promise((resolve) => setTimeout(resolve, retryAfterMs));
588
588
  continue;
589
589
  }
@@ -593,33 +593,87 @@ var HttpTransport = class {
593
593
  try {
594
594
  data = await response.json();
595
595
  } catch {
596
+ if (timedOut) {
597
+ throw new NetworkError("Asiyst Cloud request timed out");
598
+ }
599
+ if (req.signal?.aborted) {
600
+ throw new NetworkError("Asiyst Cloud request was aborted");
601
+ }
596
602
  data = null;
597
603
  }
598
604
  }
599
605
  if (!response.ok) {
600
- return { ok: false, status: response.status, data };
606
+ return { ok: false, status: response.status, data, headers: response.headers };
601
607
  }
602
- return { ok: true, status: response.status, data };
608
+ return { ok: true, status: response.status, data, headers: response.headers };
603
609
  } catch (err) {
604
- clearTimeout(timeoutId);
605
- if (req.signal) {
606
- req.signal.removeEventListener("abort", onExternalAbort);
607
- }
608
610
  if (timedOut) {
609
611
  throw new NetworkError("Asiyst Cloud request timed out");
610
612
  }
613
+ if (req.signal?.aborted) {
614
+ throw new NetworkError("Asiyst Cloud request was aborted");
615
+ }
611
616
  lastError = err;
612
617
  if (isSafeOrIdempotent && attempt < maxRetries) {
613
618
  continue;
614
619
  }
615
620
  throw new NetworkError("Asiyst Cloud is unreachable");
621
+ } finally {
622
+ clearTimeout(timeoutId);
623
+ if (req.signal) {
624
+ req.signal.removeEventListener("abort", onExternalAbort);
625
+ }
616
626
  }
617
627
  }
618
628
  throw lastError instanceof Error ? lastError : new NetworkError("Asiyst Cloud is unreachable");
619
629
  }
620
630
  };
621
631
 
632
+ // ../api-contract.ts
633
+ var API_V1_BASE_PATH = "/api/v1";
634
+ var API_ROUTES = {
635
+ runtimeAvatar: "/runtime/avatar",
636
+ runtimeToken: "/sdk/runtime/token",
637
+ installationRegister: "/sdk/installations/register",
638
+ runtimeHeartbeat: "/sdk/heartbeat",
639
+ chat: "/conversations/messages",
640
+ projectApiKeyVerify: (projectId) => `/projects/${encodeURIComponent(projectId)}/api-key/verify`,
641
+ sdkInstallationVerify: "/sdk/installations/verify"
642
+ };
643
+ var API_LIMITS = {
644
+ configStaleIfErrorMs: 0,
645
+ maxMessageChars: 12e3,
646
+ pageUrlMaxChars: 2048};
647
+ function apiV1Path(route) {
648
+ return `${API_V1_BASE_PATH}${route.startsWith("/") ? route : `/${route}`}`;
649
+ }
650
+ function contractApiBaseUrl(configuredApiBaseUrl) {
651
+ const parsed = new URL(configuredApiBaseUrl);
652
+ if (parsed.pathname.replace(/\/+$/, "").endsWith("/functions/v1/api")) {
653
+ return "https://asiyst.com";
654
+ }
655
+ return parsed.origin;
656
+ }
657
+ function contractApiUrl(configuredApiBaseUrl, route) {
658
+ return `${contractApiBaseUrl(configuredApiBaseUrl).replace(/\/+$/, "")}${apiV1Path(route)}`;
659
+ }
660
+
622
661
  // src/communication/CloudClient.ts
662
+ function newRequestId() {
663
+ const cryptoApi = globalThis.crypto;
664
+ if (typeof cryptoApi?.randomUUID === "function") return cryptoApi.randomUUID();
665
+ if (typeof cryptoApi?.getRandomValues === "function") {
666
+ const bytes = cryptoApi.getRandomValues(new Uint8Array(16));
667
+ bytes[6] = (bytes[6] ?? 0) & 15 | 64;
668
+ bytes[8] = (bytes[8] ?? 0) & 63 | 128;
669
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
670
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
671
+ }
672
+ throw new ConfigurationError("Secure request identifiers are unavailable in this browser.");
673
+ }
674
+ function isUuid(value) {
675
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
676
+ }
623
677
  var CloudClient = class {
624
678
  constructor(transport, projectId, publicKey = "", runtimeAuth, sessionId, avatarId) {
625
679
  this.transport = transport;
@@ -627,6 +681,7 @@ var CloudClient = class {
627
681
  this.publicKey = publicKey;
628
682
  this.runtimeAuth = runtimeAuth;
629
683
  this.avatarId = avatarId;
684
+ this.configMetadata = {};
630
685
  this.inFlightConversations = /* @__PURE__ */ new Map();
631
686
  this.sessionId = sessionId;
632
687
  if (!this.avatarId && typeof transport.getAvatarId === "function") {
@@ -657,243 +712,152 @@ var CloudClient = class {
657
712
  }
658
713
  return DEFAULT_API_BASE_URL;
659
714
  }
660
- async getAuthToken(capability) {
715
+ async getAuthToken() {
661
716
  if (!this.runtimeAuth) return void 0;
662
717
  if (this.tokenRefreshPromise) return this.tokenRefreshPromise;
663
- if (!this.inFlightToken) {
664
- this.inFlightToken = this.runtimeAuth.getToken(capability).then((token) => {
665
- this.activeToken = token;
666
- return token;
667
- }).finally(() => {
668
- this.inFlightToken = void 0;
669
- });
670
- }
671
- return this.inFlightToken;
718
+ this.tokenRefreshPromise = this.runtimeAuth.getToken().then((token) => {
719
+ this.activeToken = token;
720
+ return token;
721
+ }).finally(() => {
722
+ this.tokenRefreshPromise = void 0;
723
+ });
724
+ return this.tokenRefreshPromise;
672
725
  }
673
- async fetchConfig() {
674
- const avatarParam = this.avatarId ? `?avatarId=${encodeURIComponent(this.avatarId)}` : "";
675
- const avatarAndKeyParams = `?projectId=${encodeURIComponent(this.projectId)}&publicKey=${encodeURIComponent(this.publicKey)}${this.avatarId ? `&avatarId=${encodeURIComponent(this.avatarId)}` : ""}`;
676
- const baseUrl = this.getApiBaseUrl();
677
- const resolveAssetUrls = (raw) => {
678
- let canonicalBase = "https://asiyst.com";
679
- try {
680
- if (baseUrl) {
681
- const u = new URL(baseUrl);
682
- canonicalBase = u.origin;
683
- }
684
- } catch {
685
- canonicalBase = "https://asiyst.com";
726
+ getConfigMetadata() {
727
+ return this.configMetadata;
728
+ }
729
+ async fetchConfig(etag, cachedConfig) {
730
+ const response = await this.transport.request({
731
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.runtimeAvatar),
732
+ method: "GET",
733
+ idempotent: true,
734
+ retries: 2,
735
+ headers: {
736
+ Accept: "application/json",
737
+ "X-Asiyst-Public-Key": this.publicKey,
738
+ "X-Asiyst-Project-Id": this.projectId,
739
+ ...this.avatarId ? { "X-Asiyst-Avatar-Id": this.avatarId } : {},
740
+ ...etag ? { "If-None-Match": etag } : {}
686
741
  }
687
- const toAbsolute = (url) => {
688
- if (typeof url === "string" && url.startsWith("/")) {
689
- return new URL(url, canonicalBase).href;
690
- }
691
- return url;
742
+ });
743
+ if (response.status === 304 && cachedConfig) {
744
+ this.configMetadata = {
745
+ etag: response.headers?.get("etag") ?? etag,
746
+ maxAgeMs: 0,
747
+ staleIfErrorMs: 0
692
748
  };
693
- if (raw.avatar && typeof raw.avatar === "object" && !Array.isArray(raw.avatar)) {
694
- const av = { ...raw.avatar };
695
- av.assetUrl = toAbsolute(av.assetUrl);
696
- av.thumbnailUrl = toAbsolute(av.thumbnailUrl);
697
- av.modelUrl = toAbsolute(av.modelUrl);
698
- av.manifestUrl = toAbsolute(av.manifestUrl);
699
- if (Array.isArray(av.animations)) {
700
- av.animations = av.animations.map((item) => {
701
- if (item && typeof item === "object") {
702
- const animObj = item;
703
- return { ...animObj, assetUrl: toAbsolute(animObj.assetUrl) };
704
- }
705
- return item;
706
- });
707
- }
708
- raw.avatar = av;
709
- }
710
- if (raw.config && typeof raw.config === "object" && !Array.isArray(raw.config)) {
711
- const cfg = { ...raw.config };
712
- cfg.assetUrl = toAbsolute(cfg.assetUrl);
713
- cfg.thumbnailUrl = toAbsolute(cfg.thumbnailUrl);
714
- cfg.manifestUrl = toAbsolute(cfg.manifestUrl);
715
- raw.config = cfg;
716
- }
717
- if (raw.manifest && typeof raw.manifest === "object" && !Array.isArray(raw.manifest)) {
718
- const mf = { ...raw.manifest };
719
- mf.assetUrl = toAbsolute(mf.assetUrl);
720
- mf.thumbnailUrl = toAbsolute(mf.thumbnailUrl);
721
- mf.modelUrl = toAbsolute(mf.modelUrl);
722
- raw.manifest = mf;
723
- }
724
- raw.assetUrl = toAbsolute(raw.assetUrl);
725
- raw.thumbnailUrl = toAbsolute(raw.thumbnailUrl);
726
- raw.manifestUrl = toAbsolute(raw.manifestUrl);
727
- if (raw.branding && typeof raw.branding === "object" && !Array.isArray(raw.branding)) {
728
- const br = { ...raw.branding };
729
- br.siteLogoUrl = toAbsolute(br.siteLogoUrl);
730
- raw.branding = br;
731
- }
732
- return raw;
733
- };
734
- let lastError;
735
- try {
736
- const response = await this.runtimeRequest({
737
- path: `/projects/${encodeURIComponent(this.projectId)}/avatar${avatarParam}`,
738
- method: "GET",
739
- idempotent: true
740
- });
741
- if (response.ok && response.data) {
742
- const fullData = response.data && typeof response.data === "object" && !Array.isArray(response.data) ? {
743
- ...response.data,
744
- ...response.data.config && typeof response.data.config === "object" ? response.data.config : {}
745
- } : {};
746
- return normalizeProjectConfig(resolveAssetUrls(fullData));
747
- }
748
- if (response.status === 404) {
749
- lastError = new ConfigurationError(`Project ${this.projectId} or avatar configuration not found`);
750
- }
751
- } catch (err) {
752
- if (err instanceof Error) lastError = err;
749
+ return cachedConfig;
753
750
  }
754
- try {
755
- const runtimeResponse = await this.runtimeRequest({
756
- path: `/api/v1/runtime/avatar${avatarAndKeyParams}`,
757
- method: "GET",
758
- idempotent: true
759
- });
760
- if (runtimeResponse.ok && runtimeResponse.data) {
761
- return normalizeProjectConfig(resolveAssetUrls(runtimeResponse.data));
762
- }
763
- if (runtimeResponse.status === 404) {
764
- lastError = new ConfigurationError(`Avatar ${this.avatarId ?? "active"} not found for project ${this.projectId}`);
765
- }
766
- } catch (err) {
767
- if (err instanceof Error) lastError = err;
768
- }
769
- try {
770
- const webBase = baseUrl.includes("localhost") || baseUrl.includes("127.0.0.1") ? baseUrl.replace(/\/functions\/v1.*$/, "").replace(/\/api\/v1.*$/, "") : "https://asiyst.com";
771
- const fullUrl = `${webBase.replace(/\/$/, "")}/api/v1/runtime/avatar${avatarAndKeyParams}`;
772
- const res = await fetch(fullUrl, {
773
- headers: {
774
- Accept: "application/json",
775
- "x-asiyst-public-key": this.publicKey
776
- }
777
- });
778
- if (res.ok) {
779
- const body = await res.json();
780
- if (body && typeof body === "object") {
781
- return normalizeProjectConfig(resolveAssetUrls(body));
782
- }
783
- } else {
784
- const errorBody = await res.json().catch(() => ({}));
785
- const errObj = errorBody?.error ?? errorBody;
786
- const code = String(errObj?.code ?? "");
787
- const message = String(errObj?.message ?? `HTTP ${res.status}`);
788
- if (res.status === 404) {
789
- throw new ConfigurationError(code === "AVATAR_NOT_FOUND" ? `Requested avatar not found for project ${this.projectId}` : `Project ${this.projectId} not found`);
790
- } else if (res.status === 401 || res.status === 403) {
791
- throw new AuthenticationError("Asiyst credentials unauthorized for this avatar configuration");
792
- } else if (res.status >= 500) {
793
- throw new NetworkError(`Asiyst Cloud avatar service error (${res.status}): ${message}`);
794
- }
795
- }
796
- } catch (err) {
797
- if (err instanceof ConfigurationError || err instanceof AuthenticationError || err instanceof NetworkError) {
798
- throw err;
751
+ if (!response.ok || !response.data) {
752
+ const body = response.data;
753
+ const code = body?.error?.code ?? `HTTP_${response.status}`;
754
+ if (response.status === 401 || response.status === 403) {
755
+ throw new AuthenticationError(body?.error?.message ?? `Asiyst runtime avatar configuration was rejected (${code}).`);
799
756
  }
800
- if (err instanceof Error) lastError = err;
801
- }
802
- if (lastError) {
803
- throw lastError;
804
- }
805
- throw new ConfigurationError(`Failed to resolve avatar configuration for project ${this.projectId}`);
757
+ throw new NetworkError(body?.error?.message ?? `Asiyst runtime avatar configuration is unavailable (${code}).`);
758
+ }
759
+ const data = response.data;
760
+ if (data.success !== true || data.projectId !== this.projectId || typeof data.avatarId !== "string" || !data.config || typeof data.config !== "object" || Array.isArray(data.config)) {
761
+ throw new ConfigurationError("Asiyst returned an invalid runtime configuration response.");
762
+ }
763
+ const rawConfig = data.config;
764
+ const rawAvatar = data.avatar && typeof data.avatar === "object" ? data.avatar : {};
765
+ const manifest = data.manifest && typeof data.manifest === "object" ? data.manifest : {};
766
+ const modelFormat = [data.format, data.modelFormat, rawConfig.modelFormat, rawAvatar.modelFormat].find((format) => typeof format === "string");
767
+ if (modelFormat && modelFormat !== "fbx" && modelFormat !== "glb") {
768
+ throw new ConfigurationError(`Asiyst returned an unsupported avatar format: ${modelFormat}.`);
769
+ }
770
+ const assetUrl = typeof rawConfig.assetUrl === "string" ? rawConfig.assetUrl : typeof rawAvatar.assetUrl === "string" ? rawAvatar.assetUrl : typeof rawAvatar.modelUrl === "string" ? rawAvatar.modelUrl : typeof manifest.assetUrl === "string" ? manifest.assetUrl : void 0;
771
+ const animations = Array.isArray(rawConfig.animations) ? rawConfig.animations : Array.isArray(data.animations) ? data.animations : Array.isArray(rawAvatar.animations) ? rawAvatar.animations : [];
772
+ const revision = typeof data.configRevision === "string" ? data.configRevision : typeof data.publishedVersionId === "string" ? data.publishedVersionId : "0";
773
+ const version = Number.parseInt(revision, 10);
774
+ const config = normalizeProjectConfig({
775
+ ...rawConfig,
776
+ avatarId: data.avatarId,
777
+ avatarName: typeof rawAvatar.name === "string" ? rawAvatar.name : rawConfig.avatarName,
778
+ assetUrl,
779
+ modelFormat,
780
+ publishedVersion: typeof data.publishedVersionId === "string" ? data.publishedVersionId : revision,
781
+ version: Number.isFinite(version) ? version : 0,
782
+ animations,
783
+ theme: rawConfig.theme ?? rawAvatar.theme,
784
+ personality: rawConfig.personality,
785
+ behavior: rawConfig.behavior ?? rawAvatar.behavior,
786
+ maxMessageChars: API_LIMITS.maxMessageChars
787
+ });
788
+ this.configMetadata = {
789
+ etag: response.headers?.get("etag") ?? void 0,
790
+ maxAgeMs: 0,
791
+ staleIfErrorMs: 0
792
+ };
793
+ return config;
806
794
  }
807
795
  async heartbeat(metadata) {
808
- let response = await this.runtimeRequest({
809
- path: "/sdk/heartbeat",
796
+ const response = await this.runtimeRequest({
797
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.runtimeHeartbeat),
810
798
  method: "POST",
811
- idempotent: true,
799
+ canonical: true,
812
800
  body: {
813
- project_id: this.projectId,
814
- public_key: this.publicKey,
815
- sdk_version: SDK_VERSION,
816
- origin: metadata.origin,
817
- environment: metadata.environment,
818
- timestamp: metadata.timestamp
801
+ projectId: this.projectId,
802
+ publicKey: this.publicKey,
803
+ sdkVersion: metadata.sdkVersion,
804
+ environment: metadata.environment
819
805
  }
820
806
  }, "assistant:heartbeat");
821
- if (response.status === 404) {
822
- response = await this.runtimeRequest({
823
- path: "/api/v1/sdk/heartbeat",
824
- method: "POST",
825
- idempotent: true,
826
- body: {
827
- project_id: this.projectId,
828
- public_key: this.publicKey,
829
- sdk_version: SDK_VERSION,
830
- origin: metadata.origin,
831
- environment: metadata.environment,
832
- timestamp: metadata.timestamp
833
- }
834
- }, "assistant:heartbeat");
835
- }
836
- const body = response.data && typeof response.data === "object" && !Array.isArray(response.data) ? response.data : void 0;
837
- const rawStatus = body?.status ?? body?.connectionStatus ?? body?.verificationStatus ?? (body?.verified === true ? "verified" : void 0);
838
- const verificationStatus = rawStatus === "connected" || rawStatus === "verified" || rawStatus === "inactive" || rawStatus === "not_detected" || rawStatus === "error" ? rawStatus : void 0;
839
- const versionOutdated = body?.versionOutdated === true || body?.sdkVersionOutdated === true || rawStatus === "outdated";
807
+ const body = response.data;
808
+ const validResponse = body?.success === true && body.data?.connected === true && body.data.projectId === this.projectId && typeof body.data.versionOutdated === "boolean";
840
809
  return {
841
- ok: response.ok && (verificationStatus === void 0 || verificationStatus === "connected" || verificationStatus === "verified"),
842
- status: response.status,
843
- verificationStatus,
844
- versionOutdated
810
+ ok: response.ok && response.status === 202 && validResponse,
811
+ status: response.status
845
812
  };
846
813
  }
847
814
  async registerInstallation(registration) {
848
- let response = await this.transport.request({
849
- path: "/sdk/installations/register",
815
+ const response = await this.transport.request({
816
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.installationRegister),
850
817
  method: "POST",
851
- body: registration,
852
- idempotent: true,
853
- sessionId: this.sessionId
818
+ headers: {
819
+ Accept: "application/json",
820
+ "Content-Type": "application/json",
821
+ "X-Asiyst-SDK-Version": registration.sdkVersion
822
+ },
823
+ body: {
824
+ projectId: registration.projectId,
825
+ publicKey: registration.publicKey,
826
+ installationId: registration.installationId,
827
+ origin: registration.origin,
828
+ environment: registration.environment,
829
+ sdkVersion: registration.sdkVersion
830
+ }
854
831
  });
855
- if (response.status === 404) {
856
- response = await this.transport.request({
857
- path: "/api/v1/sdk/installations/register",
858
- method: "POST",
859
- body: registration,
860
- idempotent: true,
861
- sessionId: this.sessionId
862
- });
863
- }
864
- if (!response.ok) {
865
- throw new NetworkError(`SDK installation registration failed (${response.status}).`);
832
+ const body = response.data;
833
+ if (!response.ok || body?.success !== true || body.data?.registered !== true || typeof body.data.installationId !== "string" || body.data.projectId !== registration.projectId || body.data.status === "revoked") {
834
+ const error = response.data && typeof response.data === "object" ? response.data.error : void 0;
835
+ if (response.status === 403 || body?.data?.status === "revoked") {
836
+ throw new AuthenticationError(error?.message ?? `SDK installation is not authorized (${error?.code ?? response.status}).`);
837
+ }
838
+ throw new NetworkError(error?.message ?? `SDK installation registration failed (${response.status}).`);
866
839
  }
867
- return response.data ?? {};
840
+ return body;
868
841
  }
869
842
  async requestTask(userText, pageUrl) {
870
- const response = await this.runtimeRequest({
871
- path: "/tasks",
872
- method: "POST",
873
- body: {
874
- projectId: this.projectId,
875
- text: userText,
876
- pageUrl
877
- }
878
- }, "assistant:conversation");
879
- if (!response.ok || !response.data?.task?.id || !Array.isArray(response.data.task.steps)) {
880
- throw new NetworkError("Task planning is unavailable");
881
- }
882
- return response.data.task;
843
+ throw new ConfigurationError("Cloud task planning is not defined by the approved SDK API contract.");
883
844
  }
884
845
  async fetchWorkflow(workflowId) {
885
- const response = await this.runtimeRequest({
886
- path: `/workflows/${encodeURIComponent(workflowId)}`,
887
- method: "GET",
888
- idempotent: true
889
- }, "assistant:conversation");
890
- if (!response.ok || !response.data?.workflow?.id || !Array.isArray(response.data.workflow.steps)) {
891
- throw new NetworkError("Workflow is unavailable");
892
- }
893
- return response.data.workflow;
846
+ throw new ConfigurationError("Cloud workflows are not defined by the approved SDK API contract.");
894
847
  }
895
- async sendConversationMessage(text, pageUrl) {
848
+ async sendConversationMessage(text, pageUrl, maxMessageChars = API_LIMITS.maxMessageChars) {
896
849
  const trimmed = text.trim();
850
+ if (!trimmed) throw new ConfigurationError("Message cannot be empty.");
851
+ if (trimmed.length > maxMessageChars) {
852
+ throw new ConfigurationError(`Message exceeds the ${maxMessageChars}-character limit.`);
853
+ }
854
+ if (pageUrl.length > API_LIMITS.pageUrlMaxChars) {
855
+ throw new ConfigurationError("Page URL exceeds the supported length.");
856
+ }
857
+ const sessionId = this.sessionId ?? newRequestId();
858
+ if (sessionId.length < 16 || sessionId.length > 128 || !/^[A-Za-z0-9_-]+$/.test(sessionId)) {
859
+ throw new ConfigurationError("Visitor session ID must be an opaque 16-128 character identifier.");
860
+ }
897
861
  const dedupeKey2 = `${this.conversationId ?? ""}:${trimmed}:${pageUrl}`;
898
862
  const existing = this.inFlightConversations.get(dedupeKey2);
899
863
  if (existing) {
@@ -901,19 +865,87 @@ 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
+ const installationErrorCodes = {
918
+ INSTALLATION_NOT_FOUND: "Asiyst installation not found for this domain. Re-run `asiyst connect` and verify your project domain.",
919
+ INSTALLATION_INACTIVE: "Asiyst installation is inactive. Check your project status in the Asiyst dashboard.",
920
+ INSTALLATION_REVOKED: "Asiyst installation has been revoked. Re-run `asiyst connect` to register a new installation.",
921
+ INSTALLATION_PROJECT_MISMATCH: "Asiyst installation does not match the configured project.",
922
+ INSTALLATION_DOMAIN_MISMATCH: "Asiyst installation domain does not match the current website domain.",
923
+ RUNTIME_TOKEN_INVALID: "Asiyst runtime authorization token is invalid. The SDK will attempt to re-authorize.",
924
+ RUNTIME_TOKEN_EXPIRED: "Asiyst runtime authorization token has expired. The SDK will re-authorize."
925
+ };
926
+ const knownMessage = typeof code === "string" ? installationErrorCodes[code] : void 0;
927
+ if (knownMessage) {
928
+ throw new AuthenticationError(knownMessage);
929
+ }
930
+ throw new AuthenticationError(
931
+ typeof errorBody?.message === "string" ? `Asiyst runtime authorization rejected: ${errorBody.message}` : "Asiyst runtime authorization was rejected."
932
+ );
933
+ }
934
+ if (response.status === 429) {
935
+ throw new NetworkError("The assistant is rate limited. Wait before sending another message.");
936
+ }
937
+ if (response.status === 409) {
938
+ throw new NetworkError(`The conversation request conflicted (${code}); it was not retried.`);
915
939
  }
916
- return response.data;
940
+ if (response.status === 504 || code === "AI_PROVIDER_TIMEOUT") {
941
+ throw new NetworkError("The assistant timed out. The request was not retried to avoid duplicate work.");
942
+ }
943
+ if (code === "assistant_unavailable") {
944
+ throw new NetworkError("The assistant is temporarily unavailable.");
945
+ }
946
+ throw new NetworkError(
947
+ typeof errorBody?.message === "string" ? errorBody.message : typeof response.data?.message === "string" ? response.data.message : "Conversation service is unavailable."
948
+ );
917
949
  } finally {
918
950
  this.inFlightConversations.delete(dedupeKey2);
919
951
  }
@@ -922,63 +954,16 @@ var CloudClient = class {
922
954
  return conversationPromise;
923
955
  }
924
956
  async sendWebsiteMap(snapshot) {
925
- await this.safePost("/website-maps", snapshot);
957
+ throw new ConfigurationError("Website-map upload is not defined by the approved SDK API contract.");
926
958
  }
927
959
  async sendAnalytics(events) {
928
- await this.safePost("/analytics", { events });
960
+ throw new ConfigurationError("Analytics upload is not defined by the approved SDK API contract.");
929
961
  }
930
962
  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
- }
963
+ throw new ConfigurationError("Telemetry upload is not defined by the approved SDK API contract.");
970
964
  }
971
965
  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
- }
966
+ throw new ConfigurationError("Cloud task updates are not defined by the approved SDK API contract.");
982
967
  }
983
968
  async runtimeRequest(request, capability = "assistant:config") {
984
969
  const fullRequest = {
@@ -987,14 +972,32 @@ var CloudClient = class {
987
972
  conversationId: request.conversationId ?? this.conversationId
988
973
  };
989
974
  if (!this.runtimeAuth) {
975
+ if (capability === "assistant:conversation" || capability === "assistant:heartbeat") {
976
+ throw new AuthenticationError("AI request authorization failed because no runtime token is available.");
977
+ }
990
978
  return this.transport.request(fullRequest);
991
979
  }
992
- let token = await this.getAuthToken(capability);
993
- let response = await this.transport.request({ ...fullRequest, authorizationToken: token });
980
+ let token = await this.getAuthToken();
981
+ const withToken = (value) => {
982
+ const headers = new Headers({
983
+ Accept: "application/json",
984
+ "Content-Type": "application/json"
985
+ });
986
+ if (fullRequest.headers) {
987
+ new Headers(fullRequest.headers).forEach((headerValue, key) => headers.set(key, headerValue));
988
+ }
989
+ if (value) headers.set("Authorization", `Bearer ${value}`);
990
+ return this.transport.request({
991
+ ...fullRequest,
992
+ headers,
993
+ canonical: true
994
+ });
995
+ };
996
+ let response = await withToken(token);
994
997
  if (response.status === 401) {
995
998
  if (!this.tokenRefreshPromise) {
996
999
  this.runtimeAuth.invalidate();
997
- this.tokenRefreshPromise = this.runtimeAuth.getToken(capability).then((newToken) => {
1000
+ this.tokenRefreshPromise = this.runtimeAuth.getToken().then((newToken) => {
998
1001
  this.activeToken = newToken;
999
1002
  return newToken;
1000
1003
  }).finally(() => {
@@ -1004,7 +1007,7 @@ var CloudClient = class {
1004
1007
  });
1005
1008
  }
1006
1009
  token = await this.tokenRefreshPromise ?? this.activeToken;
1007
- response = await this.transport.request({ ...fullRequest, authorizationToken: token });
1010
+ response = await withToken(token);
1008
1011
  }
1009
1012
  return response;
1010
1013
  }
@@ -1071,7 +1074,8 @@ var ConfigCache = class {
1071
1074
  if (parsed.schemaVersion !== CONFIG_SCHEMA_VERSION || parsed.projectId !== projectId) {
1072
1075
  return null;
1073
1076
  }
1074
- if (!ignoreTtl && Date.now() - parsed.fetchedAt > CONFIG_CACHE_TTL_MS) {
1077
+ const maxAgeMs = parsed.maxAgeMs ?? CONFIG_CACHE_TTL_MS;
1078
+ if (!ignoreTtl && Date.now() - parsed.fetchedAt > maxAgeMs) {
1075
1079
  return null;
1076
1080
  }
1077
1081
  return normalizeProjectConfig(parsed.config);
@@ -1101,6 +1105,8 @@ var ConfigCache = class {
1101
1105
  fetchedAt: Date.now(),
1102
1106
  etag: meta?.etag,
1103
1107
  revision: meta?.revision ?? config.version,
1108
+ maxAgeMs: meta?.maxAgeMs,
1109
+ staleIfErrorMs: meta?.staleIfErrorMs,
1104
1110
  config
1105
1111
  };
1106
1112
  this.storage.write("config", JSON.stringify(envelope));
@@ -1142,19 +1148,26 @@ var ConfigManager = class {
1142
1148
  async executeRefresh(_options) {
1143
1149
  const prev = this.current;
1144
1150
  try {
1145
- const remote = await this.cloud.fetchConfig();
1146
- const normalized = normalizeProjectConfig(remote);
1151
+ const cached = this.cache.getEnvelope(this.options.projectId);
1152
+ const normalized = normalizeProjectConfig(await this.cloud.fetchConfig(cached?.etag, cached?.config));
1153
+ const receivedMetadata = this.cloud.getConfigMetadata?.() ?? {};
1154
+ const metadata = {
1155
+ ...receivedMetadata,
1156
+ maxAgeMs: receivedMetadata.maxAgeMs ?? cached?.maxAgeMs,
1157
+ staleIfErrorMs: receivedMetadata.staleIfErrorMs ?? cached?.staleIfErrorMs
1158
+ };
1147
1159
  this.current = normalized;
1148
- this.cache.write(this.options.projectId, normalized);
1160
+ this.cache.write(this.options.projectId, normalized, metadata);
1149
1161
  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
1162
  if (hasChanged && this.onConfigUpdated) {
1151
1163
  this.onConfigUpdated(normalized, prev);
1152
1164
  }
1153
1165
  return this.current;
1154
1166
  } catch (error) {
1155
- const lastKnownGood = this.cache.read(this.options.projectId, true);
1156
- if (lastKnownGood) {
1157
- this.current = lastKnownGood;
1167
+ const cached = this.cache.getEnvelope(this.options.projectId);
1168
+ const staleIfErrorMs = cached?.staleIfErrorMs ?? API_LIMITS.configStaleIfErrorMs;
1169
+ if (cached && staleIfErrorMs > 0 && Date.now() - cached.fetchedAt <= staleIfErrorMs) {
1170
+ this.current = normalizeProjectConfig(cached.config);
1158
1171
  }
1159
1172
  this.events.emit("asiyst:error", {
1160
1173
  code: "config_refresh_failed",
@@ -1831,7 +1844,7 @@ var CHUNK_TYPE_JSON = 1313821514;
1831
1844
  var CHUNK_TYPE_BIN = 5130562;
1832
1845
  var AssetLoader = class {
1833
1846
  constructor() {
1834
- this.inFlightController = null;
1847
+ this.inFlightControllers = /* @__PURE__ */ new Set();
1835
1848
  this.createdObjectUrls = [];
1836
1849
  this.inFlightLoads = /* @__PURE__ */ new Map();
1837
1850
  this.cachedAssets = /* @__PURE__ */ new Map();
@@ -1841,31 +1854,42 @@ var AssetLoader = class {
1841
1854
  if (!sanitizedUrl) {
1842
1855
  throw new Error("Asset URL is required");
1843
1856
  }
1844
- const cached = this.cachedAssets.get(sanitizedUrl);
1857
+ let parsedUrl;
1858
+ try {
1859
+ parsedUrl = new URL(sanitizedUrl, typeof location === "undefined" ? void 0 : location.href);
1860
+ } catch {
1861
+ throw new Error("Avatar asset URL is invalid");
1862
+ }
1863
+ if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:" || parsedUrl.username || parsedUrl.password) {
1864
+ throw new Error("Avatar asset URL must use HTTP or HTTPS without embedded credentials");
1865
+ }
1866
+ const cacheKey = `${sanitizedUrl}\0${options?.integrity ?? ""}\0${options?.expectedFormat ?? ""}`;
1867
+ const cached = this.cachedAssets.get(cacheKey);
1845
1868
  if (cached) {
1846
1869
  return cached;
1847
1870
  }
1848
- const inFlight = this.inFlightLoads.get(sanitizedUrl);
1871
+ const inFlight = this.inFlightLoads.get(cacheKey);
1849
1872
  if (inFlight) {
1850
1873
  return inFlight;
1851
1874
  }
1852
1875
  const loadPromise = this.performLoad(sanitizedUrl, options);
1853
- this.inFlightLoads.set(sanitizedUrl, loadPromise);
1876
+ this.inFlightLoads.set(cacheKey, loadPromise);
1854
1877
  try {
1855
1878
  const asset = await loadPromise;
1856
- this.cachedAssets.set(sanitizedUrl, asset);
1879
+ this.cachedAssets.set(cacheKey, asset);
1857
1880
  return asset;
1858
1881
  } finally {
1859
- this.inFlightLoads.delete(sanitizedUrl);
1882
+ this.inFlightLoads.delete(cacheKey);
1860
1883
  }
1861
1884
  }
1862
1885
  async performLoad(sanitizedUrl, options) {
1863
1886
  const startTime = Date.now();
1864
- this.inFlightController = new AbortController();
1865
- const abortSignal = options?.signal ? anySignal([this.inFlightController.signal, options.signal]) : this.inFlightController.signal;
1887
+ const controller = new AbortController();
1888
+ this.inFlightControllers.add(controller);
1889
+ const abortSignal = options?.signal ? anySignal([controller.signal, options.signal]) : controller.signal;
1866
1890
  const timeoutMs = options?.timeoutMs ?? 6e4;
1867
1891
  const timeoutId = setTimeout(() => {
1868
- this.inFlightController?.abort();
1892
+ controller.abort();
1869
1893
  }, timeoutMs);
1870
1894
  try {
1871
1895
  const cleanPath = (sanitizedUrl.split("?")[0] ?? "").toLowerCase();
@@ -1939,12 +1963,25 @@ var AssetLoader = class {
1939
1963
  if (arrayBuffer.byteLength < 12) {
1940
1964
  throw new Error("Avatar asset payload is too small to be a valid 3D container");
1941
1965
  }
1966
+ if (options?.integrity) {
1967
+ await verifyIntegrity(arrayBuffer, options.integrity);
1968
+ }
1942
1969
  const headerBytes = new Uint8Array(arrayBuffer, 0, Math.min(256, arrayBuffer.byteLength));
1943
1970
  const headerStr = new TextDecoder("utf-8", { fatal: false }).decode(headerBytes).trim();
1944
1971
  if (/^<!DOCTYPE\s+html/i.test(headerStr) || /^<html/i.test(headerStr)) {
1945
1972
  throw new Error(`Avatar asset payload contains HTML error page instead of binary 3D container from ${sanitizedUrl}`);
1946
1973
  }
1947
- if (isFbxExtension || this.isFbxBuffer(arrayBuffer) || !isGlbExtension && !this.isGlbBuffer(arrayBuffer)) {
1974
+ const hasFbxSignature = this.isFbxBuffer(arrayBuffer);
1975
+ const hasGlbSignature = this.isGlbBuffer(arrayBuffer);
1976
+ const isFbx = hasFbxSignature || !hasGlbSignature && isFbxExtension;
1977
+ const isGlb = hasGlbSignature || !hasFbxSignature && isGlbExtension;
1978
+ if (isFbx && isGlb) {
1979
+ throw new Error("Avatar asset format is ambiguous");
1980
+ }
1981
+ if (isFbx) {
1982
+ if (options?.expectedFormat && options.expectedFormat !== "fbx") {
1983
+ throw new Error(`Avatar asset format mismatch: expected ${options.expectedFormat}, received fbx`);
1984
+ }
1948
1985
  const fbxHeader = this.parseFbxHeader(arrayBuffer);
1949
1986
  const resourcePath = sanitizedUrl.includes("/") ? sanitizedUrl.substring(0, sanitizedUrl.lastIndexOf("/") + 1) : "";
1950
1987
  return {
@@ -1957,10 +1994,17 @@ var AssetLoader = class {
1957
1994
  durationMs: Date.now() - startTime
1958
1995
  };
1959
1996
  }
1997
+ if (!isGlb) {
1998
+ throw new Error("Avatar asset format is unsupported; expected FBX or GLB");
1999
+ }
2000
+ if (options?.expectedFormat && options.expectedFormat !== "glb") {
2001
+ throw new Error(`Avatar asset format mismatch: expected ${options.expectedFormat}, received glb`);
2002
+ }
1960
2003
  const parsedGlb = this.parseGlb(arrayBuffer);
1961
2004
  return {
1962
2005
  format: "glb",
1963
2006
  url: sanitizedUrl,
2007
+ buffer: arrayBuffer,
1964
2008
  json: parsedGlb.json,
1965
2009
  bin: parsedGlb.bin,
1966
2010
  meshes: parsedGlb.meshes,
@@ -1969,7 +2013,7 @@ var AssetLoader = class {
1969
2013
  };
1970
2014
  } finally {
1971
2015
  clearTimeout(timeoutId);
1972
- this.inFlightController = null;
2016
+ this.inFlightControllers.delete(controller);
1973
2017
  }
1974
2018
  }
1975
2019
  isFbxBuffer(buffer) {
@@ -2185,10 +2229,8 @@ var AssetLoader = class {
2185
2229
  };
2186
2230
  }
2187
2231
  destroy() {
2188
- if (this.inFlightController) {
2189
- this.inFlightController.abort();
2190
- this.inFlightController = null;
2191
- }
2232
+ for (const controller of this.inFlightControllers) controller.abort();
2233
+ this.inFlightControllers.clear();
2192
2234
  this.inFlightLoads.clear();
2193
2235
  this.cachedAssets.clear();
2194
2236
  if (typeof URL !== "undefined" && typeof URL.revokeObjectURL === "function") {
@@ -2202,6 +2244,20 @@ var AssetLoader = class {
2202
2244
  this.createdObjectUrls.length = 0;
2203
2245
  }
2204
2246
  };
2247
+ async function verifyIntegrity(buffer, integrity) {
2248
+ const [algorithm, expected] = integrity.split("-", 2);
2249
+ if (algorithm !== "sha256" || !expected) {
2250
+ throw new Error("Avatar asset integrity metadata is invalid");
2251
+ }
2252
+ const cryptoApi = globalThis.crypto;
2253
+ if (!cryptoApi?.subtle) return;
2254
+ const digest = new Uint8Array(await cryptoApi.subtle.digest("SHA-256", buffer));
2255
+ let binary = "";
2256
+ for (const byte of digest) binary += String.fromCharCode(byte);
2257
+ if (btoa(binary) !== expected) {
2258
+ throw new Error("Avatar asset integrity verification failed");
2259
+ }
2260
+ }
2205
2261
  function anySignal(signals) {
2206
2262
  const controller = new AbortController();
2207
2263
  for (const sig of signals) {
@@ -2338,7 +2394,7 @@ var FbxRenderer = class {
2338
2394
  const loader = new GLTFLoader_js.GLTFLoader();
2339
2395
  try {
2340
2396
  const gltf = await new Promise((resolve, reject) => {
2341
- const glbBuffer = asset.bin.buffer.slice(asset.bin.byteOffset, asset.bin.byteOffset + asset.bin.byteLength);
2397
+ const glbBuffer = asset.buffer ? asset.buffer : asset.bin.buffer.slice(asset.bin.byteOffset, asset.bin.byteOffset + asset.bin.byteLength);
2342
2398
  loader.parse(glbBuffer, asset.url, resolve, reject);
2343
2399
  });
2344
2400
  rawObject = gltf.scene;
@@ -2442,47 +2498,6 @@ var FbxRenderer = class {
2442
2498
  if (this.playAnimation(pose)) {
2443
2499
  return;
2444
2500
  }
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
2501
  if (!this.modelRoot) return;
2487
2502
  this.modelRoot.scale.setScalar(this.baseScale);
2488
2503
  switch (pose) {
@@ -2527,13 +2542,13 @@ var FbxRenderer = class {
2527
2542
  return true;
2528
2543
  }
2529
2544
  const idleByName = this.animationMetadataList.find(
2530
- (m) => m.name.toLowerCase().includes("idle") || m.clipName && m.clipName.toLowerCase().includes("idle")
2545
+ (m) => m.name.toLowerCase() === "idle" || m.clipName?.toLowerCase() === "idle"
2531
2546
  );
2532
2547
  if (idleByName && this.playAnimation(idleByName.id || idleByName.name)) {
2533
2548
  return true;
2534
2549
  }
2535
2550
  const embeddedIdle = this.allAnimations.find(
2536
- (c) => c.name.toLowerCase().includes("idle")
2551
+ (c) => c.name.toLowerCase() === "idle"
2537
2552
  );
2538
2553
  if (embeddedIdle) {
2539
2554
  const action = this.mixer.clipAction(embeddedIdle);
@@ -2544,22 +2559,6 @@ var FbxRenderer = class {
2544
2559
  }
2545
2560
  return true;
2546
2561
  }
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
2562
  return false;
2564
2563
  }
2565
2564
  async loadExternalAnimations(animations, targetAnimationName) {
@@ -2577,7 +2576,7 @@ var FbxRenderer = class {
2577
2576
  await Promise.allSettled(
2578
2577
  pending.map(async (anim) => {
2579
2578
  try {
2580
- const loaded = await this.assetLoader.load(anim.assetUrl);
2579
+ const loaded = await this.assetLoader.load(anim.assetUrl, { integrity: anim.integrity });
2581
2580
  let extractedClips = [];
2582
2581
  if (loaded.format === "fbx") {
2583
2582
  const loader = new FBXLoader_js.FBXLoader();
@@ -2589,7 +2588,7 @@ var FbxRenderer = class {
2589
2588
  } else if (loaded.format === "glb") {
2590
2589
  const loader = new GLTFLoader_js.GLTFLoader();
2591
2590
  const gltf = await new Promise((resolve, reject) => {
2592
- const glbBuffer = loaded.bin.buffer.slice(
2591
+ const glbBuffer = loaded.buffer ? loaded.buffer : loaded.bin.buffer.slice(
2593
2592
  loaded.bin.byteOffset,
2594
2593
  loaded.bin.byteOffset + loaded.bin.byteLength
2595
2594
  );
@@ -2703,13 +2702,13 @@ var FbxRenderer = class {
2703
2702
  clip = this.allAnimations.find((c) => c.name.toLowerCase() === query);
2704
2703
  }
2705
2704
  if (!clip) {
2706
- clip = this.allAnimations.find((c) => c.name.toLowerCase().includes(query));
2705
+ clip = this.allAnimations.find((c) => c.name.toLowerCase() === query);
2707
2706
  }
2708
2707
  if (!clip) {
2709
2708
  return false;
2710
2709
  }
2711
2710
  const action = this.mixer.clipAction(clip);
2712
- const effectiveLoop = loopMode || matched?.loopMode || "repeat";
2711
+ const effectiveLoop = (loopMode || matched?.loopMode || "loop").toLowerCase();
2713
2712
  if (effectiveLoop === "once") {
2714
2713
  action.setLoop(THREE__namespace.LoopOnce, 1);
2715
2714
  action.clampWhenFinished = true;
@@ -3217,6 +3216,8 @@ var CssAvatarRenderer = class {
3217
3216
  if (!this.isAssetLoadedFlag && this.viewport) {
3218
3217
  if (this.renderState === "error") {
3219
3218
  this.renderFallback(true);
3219
+ } else if (this.renderState === "loading") {
3220
+ this.renderLoadingPlaceholder();
3220
3221
  } else {
3221
3222
  this.viewport.replaceChildren();
3222
3223
  }
@@ -3282,7 +3283,11 @@ var CssAvatarRenderer = class {
3282
3283
  }
3283
3284
  try {
3284
3285
  this.metricsTracker?.record("assetRequestStart");
3285
- const asset = await this.assetLoader.load(assetUrl, { timeoutMs: 6e4 });
3286
+ const asset = await this.assetLoader.load(assetUrl, {
3287
+ timeoutMs: 6e4,
3288
+ integrity: config.assetIntegrity,
3289
+ expectedFormat: config.assetUrl ? config.modelFormat : void 0
3290
+ });
3286
3291
  this.metricsTracker?.record("assetDownloadComplete");
3287
3292
  const byteSize = asset.buffer?.byteLength ?? asset.bin?.byteLength ?? asset.size;
3288
3293
  this.metricsTracker?.setAssetInfo({
@@ -3383,7 +3388,10 @@ var CssAvatarRenderer = class {
3383
3388
  const thumb = typeof asset.manifest.thumbnailUrl === "string" ? asset.manifest.thumbnailUrl : void 0;
3384
3389
  const modelUrl = typeof asset.manifest.assetUrl === "string" ? asset.manifest.assetUrl : typeof asset.manifest.modelUrl === "string" ? asset.manifest.modelUrl : void 0;
3385
3390
  if (modelUrl) {
3386
- const subAsset = await this.assetLoader.load(modelUrl, { timeoutMs: 6e4 });
3391
+ const subAsset = await this.assetLoader.load(modelUrl, {
3392
+ timeoutMs: 6e4,
3393
+ expectedFormat: config.modelFormat
3394
+ });
3387
3395
  await this.renderLoadedAsset(subAsset, config);
3388
3396
  } else if (thumb) {
3389
3397
  this.viewport.replaceChildren();
@@ -3398,6 +3406,16 @@ var CssAvatarRenderer = class {
3398
3406
  }
3399
3407
  }
3400
3408
  }
3409
+ renderLoadingPlaceholder() {
3410
+ if (!this.viewport) return;
3411
+ this.viewport.replaceChildren();
3412
+ const doc = this.viewport.ownerDocument;
3413
+ const placeholder = doc.createElement("div");
3414
+ placeholder.className = "asiyst-avatar-loader";
3415
+ placeholder.setAttribute("aria-hidden", "true");
3416
+ placeholder.setAttribute("data-state", "loading");
3417
+ this.viewport.appendChild(placeholder);
3418
+ }
3401
3419
  renderFallback(isError = false) {
3402
3420
  if (!this.viewport) return;
3403
3421
  this.viewport.replaceChildren();
@@ -4177,11 +4195,10 @@ function transition(from, to) {
4177
4195
 
4178
4196
  // src/task/TaskEngine.ts
4179
4197
  var TaskEngine = class {
4180
- constructor(interaction, events, analytics, cloud) {
4198
+ constructor(interaction, events, analytics) {
4181
4199
  this.interaction = interaction;
4182
4200
  this.events = events;
4183
4201
  this.analytics = analytics;
4184
- this.cloud = cloud;
4185
4202
  this.status = TaskStatus.Idle;
4186
4203
  this.abort = false;
4187
4204
  }
@@ -4197,7 +4214,6 @@ var TaskEngine = class {
4197
4214
  this.events.emit("asiyst:task:started", { taskId: task.id });
4198
4215
  this.analytics.track("task_started", { taskId: task.id });
4199
4216
  this.analytics.track("guide_started", { taskId: task.id });
4200
- void this.cloud.sendTaskUpdate(task.id, this.status);
4201
4217
  try {
4202
4218
  for (const [index, step] of task.steps.entries()) {
4203
4219
  if (this.abort) {
@@ -4232,13 +4248,11 @@ var TaskEngine = class {
4232
4248
  }
4233
4249
  this.move(TaskStatus.StepCompleted);
4234
4250
  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
4251
  }
4237
4252
  this.move(TaskStatus.TaskCompleted);
4238
4253
  this.events.emit("asiyst:task:completed", { taskId: task.id });
4239
4254
  this.analytics.track("task_completed", { taskId: task.id });
4240
4255
  this.analytics.track("guide_completed", { taskId: task.id });
4241
- void this.cloud.sendTaskUpdate(task.id, this.status);
4242
4256
  this.move(TaskStatus.Idle);
4243
4257
  return TaskStatus.TaskCompleted;
4244
4258
  } catch (error) {
@@ -4313,6 +4327,7 @@ var ConversationPanel = class {
4313
4327
  this.onToggle = onToggle;
4314
4328
  this.conversationId = "";
4315
4329
  this.openState = false;
4330
+ this.submitting = false;
4316
4331
  const doc = root.ownerDocument;
4317
4332
  this.style = doc.createElement("style");
4318
4333
  this.style.textContent = `
@@ -4410,6 +4425,9 @@ var ConversationPanel = class {
4410
4425
  getConversationId() {
4411
4426
  return this.conversationId;
4412
4427
  }
4428
+ setConversationId(conversationId) {
4429
+ this.conversationId = conversationId;
4430
+ }
4413
4431
  open() {
4414
4432
  if (!this.conversationId) {
4415
4433
  this.conversationId = `conv_${Date.now().toString(36)}`;
@@ -4424,22 +4442,51 @@ var ConversationPanel = class {
4424
4442
  this.panel.hidden = true;
4425
4443
  this.onToggle(false);
4426
4444
  }
4427
- append(role, text) {
4445
+ append(role, text, citations = []) {
4428
4446
  const item = this.log.ownerDocument.createElement("div");
4429
4447
  item.className = "asiyst-msg";
4430
4448
  item.setAttribute("data-role", role);
4431
4449
  renderSafeText(item, text);
4450
+ for (const citation of citations) {
4451
+ if (!citation.url) continue;
4452
+ let url;
4453
+ try {
4454
+ url = new URL(citation.url);
4455
+ } catch {
4456
+ continue;
4457
+ }
4458
+ if (url.protocol !== "https:") continue;
4459
+ const link = this.log.ownerDocument.createElement("a");
4460
+ link.href = url.href;
4461
+ link.rel = "noopener noreferrer";
4462
+ link.target = "_blank";
4463
+ link.textContent = sanitizeText(citation.title, 160);
4464
+ const wrapper = this.log.ownerDocument.createElement("div");
4465
+ wrapper.appendChild(link);
4466
+ item.appendChild(wrapper);
4467
+ }
4432
4468
  this.log.appendChild(item);
4433
4469
  this.log.scrollTop = this.log.scrollHeight;
4434
4470
  }
4435
4471
  async submit() {
4472
+ if (this.submitting) return;
4436
4473
  const text = sanitizeText(this.input.value);
4437
4474
  if (!text) {
4438
4475
  return;
4439
4476
  }
4477
+ this.submitting = true;
4478
+ this.input.disabled = true;
4479
+ this.form.querySelector("button")?.setAttribute("disabled", "true");
4440
4480
  this.input.value = "";
4441
4481
  this.append("user", text);
4442
- await this.onSubmit(text);
4482
+ try {
4483
+ await this.onSubmit(text);
4484
+ } finally {
4485
+ this.submitting = false;
4486
+ this.input.disabled = false;
4487
+ this.form.querySelector("button")?.removeAttribute("disabled");
4488
+ this.input.focus();
4489
+ }
4443
4490
  }
4444
4491
  destroy() {
4445
4492
  if (this.keydownListener) {
@@ -4502,19 +4549,15 @@ function loadOrCreateInstallationId(projectId) {
4502
4549
  }
4503
4550
 
4504
4551
  // 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
4552
  var RuntimeAuth = class {
4513
4553
  constructor(options) {
4514
4554
  this.options = options;
4515
4555
  }
4516
- async getToken(capability) {
4517
- if (this.token && this.isUsable(this.token) && this.token.capabilities.has(capability)) {
4556
+ setInstallationId(installationId) {
4557
+ this.options.installationId = installationId;
4558
+ }
4559
+ async getToken() {
4560
+ if (this.token && this.isUsable(this.token) && Date.now() < this.token.refreshAfter) {
4518
4561
  return this.token.value;
4519
4562
  }
4520
4563
  if (!this.requestInFlight) {
@@ -4523,33 +4566,38 @@ var RuntimeAuth = class {
4523
4566
  });
4524
4567
  }
4525
4568
  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
4569
  return token.value;
4530
4570
  }
4531
4571
  invalidate() {
4532
4572
  this.token = void 0;
4533
4573
  }
4534
4574
  isUsable(token) {
4535
- return token.expiresAt - Date.now() > 3e4;
4575
+ return token.expiresAt > Date.now();
4536
4576
  }
4537
4577
  async issueToken() {
4578
+ const installationId = this.options.installationId;
4579
+ if (!installationId) {
4580
+ throw new AuthenticationError("ASIYST installation has not been verified.");
4581
+ }
4538
4582
  const controller = new AbortController();
4539
- const timeout = setTimeout(() => controller.abort(), 1e4);
4583
+ let timedOut = false;
4584
+ const timeout = setTimeout(() => {
4585
+ timedOut = true;
4586
+ controller.abort();
4587
+ }, 1e4);
4540
4588
  let response;
4541
4589
  try {
4542
4590
  const baseUrl = this.options.apiBaseUrl.replace(/\/$/, "");
4543
4591
  const payload = JSON.stringify({
4544
4592
  projectId: this.options.projectId,
4545
4593
  publicKey: this.options.publicKey,
4546
- installationId: this.options.installationId,
4594
+ installationId,
4547
4595
  origin: this.options.origin,
4548
- environment: this.options.environment,
4549
4596
  sdkVersion: SDK_VERSION,
4550
- capabilities: [...RUNTIME_CAPABILITIES]
4597
+ environment: this.options.environment,
4598
+ capabilities: ["assistant:config", "assistant:conversation", "assistant:heartbeat"]
4551
4599
  });
4552
- response = await fetch(`${baseUrl}/sdk/runtime/token`, {
4600
+ response = await fetch(contractApiUrl(baseUrl, API_ROUTES.runtimeToken), {
4553
4601
  method: "POST",
4554
4602
  headers: {
4555
4603
  Accept: "application/json",
@@ -4558,19 +4606,8 @@ var RuntimeAuth = class {
4558
4606
  body: payload,
4559
4607
  signal: controller.signal
4560
4608
  });
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
4609
  } catch {
4573
- throw new NetworkError("ASIYST runtime authentication is unavailable.");
4610
+ throw new NetworkError(timedOut ? "ASIYST runtime authentication request timed out." : "ASIYST runtime authentication is unavailable.");
4574
4611
  } finally {
4575
4612
  clearTimeout(timeout);
4576
4613
  }
@@ -4581,16 +4618,39 @@ var RuntimeAuth = class {
4581
4618
  body = void 0;
4582
4619
  }
4583
4620
  if (!response.ok) {
4584
- if (response.status === 403) {
4585
- throw new AuthenticationError("ASIYST runtime authorization was rejected.");
4621
+ if (response.status === 401 || response.status === 403) {
4622
+ const errorRecord = body && typeof body === "object" ? body.error : void 0;
4623
+ const errorBody = errorRecord && typeof errorRecord === "object" ? errorRecord : void 0;
4624
+ const code = typeof errorBody?.code === "string" ? errorBody.code : void 0;
4625
+ const installationErrorCodes = {
4626
+ INSTALLATION_NOT_FOUND: "Asiyst installation not found for this domain. Re-run `asiyst connect` and verify your project domain.",
4627
+ INSTALLATION_INACTIVE: "Asiyst installation is inactive. Check your project status in the Asiyst dashboard.",
4628
+ INSTALLATION_REVOKED: "Asiyst installation has been revoked. Re-run `asiyst connect` to register a new installation.",
4629
+ INSTALLATION_PROJECT_MISMATCH: "Asiyst installation does not match the configured project.",
4630
+ INSTALLATION_DOMAIN_MISMATCH: "Asiyst installation domain does not match the current website domain.",
4631
+ ORIGIN_MISMATCH: "Asiyst installation origin does not match the current website origin.",
4632
+ INSTALLATION_ENVIRONMENT_MISMATCH: "Asiyst installation environment does not match the current website environment.",
4633
+ RUNTIME_TOKEN_INVALID: "Asiyst runtime authorization token is invalid.",
4634
+ RUNTIME_TOKEN_EXPIRED: "Asiyst runtime authorization token has expired."
4635
+ };
4636
+ const knownMessage = code ? installationErrorCodes[code] : void 0;
4637
+ if (knownMessage) {
4638
+ throw new AuthenticationError(knownMessage);
4639
+ }
4640
+ throw new AuthenticationError(
4641
+ typeof errorBody?.message === "string" ? `ASIYST runtime authorization rejected: ${errorBody.message}` : "ASIYST runtime authorization was rejected."
4642
+ );
4586
4643
  }
4587
4644
  if (response.status === 429) {
4588
4645
  throw new NetworkError("ASIYST runtime authentication is rate limited.");
4589
4646
  }
4647
+ if (response.status === 503) {
4648
+ throw new NetworkError("ASIYST runtime authentication is unavailable.");
4649
+ }
4590
4650
  throw new NetworkError("ASIYST runtime authentication is unavailable.");
4591
4651
  }
4592
4652
  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))) {
4653
+ 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" || typeof data.expiresIn !== "number" || data.expiresIn <= 0 || !Array.isArray(data.capabilities) || !data.capabilities.includes("assistant:config") || !data.capabilities.includes("assistant:conversation") || !data.capabilities.includes("assistant:heartbeat")) {
4594
4654
  throw new AuthenticationError("ASIYST returned an invalid runtime authorization response.");
4595
4655
  }
4596
4656
  const expiresAt = Date.parse(data.expiresAt);
@@ -4600,7 +4660,7 @@ var RuntimeAuth = class {
4600
4660
  const token = {
4601
4661
  value: data.token,
4602
4662
  expiresAt,
4603
- capabilities: new Set(data.capabilities)
4663
+ refreshAfter: expiresAt
4604
4664
  };
4605
4665
  this.token = token;
4606
4666
  return token;
@@ -4766,6 +4826,7 @@ var AsiystRuntime = class {
4766
4826
  this.rescanDebounced = debounce(() => this.rescan(), DOM_SCAN_DEBOUNCE_MS);
4767
4827
  this.isHeartbeatInFlight = false;
4768
4828
  this.lastHeartbeatTime = 0;
4829
+ this.nextHeartbeatAfterMs = HEARTBEAT_INTERVAL_MS;
4769
4830
  this.registrationSucceeded = false;
4770
4831
  if (!doc.body) {
4771
4832
  throw new InitializationError("document.body is not available");
@@ -4785,10 +4846,11 @@ var AsiystRuntime = class {
4785
4846
  apiBaseUrl: options.apiBaseUrl ?? DEFAULT_API_BASE_URL,
4786
4847
  projectId: options.projectId,
4787
4848
  publicKey: options.publicKey,
4788
- installationId: this.installationId,
4849
+ installationId: void 0,
4789
4850
  origin: win.location.origin,
4790
4851
  environment: this.environment
4791
4852
  }) : void 0;
4853
+ this.runtimeAuth = runtimeAuth;
4792
4854
  this.cloud = new CloudClient(transport, options.projectId, options.publicKey, runtimeAuth, this.visitorSessionId, options.avatarId);
4793
4855
  this.config = new ConfigManager(options, this.cloud, this.events);
4794
4856
  this.config.onConfigUpdated = (newConfig, prevConfig) => {
@@ -4820,21 +4882,19 @@ var AsiystRuntime = class {
4820
4882
  () => this.config.get()
4821
4883
  );
4822
4884
  const interaction = new InteractionEngine(this.avatar, this.resolver, () => this.config.get(), win);
4823
- this.tasks = new TaskEngine(interaction, this.events, this.analytics, this.cloud);
4885
+ this.tasks = new TaskEngine(interaction, this.events, this.analytics);
4824
4886
  this.workflows = new WorkflowEngine(this.cloud, this.tasks);
4825
4887
  this.panel = new ConversationPanel(
4826
4888
  this.host.chrome,
4827
4889
  (text) => this.handleUserMessage(text, doc),
4828
4890
  (open) => {
4829
- const convId = this.panel.getConversationId();
4830
- this.cloud.setConversationId(convId);
4831
4891
  this.renderer.setPanelOpen(open);
4832
4892
  if (open) {
4833
4893
  this.analytics.track("assistant_opened");
4834
- this.events.emit("asiyst:conversation:started", { conversationId: convId });
4835
4894
  } else {
4836
4895
  this.analytics.track("assistant_closed");
4837
- this.events.emit("asiyst:conversation:closed", { conversationId: convId });
4896
+ const conversationId = this.panel.getConversationId();
4897
+ if (conversationId) this.events.emit("asiyst:conversation:closed", { conversationId });
4838
4898
  }
4839
4899
  }
4840
4900
  );
@@ -4843,22 +4903,35 @@ var AsiystRuntime = class {
4843
4903
  this.observer.start(doc.documentElement);
4844
4904
  this.highlights.start();
4845
4905
  this.movement.start();
4846
- this.analytics.start();
4847
4906
  this.rescan();
4848
4907
  const figure = this.renderer.getFigure();
4849
4908
  if (figure) {
4850
4909
  this.figureClickListener = () => this.open();
4851
4910
  figure.addEventListener("click", this.figureClickListener);
4852
4911
  }
4853
- this.pagehideListener = () => {
4854
- void this.analytics.flush();
4855
- };
4856
- win.addEventListener("pagehide", this.pagehideListener);
4857
4912
  }
4858
4913
  async start() {
4859
4914
  this.events.emit("asiyst:initialized", { projectId: this.options.projectId });
4860
4915
  this.avatar.show();
4861
4916
  this.movement.goToAnchor();
4917
+ this.lifecycle.emit("sdk.verification_started", {
4918
+ projectId: this.options.projectId,
4919
+ origin: window.location.origin,
4920
+ environment: this.environment,
4921
+ installationId: this.installationId,
4922
+ sdkVersion: SDK_VERSION
4923
+ });
4924
+ try {
4925
+ await this.registerInstallation();
4926
+ } catch (error) {
4927
+ this.connectionStatus = "offline";
4928
+ this.verificationStatus = "error";
4929
+ this.events.emit("asiyst:error", {
4930
+ // Safe diagnostic code — does not expose secrets or signing details.
4931
+ code: "installation_registration_failed",
4932
+ message: error instanceof Error ? error.message : "Asiyst runtime connection failed."
4933
+ });
4934
+ }
4862
4935
  const cfg = await isolateAsync(() => this.config.refresh(), this.config.get());
4863
4936
  this.metricsTracker.record("configRetrieved");
4864
4937
  const domainCheck = validateWebsiteDomain(cfg, window.location.href);
@@ -4873,28 +4946,7 @@ var AsiystRuntime = class {
4873
4946
  }
4874
4947
  this.avatar.applyConfig(cfg);
4875
4948
  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
4949
  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
4950
  const assetTarget = cfg.assetUrl ?? cfg.thumbnailUrl;
4899
4951
  if (assetTarget) {
4900
4952
  try {
@@ -4907,6 +4959,16 @@ var AsiystRuntime = class {
4907
4959
  this.avatar.show();
4908
4960
  this.movement.goToAnchor();
4909
4961
  }
4962
+ try {
4963
+ await this.sendHeartbeat();
4964
+ } catch (error) {
4965
+ this.connectionStatus = "offline";
4966
+ this.verificationStatus = "error";
4967
+ this.events.emit("asiyst:error", {
4968
+ code: "runtime_connection_failed",
4969
+ message: error instanceof Error ? error.message : "Asiyst runtime connection failed."
4970
+ });
4971
+ }
4910
4972
  this.startConfigRevalidationScheduler();
4911
4973
  }
4912
4974
  async loadAvatarAsset(cfg, assetTarget) {
@@ -4914,10 +4976,6 @@ var AsiystRuntime = class {
4914
4976
  avatarId: this.options.avatarId ?? cfg.avatarId,
4915
4977
  assetUrl: assetTarget
4916
4978
  });
4917
- void this.cloud.sendTelemetryEvent("avatar_asset_loading_started", {
4918
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4919
- assetUrl: assetTarget
4920
- });
4921
4979
  try {
4922
4980
  const loaded = await this.renderer.loadAsset(cfg, this.metricsTracker);
4923
4981
  if (loaded) {
@@ -4930,13 +4988,6 @@ var AsiystRuntime = class {
4930
4988
  assetUrl,
4931
4989
  format
4932
4990
  });
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
4991
  if (isRendered) {
4941
4992
  const metrics = this.metricsTracker.getMetrics();
4942
4993
  const durationMs = metrics?.durations.timeToFirstVisibleMs;
@@ -4945,13 +4996,6 @@ var AsiystRuntime = class {
4945
4996
  format,
4946
4997
  durationMs
4947
4998
  });
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
4999
  }
4956
5000
  return true;
4957
5001
  } else {
@@ -4961,11 +5005,6 @@ var AsiystRuntime = class {
4961
5005
  error: err,
4962
5006
  stage: "renderer_init"
4963
5007
  });
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
5008
  return false;
4970
5009
  }
4971
5010
  } catch (error) {
@@ -4975,11 +5014,6 @@ var AsiystRuntime = class {
4975
5014
  error: err,
4976
5015
  stage: "asset_fetch"
4977
5016
  });
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
5017
  return false;
4984
5018
  }
4985
5019
  }
@@ -5026,6 +5060,7 @@ var AsiystRuntime = class {
5026
5060
  config: newConfig,
5027
5061
  previousVersion: prevConfig?.version
5028
5062
  });
5063
+ void this.sendHeartbeat();
5029
5064
  }
5030
5065
  async reloadConfig() {
5031
5066
  const updated = await this.config.refresh({ force: true });
@@ -5115,15 +5150,11 @@ var AsiystRuntime = class {
5115
5150
  clearInterval(this.configRevalidationTimer);
5116
5151
  this.configRevalidationTimer = void 0;
5117
5152
  }
5118
- const doc = this.host.host.ownerDocument;
5119
- if (doc && this.visibilityListener) {
5120
- doc.removeEventListener("visibilitychange", this.visibilityListener);
5121
- this.visibilityListener = void 0;
5153
+ if (this.heartbeatTimer) {
5154
+ clearTimeout(this.heartbeatTimer);
5155
+ this.heartbeatTimer = void 0;
5122
5156
  }
5123
5157
  this.isHeartbeatInFlight = false;
5124
- if (this.pagehideListener) {
5125
- win.removeEventListener("pagehide", this.pagehideListener);
5126
- }
5127
5158
  const figure = this.renderer.getFigure();
5128
5159
  if (figure && this.figureClickListener) {
5129
5160
  figure.removeEventListener("click", this.figureClickListener);
@@ -5140,26 +5171,20 @@ var AsiystRuntime = class {
5140
5171
  this.events.removeAll();
5141
5172
  await this.analytics.destroy();
5142
5173
  }
5143
- startHeartbeatScheduler(doc) {
5144
- if (this.heartbeatTimer) {
5145
- clearInterval(this.heartbeatTimer);
5174
+ async sendHeartbeat() {
5175
+ if (this.destroyed || this.isHeartbeatInFlight || !this.registrationSucceeded || !this.installationId) {
5176
+ return false;
5146
5177
  }
5147
- this.heartbeatTimer = setInterval(() => {
5148
- if (!this.destroyed) {
5149
- void this.sendHeartbeat(true);
5178
+ const state = this.renderer.getRenderState() === "error" ? "degraded" : "ready";
5179
+ if (this.lastReportedState === state) return true;
5180
+ const elapsed = Date.now() - this.lastHeartbeatTime;
5181
+ if (this.lastHeartbeatTime && elapsed < this.nextHeartbeatAfterMs) {
5182
+ if (!this.heartbeatTimer) {
5183
+ this.heartbeatTimer = setTimeout(() => {
5184
+ this.heartbeatTimer = void 0;
5185
+ void this.sendHeartbeat();
5186
+ }, this.nextHeartbeatAfterMs - elapsed);
5150
5187
  }
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
5188
  return false;
5164
5189
  }
5165
5190
  this.isHeartbeatInFlight = true;
@@ -5168,17 +5193,23 @@ var AsiystRuntime = class {
5168
5193
  const environment = this.environment;
5169
5194
  const installationId = this.installationId;
5170
5195
  try {
5171
- if (!this.registrationSucceeded && installationId) {
5172
- await this.registerInstallation();
5173
- }
5174
5196
  const heartbeat = await this.cloud.heartbeat({
5175
- origin,
5176
- environment,
5177
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
5197
+ installationId: this.installationId,
5198
+ sdkVersion: SDK_VERSION,
5199
+ state,
5200
+ avatarReady: this.renderer.getRenderState() === "ready",
5201
+ textChatReady: true,
5202
+ environment: this.environment,
5203
+ ...state === "degraded" ? { failureReason: "asset_load_failed" } : {}
5178
5204
  });
5179
5205
  this.lastHeartbeatTime = Date.now();
5206
+ if (heartbeat.ok) this.lastReportedState = state;
5207
+ this.nextHeartbeatAfterMs = Math.max(
5208
+ HEARTBEAT_INTERVAL_MS,
5209
+ heartbeat.nextHeartbeatAfterMs ?? heartbeat.retryAfterMs ?? HEARTBEAT_INTERVAL_MS
5210
+ );
5180
5211
  this.connectionStatus = heartbeat.ok ? "connected" : "disconnected";
5181
- this.verificationStatus = heartbeat.verificationStatus === "verified" ? "connected" : heartbeat.verificationStatus ?? (heartbeat.ok ? "connected" : "not_detected");
5212
+ this.verificationStatus = heartbeat.ok ? "connected" : "not_detected";
5182
5213
  if (heartbeat.ok) {
5183
5214
  if (!previousConnection) {
5184
5215
  this.events.emit("asiyst:runtime:connected", {
@@ -5195,32 +5226,21 @@ var AsiystRuntime = class {
5195
5226
  sdkVersion: SDK_VERSION
5196
5227
  });
5197
5228
  }
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
- }
5229
+ this.lifecycle.emit("sdk.verified", {
5230
+ projectId: this.options.projectId,
5231
+ origin,
5232
+ environment,
5233
+ installationId,
5234
+ sdkVersion: SDK_VERSION
5235
+ });
5216
5236
  return true;
5217
5237
  } else {
5218
- const reason = heartbeat.verificationStatus ?? "unverified";
5238
+ this.lastReportedState = void 0;
5219
5239
  this.lifecycle.emit("sdk.verification_failed", {
5220
5240
  projectId: this.options.projectId,
5221
5241
  origin,
5222
5242
  environment,
5223
- status: reason,
5243
+ status: "heartbeat_failed",
5224
5244
  reason: "heartbeat_failed"
5225
5245
  });
5226
5246
  if (previousConnection) {
@@ -5234,12 +5254,15 @@ var AsiystRuntime = class {
5234
5254
  environment,
5235
5255
  installationId,
5236
5256
  reason: "heartbeat_failed",
5237
- status: reason
5257
+ status: "heartbeat_failed"
5238
5258
  });
5239
5259
  }
5260
+ this.scheduleHeartbeatRetry();
5240
5261
  return false;
5241
5262
  }
5242
5263
  } catch (error) {
5264
+ this.lastHeartbeatTime = Date.now();
5265
+ this.lastReportedState = void 0;
5243
5266
  this.connectionStatus = "offline";
5244
5267
  this.verificationStatus = "error";
5245
5268
  this.lifecycle.emit("sdk.verification_failed", {
@@ -5250,6 +5273,10 @@ var AsiystRuntime = class {
5250
5273
  reason: "heartbeat_failed",
5251
5274
  category: error instanceof AuthenticationError ? "authorization" : "network"
5252
5275
  });
5276
+ this.events.emit("asiyst:error", {
5277
+ code: "runtime_heartbeat_failed",
5278
+ message: error instanceof Error ? error.message : "Asiyst heartbeat failed."
5279
+ });
5253
5280
  if (previousConnection) {
5254
5281
  this.events.emit("asiyst:runtime:disconnected", {
5255
5282
  projectId: this.options.projectId,
@@ -5269,73 +5296,72 @@ var AsiystRuntime = class {
5269
5296
  this.isHeartbeatInFlight = false;
5270
5297
  }
5271
5298
  }
5299
+ scheduleHeartbeatRetry() {
5300
+ if (this.destroyed || this.heartbeatTimer) return;
5301
+ const remaining = Math.max(0, this.nextHeartbeatAfterMs - (Date.now() - this.lastHeartbeatTime));
5302
+ this.heartbeatTimer = setTimeout(() => {
5303
+ this.heartbeatTimer = void 0;
5304
+ void this.sendHeartbeat();
5305
+ }, remaining);
5306
+ }
5272
5307
  async registerInstallation() {
5273
5308
  const origin = window.location.origin;
5274
5309
  const environment = this.environment;
5275
5310
  const installationId = this.installationId;
5276
5311
  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;
5312
+ throw new InitializationError("Asiyst could not establish a secure installation identity.");
5281
5313
  }
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));
5314
+ try {
5315
+ const verified = await this.cloud.registerInstallation({
5316
+ projectId: this.options.projectId,
5317
+ publicKey: this.options.publicKey,
5318
+ installationId,
5319
+ origin,
5320
+ environment,
5321
+ sdkVersion: SDK_VERSION
5322
+ });
5323
+ if (!verified.data.installationId) {
5324
+ throw new InitializationError("Asiyst returned no verified installation identifier.");
5312
5325
  }
5326
+ this.installationId = verified.data.installationId;
5327
+ this.runtimeAuth?.setInstallationId(verified.data.installationId);
5328
+ this.registrationSucceeded = true;
5329
+ } catch (error) {
5330
+ if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
5331
+ console.debug("[asiyst] SDK installation verification failed.", error);
5332
+ }
5333
+ this.lifecycle.emit("sdk.verification_failed", {
5334
+ projectId: this.options.projectId,
5335
+ origin,
5336
+ environment,
5337
+ installationId,
5338
+ reason: "registration_failed",
5339
+ category: error instanceof AuthenticationError ? "authorization" : "network"
5340
+ });
5341
+ throw error;
5313
5342
  }
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
5343
  }
5323
5344
  rescan() {
5324
5345
  withIsolation(() => {
5325
5346
  const doc = this.host.host.ownerDocument;
5326
5347
  this.map.replace(inspectDocument(doc));
5327
- void this.cloud.sendWebsiteMap(this.map.snapshot(doc));
5328
5348
  });
5329
5349
  }
5330
5350
  async handleUserMessage(text, doc) {
5331
5351
  this.events.emit("asiyst:conversation:message", { role: "user", text });
5332
5352
  this.avatar.think();
5333
5353
  try {
5334
- const reply = await this.cloud.sendConversationMessage(text, doc.location.href);
5335
- this.panel.append("assistant", reply.message.text);
5354
+ const reply = await this.cloud.sendConversationMessage(
5355
+ text,
5356
+ doc.location.href,
5357
+ this.config.get().maxMessageChars
5358
+ );
5359
+ this.panel.setConversationId(reply.conversationId);
5360
+ this.cloud.setConversationId(reply.conversationId);
5361
+ this.events.emit("asiyst:conversation:started", { conversationId: reply.conversationId });
5362
+ this.panel.append("assistant", reply.message.text, reply.citations);
5336
5363
  this.avatar.speak(reply.message.text);
5337
5364
  this.events.emit("asiyst:conversation:message", { role: "assistant", text: reply.message.text });
5338
- await this.startTaskFromText(text, doc);
5339
5365
  } catch (error) {
5340
5366
  const message = error instanceof Error ? error.message : "Asiyst Cloud is unavailable";
5341
5367
  this.panel.append("assistant", message);
@@ -5359,6 +5385,9 @@ var Asiyst = {
5359
5385
  if (runtime) {
5360
5386
  throw new InitializationError("Asiyst is already initialized");
5361
5387
  }
5388
+ if (typeof document === "undefined" || typeof window === "undefined") {
5389
+ throw new InitializationError("Asiyst SDK can only be initialized in a browser environment.");
5390
+ }
5362
5391
  const credentials = validateInitOptions(options);
5363
5392
  const doc = document;
5364
5393
  const win = window;