@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.js CHANGED
@@ -75,7 +75,7 @@ var ALL_ACTION_KINDS = [
75
75
  // src/core/constants.ts
76
76
  function resolveSdkVersion() {
77
77
  {
78
- return "0.1.28";
78
+ return "0.1.31";
79
79
  }
80
80
  }
81
81
  var SDK_VERSION = resolveSdkVersion();
@@ -94,7 +94,7 @@ var AVATAR_TARGET_GAP = 16;
94
94
  var WEBSITE_MAP_TEXT_LIMIT = 80;
95
95
  var CONFIG_CACHE_TTL_MS = 1e3 * 30;
96
96
  var CONFIG_REVALIDATION_INTERVAL_MS = 3e4;
97
- var HEARTBEAT_INTERVAL_MS = 45e3;
97
+ var HEARTBEAT_INTERVAL_MS = 3e5;
98
98
 
99
99
  // src/security/selectors.ts
100
100
  var DANGEROUS_SELECTOR = /javascript:|expression\(|@import|url\s*\(|behavior:|binding:|<script/i;
@@ -356,7 +356,8 @@ function parseAnimations(value) {
356
356
  clipName: typeof item.clipName === "string" ? sanitizeText(item.clipName, 64) : void 0,
357
357
  loopMode: typeof item.loopMode === "string" ? sanitizeText(item.loopMode, 32) : void 0,
358
358
  durationMs: typeof item.durationMs === "number" ? item.durationMs : void 0,
359
- assetUrl: typeof item.assetUrl === "string" ? item.assetUrl : null
359
+ assetUrl: typeof item.assetUrl === "string" ? item.assetUrl : null,
360
+ integrity: typeof item.integrity === "string" ? item.integrity : void 0
360
361
  });
361
362
  }
362
363
  }
@@ -383,6 +384,8 @@ function normalizeProjectConfig(raw) {
383
384
  ) || void 0;
384
385
  const assetUrl = typeof raw.assetUrl === "string" && raw.assetUrl ? raw.assetUrl : typeof rawAvatarRecord?.assetUrl === "string" && rawAvatarRecord.assetUrl ? rawAvatarRecord.assetUrl : typeof rawAvatarRecord?.modelUrl === "string" && rawAvatarRecord.modelUrl ? rawAvatarRecord.modelUrl : typeof rawConfigRecord?.assetUrl === "string" && rawConfigRecord.assetUrl ? rawConfigRecord.assetUrl : typeof rawManifestRecord?.assetUrl === "string" && rawManifestRecord.assetUrl ? rawManifestRecord.assetUrl : typeof rawManifestRecord?.modelUrl === "string" && rawManifestRecord.modelUrl ? rawManifestRecord.modelUrl : void 0;
385
386
  const thumbnailUrl = typeof raw.thumbnailUrl === "string" ? raw.thumbnailUrl : typeof rawAvatarRecord?.thumbnailUrl === "string" ? rawAvatarRecord.thumbnailUrl : typeof rawConfigRecord?.thumbnailUrl === "string" ? rawConfigRecord.thumbnailUrl : typeof rawManifestRecord?.thumbnailUrl === "string" ? rawManifestRecord.thumbnailUrl : rawAvatarRecord?.thumbnailUrl === null ? null : void 0;
387
+ const rawModelFormat = raw.modelFormat ?? rawAvatarRecord?.modelFormat ?? rawConfigRecord?.modelFormat ?? rawManifestRecord?.modelFormat;
388
+ const modelFormat = rawModelFormat === "fbx" || rawModelFormat === "glb" ? rawModelFormat : void 0;
386
389
  const publishedVersion = typeof raw.publishedVersion === "string" ? raw.publishedVersion : typeof rawAvatarRecord?.version === "string" ? rawAvatarRecord.version : typeof rawManifestRecord?.version === "string" ? rawManifestRecord.version : void 0;
387
390
  const animations = parseAnimations(
388
391
  raw.animations ?? rawAvatarRecord?.animations ?? rawConfigRecord?.animations
@@ -402,6 +405,8 @@ function normalizeProjectConfig(raw) {
402
405
  avatar,
403
406
  avatarId,
404
407
  assetUrl,
408
+ modelFormat,
409
+ assetIntegrity: typeof raw.assetIntegrity === "string" ? raw.assetIntegrity : typeof rawAvatarRecord?.assetIntegrity === "string" ? rawAvatarRecord.assetIntegrity : void 0,
405
410
  thumbnailUrl,
406
411
  publishedVersion,
407
412
  animations,
@@ -420,7 +425,8 @@ function normalizeProjectConfig(raw) {
420
425
  blockedRoutes: parseStringList(raw.blockedRoutes ?? raw.blocked_routes),
421
426
  rules: parseRules(raw.rules ?? raw.avatarRules),
422
427
  dataSources: parseDataSources(raw.dataSources ?? raw.enabledDataSources),
423
- elementSelectors: parseElementSelectors(raw.elementSelectors)
428
+ elementSelectors: parseElementSelectors(raw.elementSelectors),
429
+ maxMessageChars: asNumber(raw.maxMessageChars, 4e3, 1, 4e3)
424
430
  };
425
431
  }
426
432
  function validateInitOptions(options) {
@@ -504,7 +510,7 @@ var HttpTransport = class {
504
510
  return this.options.avatarId;
505
511
  }
506
512
  async request(req) {
507
- const url = `${this.options.apiBaseUrl.replace(/\/$/, "")}${req.path}`;
513
+ const url = /^https?:\/\//i.test(req.path) ? req.path : `${this.options.apiBaseUrl.replace(/\/$/, "")}${req.path}`;
508
514
  const requestId = req.requestId || generateRequestId();
509
515
  const timeoutMs = req.timeoutMs ?? this.options.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS;
510
516
  const isSafeOrIdempotent = req.method === "GET" || Boolean(req.idempotent);
@@ -532,36 +538,30 @@ var HttpTransport = class {
532
538
  }
533
539
  try {
534
540
  let response;
535
- try {
536
- response = await fetch(url, {
537
- method: req.method,
538
- headers: {
539
- Accept: "application/json",
540
- "Content-Type": "application/json",
541
- "X-Asiyst-Project-Id": this.options.projectId,
542
- "X-Asiyst-Public-Key": this.options.publicKey,
543
- ...this.options.avatarId ? { "X-Asiyst-Avatar-Id": this.options.avatarId } : {},
544
- "X-Asiyst-SDK-Version": SDK_VERSION,
545
- "X-Asiyst-Request-Id": requestId,
546
- ...req.sessionId ? { "X-Asiyst-Session-Id": req.sessionId } : {},
547
- ...req.conversationId ? { "X-Asiyst-Conversation-Id": req.conversationId } : {},
548
- ...req.authorizationToken ? { Authorization: `Bearer ${req.authorizationToken}` } : {}
549
- },
550
- body: req.body === void 0 ? void 0 : JSON.stringify(req.body),
551
- signal: controller.signal
552
- });
553
- } finally {
554
- clearTimeout(timeoutId);
555
- if (req.signal) {
556
- req.signal.removeEventListener("abort", onExternalAbort);
557
- }
558
- }
541
+ response = await fetch(url, {
542
+ method: req.method,
543
+ headers: req.headers ?? {
544
+ Accept: "application/json",
545
+ "Content-Type": "application/json",
546
+ "X-Asiyst-Project-Id": this.options.projectId,
547
+ "X-Asiyst-Public-Key": this.options.publicKey,
548
+ ...this.options.avatarId ? { "X-Asiyst-Avatar-Id": this.options.avatarId } : {},
549
+ "X-Asiyst-SDK-Version": SDK_VERSION,
550
+ "X-Asiyst-Request-Id": requestId,
551
+ ...req.sessionId ? { "X-Asiyst-Session-Id": req.sessionId } : {},
552
+ ...req.conversationId ? { "X-Asiyst-Conversation-Id": req.conversationId } : {},
553
+ ...req.authorizationToken ? { Authorization: `Bearer ${req.authorizationToken}` } : {}
554
+ },
555
+ body: req.body === void 0 ? void 0 : JSON.stringify(req.body),
556
+ signal: controller.signal
557
+ });
559
558
  if (isSafeOrIdempotent && attempt < maxRetries && [502, 503, 504].includes(response.status)) {
560
559
  continue;
561
560
  }
562
561
  if (response.status === 429 && isSafeOrIdempotent && attempt < maxRetries) {
563
562
  const retryAfterHeader = response.headers.get("retry-after");
564
563
  const retryAfterMs = retryAfterHeader ? Math.min(Number(retryAfterHeader) * 1e3 || 200, 1e3) : 100;
564
+ clearTimeout(timeoutId);
565
565
  await new Promise((resolve) => setTimeout(resolve, retryAfterMs));
566
566
  continue;
567
567
  }
@@ -571,33 +571,87 @@ var HttpTransport = class {
571
571
  try {
572
572
  data = await response.json();
573
573
  } catch {
574
+ if (timedOut) {
575
+ throw new NetworkError("Asiyst Cloud request timed out");
576
+ }
577
+ if (req.signal?.aborted) {
578
+ throw new NetworkError("Asiyst Cloud request was aborted");
579
+ }
574
580
  data = null;
575
581
  }
576
582
  }
577
583
  if (!response.ok) {
578
- return { ok: false, status: response.status, data };
584
+ return { ok: false, status: response.status, data, headers: response.headers };
579
585
  }
580
- return { ok: true, status: response.status, data };
586
+ return { ok: true, status: response.status, data, headers: response.headers };
581
587
  } catch (err) {
582
- clearTimeout(timeoutId);
583
- if (req.signal) {
584
- req.signal.removeEventListener("abort", onExternalAbort);
585
- }
586
588
  if (timedOut) {
587
589
  throw new NetworkError("Asiyst Cloud request timed out");
588
590
  }
591
+ if (req.signal?.aborted) {
592
+ throw new NetworkError("Asiyst Cloud request was aborted");
593
+ }
589
594
  lastError = err;
590
595
  if (isSafeOrIdempotent && attempt < maxRetries) {
591
596
  continue;
592
597
  }
593
598
  throw new NetworkError("Asiyst Cloud is unreachable");
599
+ } finally {
600
+ clearTimeout(timeoutId);
601
+ if (req.signal) {
602
+ req.signal.removeEventListener("abort", onExternalAbort);
603
+ }
594
604
  }
595
605
  }
596
606
  throw lastError instanceof Error ? lastError : new NetworkError("Asiyst Cloud is unreachable");
597
607
  }
598
608
  };
599
609
 
610
+ // ../api-contract.ts
611
+ var API_V1_BASE_PATH = "/api/v1";
612
+ var API_ROUTES = {
613
+ runtimeAvatar: "/runtime/avatar",
614
+ runtimeToken: "/sdk/runtime/token",
615
+ installationRegister: "/sdk/installations/register",
616
+ runtimeHeartbeat: "/sdk/heartbeat",
617
+ chat: "/conversations/messages",
618
+ projectApiKeyVerify: (projectId) => `/projects/${encodeURIComponent(projectId)}/api-key/verify`,
619
+ sdkInstallationVerify: "/sdk/installations/verify"
620
+ };
621
+ var API_LIMITS = {
622
+ configStaleIfErrorMs: 0,
623
+ maxMessageChars: 12e3,
624
+ pageUrlMaxChars: 2048};
625
+ function apiV1Path(route) {
626
+ return `${API_V1_BASE_PATH}${route.startsWith("/") ? route : `/${route}`}`;
627
+ }
628
+ function contractApiBaseUrl(configuredApiBaseUrl) {
629
+ const parsed = new URL(configuredApiBaseUrl);
630
+ if (parsed.pathname.replace(/\/+$/, "").endsWith("/functions/v1/api")) {
631
+ return "https://asiyst.com";
632
+ }
633
+ return parsed.origin;
634
+ }
635
+ function contractApiUrl(configuredApiBaseUrl, route) {
636
+ return `${contractApiBaseUrl(configuredApiBaseUrl).replace(/\/+$/, "")}${apiV1Path(route)}`;
637
+ }
638
+
600
639
  // src/communication/CloudClient.ts
640
+ function newRequestId() {
641
+ const cryptoApi = globalThis.crypto;
642
+ if (typeof cryptoApi?.randomUUID === "function") return cryptoApi.randomUUID();
643
+ if (typeof cryptoApi?.getRandomValues === "function") {
644
+ const bytes = cryptoApi.getRandomValues(new Uint8Array(16));
645
+ bytes[6] = (bytes[6] ?? 0) & 15 | 64;
646
+ bytes[8] = (bytes[8] ?? 0) & 63 | 128;
647
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
648
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
649
+ }
650
+ throw new ConfigurationError("Secure request identifiers are unavailable in this browser.");
651
+ }
652
+ function isUuid(value) {
653
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
654
+ }
601
655
  var CloudClient = class {
602
656
  constructor(transport, projectId, publicKey = "", runtimeAuth, sessionId, avatarId) {
603
657
  this.transport = transport;
@@ -605,6 +659,7 @@ var CloudClient = class {
605
659
  this.publicKey = publicKey;
606
660
  this.runtimeAuth = runtimeAuth;
607
661
  this.avatarId = avatarId;
662
+ this.configMetadata = {};
608
663
  this.inFlightConversations = /* @__PURE__ */ new Map();
609
664
  this.sessionId = sessionId;
610
665
  if (!this.avatarId && typeof transport.getAvatarId === "function") {
@@ -635,243 +690,152 @@ var CloudClient = class {
635
690
  }
636
691
  return DEFAULT_API_BASE_URL;
637
692
  }
638
- async getAuthToken(capability) {
693
+ async getAuthToken() {
639
694
  if (!this.runtimeAuth) return void 0;
640
695
  if (this.tokenRefreshPromise) return this.tokenRefreshPromise;
641
- if (!this.inFlightToken) {
642
- this.inFlightToken = this.runtimeAuth.getToken(capability).then((token) => {
643
- this.activeToken = token;
644
- return token;
645
- }).finally(() => {
646
- this.inFlightToken = void 0;
647
- });
648
- }
649
- return this.inFlightToken;
696
+ this.tokenRefreshPromise = this.runtimeAuth.getToken().then((token) => {
697
+ this.activeToken = token;
698
+ return token;
699
+ }).finally(() => {
700
+ this.tokenRefreshPromise = void 0;
701
+ });
702
+ return this.tokenRefreshPromise;
650
703
  }
651
- async fetchConfig() {
652
- const avatarParam = this.avatarId ? `?avatarId=${encodeURIComponent(this.avatarId)}` : "";
653
- const avatarAndKeyParams = `?projectId=${encodeURIComponent(this.projectId)}&publicKey=${encodeURIComponent(this.publicKey)}${this.avatarId ? `&avatarId=${encodeURIComponent(this.avatarId)}` : ""}`;
654
- const baseUrl = this.getApiBaseUrl();
655
- const resolveAssetUrls = (raw) => {
656
- let canonicalBase = "https://asiyst.com";
657
- try {
658
- if (baseUrl) {
659
- const u = new URL(baseUrl);
660
- canonicalBase = u.origin;
661
- }
662
- } catch {
663
- canonicalBase = "https://asiyst.com";
704
+ getConfigMetadata() {
705
+ return this.configMetadata;
706
+ }
707
+ async fetchConfig(etag, cachedConfig) {
708
+ const response = await this.transport.request({
709
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.runtimeAvatar),
710
+ method: "GET",
711
+ idempotent: true,
712
+ retries: 2,
713
+ headers: {
714
+ Accept: "application/json",
715
+ "X-Asiyst-Public-Key": this.publicKey,
716
+ "X-Asiyst-Project-Id": this.projectId,
717
+ ...this.avatarId ? { "X-Asiyst-Avatar-Id": this.avatarId } : {},
718
+ ...etag ? { "If-None-Match": etag } : {}
664
719
  }
665
- const toAbsolute = (url) => {
666
- if (typeof url === "string" && url.startsWith("/")) {
667
- return new URL(url, canonicalBase).href;
668
- }
669
- return url;
720
+ });
721
+ if (response.status === 304 && cachedConfig) {
722
+ this.configMetadata = {
723
+ etag: response.headers?.get("etag") ?? etag,
724
+ maxAgeMs: 0,
725
+ staleIfErrorMs: 0
670
726
  };
671
- if (raw.avatar && typeof raw.avatar === "object" && !Array.isArray(raw.avatar)) {
672
- const av = { ...raw.avatar };
673
- av.assetUrl = toAbsolute(av.assetUrl);
674
- av.thumbnailUrl = toAbsolute(av.thumbnailUrl);
675
- av.modelUrl = toAbsolute(av.modelUrl);
676
- av.manifestUrl = toAbsolute(av.manifestUrl);
677
- if (Array.isArray(av.animations)) {
678
- av.animations = av.animations.map((item) => {
679
- if (item && typeof item === "object") {
680
- const animObj = item;
681
- return { ...animObj, assetUrl: toAbsolute(animObj.assetUrl) };
682
- }
683
- return item;
684
- });
685
- }
686
- raw.avatar = av;
687
- }
688
- if (raw.config && typeof raw.config === "object" && !Array.isArray(raw.config)) {
689
- const cfg = { ...raw.config };
690
- cfg.assetUrl = toAbsolute(cfg.assetUrl);
691
- cfg.thumbnailUrl = toAbsolute(cfg.thumbnailUrl);
692
- cfg.manifestUrl = toAbsolute(cfg.manifestUrl);
693
- raw.config = cfg;
694
- }
695
- if (raw.manifest && typeof raw.manifest === "object" && !Array.isArray(raw.manifest)) {
696
- const mf = { ...raw.manifest };
697
- mf.assetUrl = toAbsolute(mf.assetUrl);
698
- mf.thumbnailUrl = toAbsolute(mf.thumbnailUrl);
699
- mf.modelUrl = toAbsolute(mf.modelUrl);
700
- raw.manifest = mf;
701
- }
702
- raw.assetUrl = toAbsolute(raw.assetUrl);
703
- raw.thumbnailUrl = toAbsolute(raw.thumbnailUrl);
704
- raw.manifestUrl = toAbsolute(raw.manifestUrl);
705
- if (raw.branding && typeof raw.branding === "object" && !Array.isArray(raw.branding)) {
706
- const br = { ...raw.branding };
707
- br.siteLogoUrl = toAbsolute(br.siteLogoUrl);
708
- raw.branding = br;
709
- }
710
- return raw;
711
- };
712
- let lastError;
713
- try {
714
- const response = await this.runtimeRequest({
715
- path: `/projects/${encodeURIComponent(this.projectId)}/avatar${avatarParam}`,
716
- method: "GET",
717
- idempotent: true
718
- });
719
- if (response.ok && response.data) {
720
- const fullData = response.data && typeof response.data === "object" && !Array.isArray(response.data) ? {
721
- ...response.data,
722
- ...response.data.config && typeof response.data.config === "object" ? response.data.config : {}
723
- } : {};
724
- return normalizeProjectConfig(resolveAssetUrls(fullData));
725
- }
726
- if (response.status === 404) {
727
- lastError = new ConfigurationError(`Project ${this.projectId} or avatar configuration not found`);
728
- }
729
- } catch (err) {
730
- if (err instanceof Error) lastError = err;
727
+ return cachedConfig;
731
728
  }
732
- try {
733
- const runtimeResponse = await this.runtimeRequest({
734
- path: `/api/v1/runtime/avatar${avatarAndKeyParams}`,
735
- method: "GET",
736
- idempotent: true
737
- });
738
- if (runtimeResponse.ok && runtimeResponse.data) {
739
- return normalizeProjectConfig(resolveAssetUrls(runtimeResponse.data));
740
- }
741
- if (runtimeResponse.status === 404) {
742
- lastError = new ConfigurationError(`Avatar ${this.avatarId ?? "active"} not found for project ${this.projectId}`);
743
- }
744
- } catch (err) {
745
- if (err instanceof Error) lastError = err;
746
- }
747
- try {
748
- const webBase = baseUrl.includes("localhost") || baseUrl.includes("127.0.0.1") ? baseUrl.replace(/\/functions\/v1.*$/, "").replace(/\/api\/v1.*$/, "") : "https://asiyst.com";
749
- const fullUrl = `${webBase.replace(/\/$/, "")}/api/v1/runtime/avatar${avatarAndKeyParams}`;
750
- const res = await fetch(fullUrl, {
751
- headers: {
752
- Accept: "application/json",
753
- "x-asiyst-public-key": this.publicKey
754
- }
755
- });
756
- if (res.ok) {
757
- const body = await res.json();
758
- if (body && typeof body === "object") {
759
- return normalizeProjectConfig(resolveAssetUrls(body));
760
- }
761
- } else {
762
- const errorBody = await res.json().catch(() => ({}));
763
- const errObj = errorBody?.error ?? errorBody;
764
- const code = String(errObj?.code ?? "");
765
- const message = String(errObj?.message ?? `HTTP ${res.status}`);
766
- if (res.status === 404) {
767
- throw new ConfigurationError(code === "AVATAR_NOT_FOUND" ? `Requested avatar not found for project ${this.projectId}` : `Project ${this.projectId} not found`);
768
- } else if (res.status === 401 || res.status === 403) {
769
- throw new AuthenticationError("Asiyst credentials unauthorized for this avatar configuration");
770
- } else if (res.status >= 500) {
771
- throw new NetworkError(`Asiyst Cloud avatar service error (${res.status}): ${message}`);
772
- }
773
- }
774
- } catch (err) {
775
- if (err instanceof ConfigurationError || err instanceof AuthenticationError || err instanceof NetworkError) {
776
- throw err;
729
+ if (!response.ok || !response.data) {
730
+ const body = response.data;
731
+ const code = body?.error?.code ?? `HTTP_${response.status}`;
732
+ if (response.status === 401 || response.status === 403) {
733
+ throw new AuthenticationError(body?.error?.message ?? `Asiyst runtime avatar configuration was rejected (${code}).`);
777
734
  }
778
- if (err instanceof Error) lastError = err;
779
- }
780
- if (lastError) {
781
- throw lastError;
782
- }
783
- throw new ConfigurationError(`Failed to resolve avatar configuration for project ${this.projectId}`);
735
+ throw new NetworkError(body?.error?.message ?? `Asiyst runtime avatar configuration is unavailable (${code}).`);
736
+ }
737
+ const data = response.data;
738
+ if (data.success !== true || data.projectId !== this.projectId || typeof data.avatarId !== "string" || !data.config || typeof data.config !== "object" || Array.isArray(data.config)) {
739
+ throw new ConfigurationError("Asiyst returned an invalid runtime configuration response.");
740
+ }
741
+ const rawConfig = data.config;
742
+ const rawAvatar = data.avatar && typeof data.avatar === "object" ? data.avatar : {};
743
+ const manifest = data.manifest && typeof data.manifest === "object" ? data.manifest : {};
744
+ const modelFormat = [data.format, data.modelFormat, rawConfig.modelFormat, rawAvatar.modelFormat].find((format) => typeof format === "string");
745
+ if (modelFormat && modelFormat !== "fbx" && modelFormat !== "glb") {
746
+ throw new ConfigurationError(`Asiyst returned an unsupported avatar format: ${modelFormat}.`);
747
+ }
748
+ const assetUrl = typeof rawConfig.assetUrl === "string" ? rawConfig.assetUrl : typeof rawAvatar.assetUrl === "string" ? rawAvatar.assetUrl : typeof rawAvatar.modelUrl === "string" ? rawAvatar.modelUrl : typeof manifest.assetUrl === "string" ? manifest.assetUrl : void 0;
749
+ const animations = Array.isArray(rawConfig.animations) ? rawConfig.animations : Array.isArray(data.animations) ? data.animations : Array.isArray(rawAvatar.animations) ? rawAvatar.animations : [];
750
+ const revision = typeof data.configRevision === "string" ? data.configRevision : typeof data.publishedVersionId === "string" ? data.publishedVersionId : "0";
751
+ const version = Number.parseInt(revision, 10);
752
+ const config = normalizeProjectConfig({
753
+ ...rawConfig,
754
+ avatarId: data.avatarId,
755
+ avatarName: typeof rawAvatar.name === "string" ? rawAvatar.name : rawConfig.avatarName,
756
+ assetUrl,
757
+ modelFormat,
758
+ publishedVersion: typeof data.publishedVersionId === "string" ? data.publishedVersionId : revision,
759
+ version: Number.isFinite(version) ? version : 0,
760
+ animations,
761
+ theme: rawConfig.theme ?? rawAvatar.theme,
762
+ personality: rawConfig.personality,
763
+ behavior: rawConfig.behavior ?? rawAvatar.behavior,
764
+ maxMessageChars: API_LIMITS.maxMessageChars
765
+ });
766
+ this.configMetadata = {
767
+ etag: response.headers?.get("etag") ?? void 0,
768
+ maxAgeMs: 0,
769
+ staleIfErrorMs: 0
770
+ };
771
+ return config;
784
772
  }
785
773
  async heartbeat(metadata) {
786
- let response = await this.runtimeRequest({
787
- path: "/sdk/heartbeat",
774
+ const response = await this.runtimeRequest({
775
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.runtimeHeartbeat),
788
776
  method: "POST",
789
- idempotent: true,
777
+ canonical: true,
790
778
  body: {
791
- project_id: this.projectId,
792
- public_key: this.publicKey,
793
- sdk_version: SDK_VERSION,
794
- origin: metadata.origin,
795
- environment: metadata.environment,
796
- timestamp: metadata.timestamp
779
+ projectId: this.projectId,
780
+ publicKey: this.publicKey,
781
+ sdkVersion: metadata.sdkVersion,
782
+ environment: metadata.environment
797
783
  }
798
784
  }, "assistant:heartbeat");
799
- if (response.status === 404) {
800
- response = await this.runtimeRequest({
801
- path: "/api/v1/sdk/heartbeat",
802
- method: "POST",
803
- idempotent: true,
804
- body: {
805
- project_id: this.projectId,
806
- public_key: this.publicKey,
807
- sdk_version: SDK_VERSION,
808
- origin: metadata.origin,
809
- environment: metadata.environment,
810
- timestamp: metadata.timestamp
811
- }
812
- }, "assistant:heartbeat");
813
- }
814
- const body = response.data && typeof response.data === "object" && !Array.isArray(response.data) ? response.data : void 0;
815
- const rawStatus = body?.status ?? body?.connectionStatus ?? body?.verificationStatus ?? (body?.verified === true ? "verified" : void 0);
816
- const verificationStatus = rawStatus === "connected" || rawStatus === "verified" || rawStatus === "inactive" || rawStatus === "not_detected" || rawStatus === "error" ? rawStatus : void 0;
817
- const versionOutdated = body?.versionOutdated === true || body?.sdkVersionOutdated === true || rawStatus === "outdated";
785
+ const body = response.data;
786
+ const validResponse = body?.success === true && body.data?.connected === true && body.data.projectId === this.projectId && typeof body.data.versionOutdated === "boolean";
818
787
  return {
819
- ok: response.ok && (verificationStatus === void 0 || verificationStatus === "connected" || verificationStatus === "verified"),
820
- status: response.status,
821
- verificationStatus,
822
- versionOutdated
788
+ ok: response.ok && response.status === 202 && validResponse,
789
+ status: response.status
823
790
  };
824
791
  }
825
792
  async registerInstallation(registration) {
826
- let response = await this.transport.request({
827
- path: "/sdk/installations/register",
793
+ const response = await this.transport.request({
794
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.installationRegister),
828
795
  method: "POST",
829
- body: registration,
830
- idempotent: true,
831
- sessionId: this.sessionId
796
+ headers: {
797
+ Accept: "application/json",
798
+ "Content-Type": "application/json",
799
+ "X-Asiyst-SDK-Version": registration.sdkVersion
800
+ },
801
+ body: {
802
+ projectId: registration.projectId,
803
+ publicKey: registration.publicKey,
804
+ installationId: registration.installationId,
805
+ origin: registration.origin,
806
+ environment: registration.environment,
807
+ sdkVersion: registration.sdkVersion
808
+ }
832
809
  });
833
- if (response.status === 404) {
834
- response = await this.transport.request({
835
- path: "/api/v1/sdk/installations/register",
836
- method: "POST",
837
- body: registration,
838
- idempotent: true,
839
- sessionId: this.sessionId
840
- });
841
- }
842
- if (!response.ok) {
843
- throw new NetworkError(`SDK installation registration failed (${response.status}).`);
810
+ const body = response.data;
811
+ if (!response.ok || body?.success !== true || body.data?.registered !== true || typeof body.data.installationId !== "string" || body.data.projectId !== registration.projectId || body.data.status === "revoked") {
812
+ const error = response.data && typeof response.data === "object" ? response.data.error : void 0;
813
+ if (response.status === 403 || body?.data?.status === "revoked") {
814
+ throw new AuthenticationError(error?.message ?? `SDK installation is not authorized (${error?.code ?? response.status}).`);
815
+ }
816
+ throw new NetworkError(error?.message ?? `SDK installation registration failed (${response.status}).`);
844
817
  }
845
- return response.data ?? {};
818
+ return body;
846
819
  }
847
820
  async requestTask(userText, pageUrl) {
848
- const response = await this.runtimeRequest({
849
- path: "/tasks",
850
- method: "POST",
851
- body: {
852
- projectId: this.projectId,
853
- text: userText,
854
- pageUrl
855
- }
856
- }, "assistant:conversation");
857
- if (!response.ok || !response.data?.task?.id || !Array.isArray(response.data.task.steps)) {
858
- throw new NetworkError("Task planning is unavailable");
859
- }
860
- return response.data.task;
821
+ throw new ConfigurationError("Cloud task planning is not defined by the approved SDK API contract.");
861
822
  }
862
823
  async fetchWorkflow(workflowId) {
863
- const response = await this.runtimeRequest({
864
- path: `/workflows/${encodeURIComponent(workflowId)}`,
865
- method: "GET",
866
- idempotent: true
867
- }, "assistant:conversation");
868
- if (!response.ok || !response.data?.workflow?.id || !Array.isArray(response.data.workflow.steps)) {
869
- throw new NetworkError("Workflow is unavailable");
870
- }
871
- return response.data.workflow;
824
+ throw new ConfigurationError("Cloud workflows are not defined by the approved SDK API contract.");
872
825
  }
873
- async sendConversationMessage(text, pageUrl) {
826
+ async sendConversationMessage(text, pageUrl, maxMessageChars = API_LIMITS.maxMessageChars) {
874
827
  const trimmed = text.trim();
828
+ if (!trimmed) throw new ConfigurationError("Message cannot be empty.");
829
+ if (trimmed.length > maxMessageChars) {
830
+ throw new ConfigurationError(`Message exceeds the ${maxMessageChars}-character limit.`);
831
+ }
832
+ if (pageUrl.length > API_LIMITS.pageUrlMaxChars) {
833
+ throw new ConfigurationError("Page URL exceeds the supported length.");
834
+ }
835
+ const sessionId = this.sessionId ?? newRequestId();
836
+ if (sessionId.length < 16 || sessionId.length > 128 || !/^[A-Za-z0-9_-]+$/.test(sessionId)) {
837
+ throw new ConfigurationError("Visitor session ID must be an opaque 16-128 character identifier.");
838
+ }
875
839
  const dedupeKey2 = `${this.conversationId ?? ""}:${trimmed}:${pageUrl}`;
876
840
  const existing = this.inFlightConversations.get(dedupeKey2);
877
841
  if (existing) {
@@ -879,19 +843,87 @@ var CloudClient = class {
879
843
  }
880
844
  const conversationPromise = (async () => {
881
845
  try {
846
+ const requestConversationId = this.conversationId && isUuid(this.conversationId) ? this.conversationId : void 0;
882
847
  const response = await this.runtimeRequest({
883
- path: "/conversations/messages",
848
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.chat),
884
849
  method: "POST",
885
- body: { projectId: this.projectId, text: trimmed, pageUrl },
886
- conversationId: this.conversationId
850
+ body: {
851
+ projectId: this.projectId,
852
+ text: trimmed,
853
+ ...requestConversationId ? { conversationId: requestConversationId } : {},
854
+ sessionId,
855
+ pageUrl
856
+ }
887
857
  }, "assistant:conversation");
888
- if (!response.ok || !response.data?.message?.text) {
889
- if (response.status === 401 || response.status === 403) {
890
- throw new NetworkError("AI request authorization failed. The project credentials may be inactive, revoked, or inaccessible.");
858
+ if (response.ok && response.data?.success === true) {
859
+ const body = response.data;
860
+ const message = body.message && typeof body.message === "object" ? body.message : void 0;
861
+ const conversationId = body.conversationId;
862
+ const messageText = message?.text ?? body.response ?? body.answer;
863
+ if (body.success !== true || typeof conversationId !== "string" || typeof messageText !== "string" || !messageText.trim() || message && message.role !== "assistant") {
864
+ throw new NetworkError("Asiyst returned an unsupported conversation response.");
891
865
  }
892
- throw new NetworkError("Conversation service is unavailable");
866
+ this.conversationId = conversationId;
867
+ const rawCitations = Array.isArray(body.sources) ? body.sources : [];
868
+ return {
869
+ requestId: typeof body.requestId === "string" ? body.requestId : void 0,
870
+ conversationId,
871
+ message: {
872
+ ...typeof message?.id === "string" ? { id: message.id } : {},
873
+ role: "assistant",
874
+ text: messageText
875
+ },
876
+ citations: rawCitations.flatMap((citation) => {
877
+ if (!citation || typeof citation !== "object") return [];
878
+ const item = citation;
879
+ const sourceId = item.source_id ?? item.id;
880
+ if (typeof sourceId !== "string" || typeof item.title !== "string") return [];
881
+ return [{
882
+ sourceId,
883
+ title: item.title,
884
+ ...typeof item.url === "string" ? { url: item.url } : {}
885
+ }];
886
+ }),
887
+ finishReason: void 0,
888
+ createdAt: void 0
889
+ };
890
+ }
891
+ const errorRecord = response.data && typeof response.data === "object" ? response.data.error : void 0;
892
+ const errorBody = errorRecord && typeof errorRecord === "object" ? errorRecord : void 0;
893
+ const code = typeof errorBody?.code === "string" ? errorBody.code : typeof errorRecord === "string" ? errorRecord : `HTTP_${response.status}`;
894
+ if (response.status === 401 || response.status === 403) {
895
+ const installationErrorCodes = {
896
+ INSTALLATION_NOT_FOUND: "Asiyst installation not found for this domain. Re-run `asiyst connect` and verify your project domain.",
897
+ INSTALLATION_INACTIVE: "Asiyst installation is inactive. Check your project status in the Asiyst dashboard.",
898
+ INSTALLATION_REVOKED: "Asiyst installation has been revoked. Re-run `asiyst connect` to register a new installation.",
899
+ INSTALLATION_PROJECT_MISMATCH: "Asiyst installation does not match the configured project.",
900
+ INSTALLATION_DOMAIN_MISMATCH: "Asiyst installation domain does not match the current website domain.",
901
+ RUNTIME_TOKEN_INVALID: "Asiyst runtime authorization token is invalid. The SDK will attempt to re-authorize.",
902
+ RUNTIME_TOKEN_EXPIRED: "Asiyst runtime authorization token has expired. The SDK will re-authorize."
903
+ };
904
+ const knownMessage = typeof code === "string" ? installationErrorCodes[code] : void 0;
905
+ if (knownMessage) {
906
+ throw new AuthenticationError(knownMessage);
907
+ }
908
+ throw new AuthenticationError(
909
+ typeof errorBody?.message === "string" ? `Asiyst runtime authorization rejected: ${errorBody.message}` : "Asiyst runtime authorization was rejected."
910
+ );
911
+ }
912
+ if (response.status === 429) {
913
+ throw new NetworkError("The assistant is rate limited. Wait before sending another message.");
914
+ }
915
+ if (response.status === 409) {
916
+ throw new NetworkError(`The conversation request conflicted (${code}); it was not retried.`);
893
917
  }
894
- return response.data;
918
+ if (response.status === 504 || code === "AI_PROVIDER_TIMEOUT") {
919
+ throw new NetworkError("The assistant timed out. The request was not retried to avoid duplicate work.");
920
+ }
921
+ if (code === "assistant_unavailable") {
922
+ throw new NetworkError("The assistant is temporarily unavailable.");
923
+ }
924
+ throw new NetworkError(
925
+ typeof errorBody?.message === "string" ? errorBody.message : typeof response.data?.message === "string" ? response.data.message : "Conversation service is unavailable."
926
+ );
895
927
  } finally {
896
928
  this.inFlightConversations.delete(dedupeKey2);
897
929
  }
@@ -900,63 +932,16 @@ var CloudClient = class {
900
932
  return conversationPromise;
901
933
  }
902
934
  async sendWebsiteMap(snapshot) {
903
- await this.safePost("/website-maps", snapshot);
935
+ throw new ConfigurationError("Website-map upload is not defined by the approved SDK API contract.");
904
936
  }
905
937
  async sendAnalytics(events) {
906
- await this.safePost("/analytics", { events });
938
+ throw new ConfigurationError("Analytics upload is not defined by the approved SDK API contract.");
907
939
  }
908
940
  async sendTelemetryEvent(eventType, metadata = {}) {
909
- try {
910
- const origin = typeof window !== "undefined" ? window.location.origin : void 0;
911
- const installationId = this.runtimeAuth ? this.runtimeAuth.options?.installationId : void 0;
912
- const sanitizedMeta = {
913
- sdkVersion: SDK_VERSION
914
- };
915
- for (const [key, val] of Object.entries(metadata)) {
916
- if (/(token|secret|cookie|session|api.?key|password|bearer|authorization)/i.test(key)) {
917
- continue;
918
- }
919
- if (typeof val === "string") {
920
- sanitizedMeta[key] = sanitizeText(val, 512);
921
- } else if (typeof val === "number" || typeof val === "boolean") {
922
- sanitizedMeta[key] = val;
923
- } else if (val && typeof val === "object" && !Array.isArray(val)) {
924
- sanitizedMeta[key] = val;
925
- }
926
- }
927
- const payload = {
928
- projectId: this.projectId,
929
- publicKey: this.publicKey,
930
- eventType,
931
- installationId,
932
- origin,
933
- metadata: sanitizedMeta
934
- };
935
- const baseUrl = this.getApiBaseUrl();
936
- const targetUrl = baseUrl.includes("localhost") || baseUrl.includes("127.0.0.1") ? `${baseUrl.replace(/\/functions\/v1.*$/, "").replace(/\/api\/v1.*$/, "")}/api/v1/events` : "https://asiyst.com/api/v1/events";
937
- await fetch(targetUrl, {
938
- method: "POST",
939
- headers: {
940
- "Content-Type": "application/json",
941
- Accept: "application/json",
942
- "x-asiyst-public-key": this.publicKey
943
- },
944
- body: JSON.stringify(payload)
945
- });
946
- } catch {
947
- }
941
+ throw new ConfigurationError("Telemetry upload is not defined by the approved SDK API contract.");
948
942
  }
949
943
  async sendTaskUpdate(taskId, status, stepId) {
950
- await this.safePost(`/tasks/${encodeURIComponent(taskId)}/events`, {
951
- status,
952
- stepId
953
- });
954
- }
955
- async safePost(path, body) {
956
- try {
957
- await this.runtimeRequest({ path, method: "POST", body, idempotent: true }, "assistant:telemetry");
958
- } catch {
959
- }
944
+ throw new ConfigurationError("Cloud task updates are not defined by the approved SDK API contract.");
960
945
  }
961
946
  async runtimeRequest(request, capability = "assistant:config") {
962
947
  const fullRequest = {
@@ -965,14 +950,32 @@ var CloudClient = class {
965
950
  conversationId: request.conversationId ?? this.conversationId
966
951
  };
967
952
  if (!this.runtimeAuth) {
953
+ if (capability === "assistant:conversation" || capability === "assistant:heartbeat") {
954
+ throw new AuthenticationError("AI request authorization failed because no runtime token is available.");
955
+ }
968
956
  return this.transport.request(fullRequest);
969
957
  }
970
- let token = await this.getAuthToken(capability);
971
- let response = await this.transport.request({ ...fullRequest, authorizationToken: token });
958
+ let token = await this.getAuthToken();
959
+ const withToken = (value) => {
960
+ const headers = new Headers({
961
+ Accept: "application/json",
962
+ "Content-Type": "application/json"
963
+ });
964
+ if (fullRequest.headers) {
965
+ new Headers(fullRequest.headers).forEach((headerValue, key) => headers.set(key, headerValue));
966
+ }
967
+ if (value) headers.set("Authorization", `Bearer ${value}`);
968
+ return this.transport.request({
969
+ ...fullRequest,
970
+ headers,
971
+ canonical: true
972
+ });
973
+ };
974
+ let response = await withToken(token);
972
975
  if (response.status === 401) {
973
976
  if (!this.tokenRefreshPromise) {
974
977
  this.runtimeAuth.invalidate();
975
- this.tokenRefreshPromise = this.runtimeAuth.getToken(capability).then((newToken) => {
978
+ this.tokenRefreshPromise = this.runtimeAuth.getToken().then((newToken) => {
976
979
  this.activeToken = newToken;
977
980
  return newToken;
978
981
  }).finally(() => {
@@ -982,7 +985,7 @@ var CloudClient = class {
982
985
  });
983
986
  }
984
987
  token = await this.tokenRefreshPromise ?? this.activeToken;
985
- response = await this.transport.request({ ...fullRequest, authorizationToken: token });
988
+ response = await withToken(token);
986
989
  }
987
990
  return response;
988
991
  }
@@ -1049,7 +1052,8 @@ var ConfigCache = class {
1049
1052
  if (parsed.schemaVersion !== CONFIG_SCHEMA_VERSION || parsed.projectId !== projectId) {
1050
1053
  return null;
1051
1054
  }
1052
- if (!ignoreTtl && Date.now() - parsed.fetchedAt > CONFIG_CACHE_TTL_MS) {
1055
+ const maxAgeMs = parsed.maxAgeMs ?? CONFIG_CACHE_TTL_MS;
1056
+ if (!ignoreTtl && Date.now() - parsed.fetchedAt > maxAgeMs) {
1053
1057
  return null;
1054
1058
  }
1055
1059
  return normalizeProjectConfig(parsed.config);
@@ -1079,6 +1083,8 @@ var ConfigCache = class {
1079
1083
  fetchedAt: Date.now(),
1080
1084
  etag: meta?.etag,
1081
1085
  revision: meta?.revision ?? config.version,
1086
+ maxAgeMs: meta?.maxAgeMs,
1087
+ staleIfErrorMs: meta?.staleIfErrorMs,
1082
1088
  config
1083
1089
  };
1084
1090
  this.storage.write("config", JSON.stringify(envelope));
@@ -1120,19 +1126,26 @@ var ConfigManager = class {
1120
1126
  async executeRefresh(_options) {
1121
1127
  const prev = this.current;
1122
1128
  try {
1123
- const remote = await this.cloud.fetchConfig();
1124
- const normalized = normalizeProjectConfig(remote);
1129
+ const cached = this.cache.getEnvelope(this.options.projectId);
1130
+ const normalized = normalizeProjectConfig(await this.cloud.fetchConfig(cached?.etag, cached?.config));
1131
+ const receivedMetadata = this.cloud.getConfigMetadata?.() ?? {};
1132
+ const metadata = {
1133
+ ...receivedMetadata,
1134
+ maxAgeMs: receivedMetadata.maxAgeMs ?? cached?.maxAgeMs,
1135
+ staleIfErrorMs: receivedMetadata.staleIfErrorMs ?? cached?.staleIfErrorMs
1136
+ };
1125
1137
  this.current = normalized;
1126
- this.cache.write(this.options.projectId, normalized);
1138
+ this.cache.write(this.options.projectId, normalized, metadata);
1127
1139
  const hasChanged = prev.version !== normalized.version || prev.avatarName !== normalized.avatarName || prev.position !== normalized.position || prev.size !== normalized.size || prev.assetUrl !== normalized.assetUrl || prev.thumbnailUrl !== normalized.thumbnailUrl || JSON.stringify(prev.theme) !== JSON.stringify(normalized.theme) || JSON.stringify(prev.animations) !== JSON.stringify(normalized.animations);
1128
1140
  if (hasChanged && this.onConfigUpdated) {
1129
1141
  this.onConfigUpdated(normalized, prev);
1130
1142
  }
1131
1143
  return this.current;
1132
1144
  } catch (error) {
1133
- const lastKnownGood = this.cache.read(this.options.projectId, true);
1134
- if (lastKnownGood) {
1135
- this.current = lastKnownGood;
1145
+ const cached = this.cache.getEnvelope(this.options.projectId);
1146
+ const staleIfErrorMs = cached?.staleIfErrorMs ?? API_LIMITS.configStaleIfErrorMs;
1147
+ if (cached && staleIfErrorMs > 0 && Date.now() - cached.fetchedAt <= staleIfErrorMs) {
1148
+ this.current = normalizeProjectConfig(cached.config);
1136
1149
  }
1137
1150
  this.events.emit("asiyst:error", {
1138
1151
  code: "config_refresh_failed",
@@ -1809,7 +1822,7 @@ var CHUNK_TYPE_JSON = 1313821514;
1809
1822
  var CHUNK_TYPE_BIN = 5130562;
1810
1823
  var AssetLoader = class {
1811
1824
  constructor() {
1812
- this.inFlightController = null;
1825
+ this.inFlightControllers = /* @__PURE__ */ new Set();
1813
1826
  this.createdObjectUrls = [];
1814
1827
  this.inFlightLoads = /* @__PURE__ */ new Map();
1815
1828
  this.cachedAssets = /* @__PURE__ */ new Map();
@@ -1819,31 +1832,42 @@ var AssetLoader = class {
1819
1832
  if (!sanitizedUrl) {
1820
1833
  throw new Error("Asset URL is required");
1821
1834
  }
1822
- const cached = this.cachedAssets.get(sanitizedUrl);
1835
+ let parsedUrl;
1836
+ try {
1837
+ parsedUrl = new URL(sanitizedUrl, typeof location === "undefined" ? void 0 : location.href);
1838
+ } catch {
1839
+ throw new Error("Avatar asset URL is invalid");
1840
+ }
1841
+ if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:" || parsedUrl.username || parsedUrl.password) {
1842
+ throw new Error("Avatar asset URL must use HTTP or HTTPS without embedded credentials");
1843
+ }
1844
+ const cacheKey = `${sanitizedUrl}\0${options?.integrity ?? ""}\0${options?.expectedFormat ?? ""}`;
1845
+ const cached = this.cachedAssets.get(cacheKey);
1823
1846
  if (cached) {
1824
1847
  return cached;
1825
1848
  }
1826
- const inFlight = this.inFlightLoads.get(sanitizedUrl);
1849
+ const inFlight = this.inFlightLoads.get(cacheKey);
1827
1850
  if (inFlight) {
1828
1851
  return inFlight;
1829
1852
  }
1830
1853
  const loadPromise = this.performLoad(sanitizedUrl, options);
1831
- this.inFlightLoads.set(sanitizedUrl, loadPromise);
1854
+ this.inFlightLoads.set(cacheKey, loadPromise);
1832
1855
  try {
1833
1856
  const asset = await loadPromise;
1834
- this.cachedAssets.set(sanitizedUrl, asset);
1857
+ this.cachedAssets.set(cacheKey, asset);
1835
1858
  return asset;
1836
1859
  } finally {
1837
- this.inFlightLoads.delete(sanitizedUrl);
1860
+ this.inFlightLoads.delete(cacheKey);
1838
1861
  }
1839
1862
  }
1840
1863
  async performLoad(sanitizedUrl, options) {
1841
1864
  const startTime = Date.now();
1842
- this.inFlightController = new AbortController();
1843
- const abortSignal = options?.signal ? anySignal([this.inFlightController.signal, options.signal]) : this.inFlightController.signal;
1865
+ const controller = new AbortController();
1866
+ this.inFlightControllers.add(controller);
1867
+ const abortSignal = options?.signal ? anySignal([controller.signal, options.signal]) : controller.signal;
1844
1868
  const timeoutMs = options?.timeoutMs ?? 6e4;
1845
1869
  const timeoutId = setTimeout(() => {
1846
- this.inFlightController?.abort();
1870
+ controller.abort();
1847
1871
  }, timeoutMs);
1848
1872
  try {
1849
1873
  const cleanPath = (sanitizedUrl.split("?")[0] ?? "").toLowerCase();
@@ -1917,12 +1941,25 @@ var AssetLoader = class {
1917
1941
  if (arrayBuffer.byteLength < 12) {
1918
1942
  throw new Error("Avatar asset payload is too small to be a valid 3D container");
1919
1943
  }
1944
+ if (options?.integrity) {
1945
+ await verifyIntegrity(arrayBuffer, options.integrity);
1946
+ }
1920
1947
  const headerBytes = new Uint8Array(arrayBuffer, 0, Math.min(256, arrayBuffer.byteLength));
1921
1948
  const headerStr = new TextDecoder("utf-8", { fatal: false }).decode(headerBytes).trim();
1922
1949
  if (/^<!DOCTYPE\s+html/i.test(headerStr) || /^<html/i.test(headerStr)) {
1923
1950
  throw new Error(`Avatar asset payload contains HTML error page instead of binary 3D container from ${sanitizedUrl}`);
1924
1951
  }
1925
- if (isFbxExtension || this.isFbxBuffer(arrayBuffer) || !isGlbExtension && !this.isGlbBuffer(arrayBuffer)) {
1952
+ const hasFbxSignature = this.isFbxBuffer(arrayBuffer);
1953
+ const hasGlbSignature = this.isGlbBuffer(arrayBuffer);
1954
+ const isFbx = hasFbxSignature || !hasGlbSignature && isFbxExtension;
1955
+ const isGlb = hasGlbSignature || !hasFbxSignature && isGlbExtension;
1956
+ if (isFbx && isGlb) {
1957
+ throw new Error("Avatar asset format is ambiguous");
1958
+ }
1959
+ if (isFbx) {
1960
+ if (options?.expectedFormat && options.expectedFormat !== "fbx") {
1961
+ throw new Error(`Avatar asset format mismatch: expected ${options.expectedFormat}, received fbx`);
1962
+ }
1926
1963
  const fbxHeader = this.parseFbxHeader(arrayBuffer);
1927
1964
  const resourcePath = sanitizedUrl.includes("/") ? sanitizedUrl.substring(0, sanitizedUrl.lastIndexOf("/") + 1) : "";
1928
1965
  return {
@@ -1935,10 +1972,17 @@ var AssetLoader = class {
1935
1972
  durationMs: Date.now() - startTime
1936
1973
  };
1937
1974
  }
1975
+ if (!isGlb) {
1976
+ throw new Error("Avatar asset format is unsupported; expected FBX or GLB");
1977
+ }
1978
+ if (options?.expectedFormat && options.expectedFormat !== "glb") {
1979
+ throw new Error(`Avatar asset format mismatch: expected ${options.expectedFormat}, received glb`);
1980
+ }
1938
1981
  const parsedGlb = this.parseGlb(arrayBuffer);
1939
1982
  return {
1940
1983
  format: "glb",
1941
1984
  url: sanitizedUrl,
1985
+ buffer: arrayBuffer,
1942
1986
  json: parsedGlb.json,
1943
1987
  bin: parsedGlb.bin,
1944
1988
  meshes: parsedGlb.meshes,
@@ -1947,7 +1991,7 @@ var AssetLoader = class {
1947
1991
  };
1948
1992
  } finally {
1949
1993
  clearTimeout(timeoutId);
1950
- this.inFlightController = null;
1994
+ this.inFlightControllers.delete(controller);
1951
1995
  }
1952
1996
  }
1953
1997
  isFbxBuffer(buffer) {
@@ -2163,10 +2207,8 @@ var AssetLoader = class {
2163
2207
  };
2164
2208
  }
2165
2209
  destroy() {
2166
- if (this.inFlightController) {
2167
- this.inFlightController.abort();
2168
- this.inFlightController = null;
2169
- }
2210
+ for (const controller of this.inFlightControllers) controller.abort();
2211
+ this.inFlightControllers.clear();
2170
2212
  this.inFlightLoads.clear();
2171
2213
  this.cachedAssets.clear();
2172
2214
  if (typeof URL !== "undefined" && typeof URL.revokeObjectURL === "function") {
@@ -2180,6 +2222,20 @@ var AssetLoader = class {
2180
2222
  this.createdObjectUrls.length = 0;
2181
2223
  }
2182
2224
  };
2225
+ async function verifyIntegrity(buffer, integrity) {
2226
+ const [algorithm, expected] = integrity.split("-", 2);
2227
+ if (algorithm !== "sha256" || !expected) {
2228
+ throw new Error("Avatar asset integrity metadata is invalid");
2229
+ }
2230
+ const cryptoApi = globalThis.crypto;
2231
+ if (!cryptoApi?.subtle) return;
2232
+ const digest = new Uint8Array(await cryptoApi.subtle.digest("SHA-256", buffer));
2233
+ let binary = "";
2234
+ for (const byte of digest) binary += String.fromCharCode(byte);
2235
+ if (btoa(binary) !== expected) {
2236
+ throw new Error("Avatar asset integrity verification failed");
2237
+ }
2238
+ }
2183
2239
  function anySignal(signals) {
2184
2240
  const controller = new AbortController();
2185
2241
  for (const sig of signals) {
@@ -2316,7 +2372,7 @@ var FbxRenderer = class {
2316
2372
  const loader = new GLTFLoader();
2317
2373
  try {
2318
2374
  const gltf = await new Promise((resolve, reject) => {
2319
- const glbBuffer = asset.bin.buffer.slice(asset.bin.byteOffset, asset.bin.byteOffset + asset.bin.byteLength);
2375
+ const glbBuffer = asset.buffer ? asset.buffer : asset.bin.buffer.slice(asset.bin.byteOffset, asset.bin.byteOffset + asset.bin.byteLength);
2320
2376
  loader.parse(glbBuffer, asset.url, resolve, reject);
2321
2377
  });
2322
2378
  rawObject = gltf.scene;
@@ -2420,47 +2476,6 @@ var FbxRenderer = class {
2420
2476
  if (this.playAnimation(pose)) {
2421
2477
  return;
2422
2478
  }
2423
- if (this.mixer && this.allAnimations.length > 0) {
2424
- let targetClip;
2425
- if (pose === "speak") {
2426
- targetClip = this.allAnimations.find(
2427
- (c) => c.name.toLowerCase().includes("talk") || c.name.toLowerCase().includes("speak")
2428
- );
2429
- } else if (pose === "think") {
2430
- targetClip = this.allAnimations.find(
2431
- (c) => c.name.toLowerCase().includes("think")
2432
- );
2433
- } else if (pose === "walk") {
2434
- targetClip = this.allAnimations.find(
2435
- (c) => c.name.toLowerCase().includes("walk") || c.name.toLowerCase().includes("run")
2436
- );
2437
- } else if (pose === "point") {
2438
- targetClip = this.allAnimations.find(
2439
- (c) => c.name.toLowerCase().includes("point")
2440
- );
2441
- } else if (pose === "celebrate") {
2442
- targetClip = this.allAnimations.find(
2443
- (c) => c.name.toLowerCase().includes("celebrat") || c.name.toLowerCase().includes("wave") || c.name.toLowerCase().includes("cheer") || c.name.toLowerCase().includes("jump")
2444
- );
2445
- } else {
2446
- targetClip = this.allAnimations.find((c) => c.name.toLowerCase().includes("idle")) || this.animationMetadataList[0]?.clip || this.allAnimations[0];
2447
- }
2448
- if (targetClip) {
2449
- const newAction = this.mixer.clipAction(targetClip);
2450
- if (newAction !== this.currentAction) {
2451
- newAction.reset().fadeIn(0.25).play();
2452
- if (this.currentAction) {
2453
- this.currentAction.fadeOut(0.25);
2454
- }
2455
- this.currentAction = newAction;
2456
- return;
2457
- } else if (!this.currentAction?.isRunning()) {
2458
- this.currentAction?.play();
2459
- return;
2460
- }
2461
- return;
2462
- }
2463
- }
2464
2479
  if (!this.modelRoot) return;
2465
2480
  this.modelRoot.scale.setScalar(this.baseScale);
2466
2481
  switch (pose) {
@@ -2505,13 +2520,13 @@ var FbxRenderer = class {
2505
2520
  return true;
2506
2521
  }
2507
2522
  const idleByName = this.animationMetadataList.find(
2508
- (m) => m.name.toLowerCase().includes("idle") || m.clipName && m.clipName.toLowerCase().includes("idle")
2523
+ (m) => m.name.toLowerCase() === "idle" || m.clipName?.toLowerCase() === "idle"
2509
2524
  );
2510
2525
  if (idleByName && this.playAnimation(idleByName.id || idleByName.name)) {
2511
2526
  return true;
2512
2527
  }
2513
2528
  const embeddedIdle = this.allAnimations.find(
2514
- (c) => c.name.toLowerCase().includes("idle")
2529
+ (c) => c.name.toLowerCase() === "idle"
2515
2530
  );
2516
2531
  if (embeddedIdle) {
2517
2532
  const action = this.mixer.clipAction(embeddedIdle);
@@ -2522,22 +2537,6 @@ var FbxRenderer = class {
2522
2537
  }
2523
2538
  return true;
2524
2539
  }
2525
- if (this.animationMetadataList.length > 0) {
2526
- const firstMeta = this.animationMetadataList[0];
2527
- if (this.playAnimation(firstMeta.id || firstMeta.name)) {
2528
- return true;
2529
- }
2530
- }
2531
- if (this.allAnimations.length > 0) {
2532
- const firstClip = this.allAnimations[0];
2533
- const action = this.mixer.clipAction(firstClip);
2534
- if (this.currentAction !== action) {
2535
- action.reset().fadeIn(0.25).play();
2536
- if (this.currentAction) this.currentAction.fadeOut(0.25);
2537
- this.currentAction = action;
2538
- }
2539
- return true;
2540
- }
2541
2540
  return false;
2542
2541
  }
2543
2542
  async loadExternalAnimations(animations, targetAnimationName) {
@@ -2555,7 +2554,7 @@ var FbxRenderer = class {
2555
2554
  await Promise.allSettled(
2556
2555
  pending.map(async (anim) => {
2557
2556
  try {
2558
- const loaded = await this.assetLoader.load(anim.assetUrl);
2557
+ const loaded = await this.assetLoader.load(anim.assetUrl, { integrity: anim.integrity });
2559
2558
  let extractedClips = [];
2560
2559
  if (loaded.format === "fbx") {
2561
2560
  const loader = new FBXLoader();
@@ -2567,7 +2566,7 @@ var FbxRenderer = class {
2567
2566
  } else if (loaded.format === "glb") {
2568
2567
  const loader = new GLTFLoader();
2569
2568
  const gltf = await new Promise((resolve, reject) => {
2570
- const glbBuffer = loaded.bin.buffer.slice(
2569
+ const glbBuffer = loaded.buffer ? loaded.buffer : loaded.bin.buffer.slice(
2571
2570
  loaded.bin.byteOffset,
2572
2571
  loaded.bin.byteOffset + loaded.bin.byteLength
2573
2572
  );
@@ -2681,13 +2680,13 @@ var FbxRenderer = class {
2681
2680
  clip = this.allAnimations.find((c) => c.name.toLowerCase() === query);
2682
2681
  }
2683
2682
  if (!clip) {
2684
- clip = this.allAnimations.find((c) => c.name.toLowerCase().includes(query));
2683
+ clip = this.allAnimations.find((c) => c.name.toLowerCase() === query);
2685
2684
  }
2686
2685
  if (!clip) {
2687
2686
  return false;
2688
2687
  }
2689
2688
  const action = this.mixer.clipAction(clip);
2690
- const effectiveLoop = loopMode || matched?.loopMode || "repeat";
2689
+ const effectiveLoop = (loopMode || matched?.loopMode || "loop").toLowerCase();
2691
2690
  if (effectiveLoop === "once") {
2692
2691
  action.setLoop(THREE.LoopOnce, 1);
2693
2692
  action.clampWhenFinished = true;
@@ -3195,6 +3194,8 @@ var CssAvatarRenderer = class {
3195
3194
  if (!this.isAssetLoadedFlag && this.viewport) {
3196
3195
  if (this.renderState === "error") {
3197
3196
  this.renderFallback(true);
3197
+ } else if (this.renderState === "loading") {
3198
+ this.renderLoadingPlaceholder();
3198
3199
  } else {
3199
3200
  this.viewport.replaceChildren();
3200
3201
  }
@@ -3260,7 +3261,11 @@ var CssAvatarRenderer = class {
3260
3261
  }
3261
3262
  try {
3262
3263
  this.metricsTracker?.record("assetRequestStart");
3263
- const asset = await this.assetLoader.load(assetUrl, { timeoutMs: 6e4 });
3264
+ const asset = await this.assetLoader.load(assetUrl, {
3265
+ timeoutMs: 6e4,
3266
+ integrity: config.assetIntegrity,
3267
+ expectedFormat: config.assetUrl ? config.modelFormat : void 0
3268
+ });
3264
3269
  this.metricsTracker?.record("assetDownloadComplete");
3265
3270
  const byteSize = asset.buffer?.byteLength ?? asset.bin?.byteLength ?? asset.size;
3266
3271
  this.metricsTracker?.setAssetInfo({
@@ -3361,7 +3366,10 @@ var CssAvatarRenderer = class {
3361
3366
  const thumb = typeof asset.manifest.thumbnailUrl === "string" ? asset.manifest.thumbnailUrl : void 0;
3362
3367
  const modelUrl = typeof asset.manifest.assetUrl === "string" ? asset.manifest.assetUrl : typeof asset.manifest.modelUrl === "string" ? asset.manifest.modelUrl : void 0;
3363
3368
  if (modelUrl) {
3364
- const subAsset = await this.assetLoader.load(modelUrl, { timeoutMs: 6e4 });
3369
+ const subAsset = await this.assetLoader.load(modelUrl, {
3370
+ timeoutMs: 6e4,
3371
+ expectedFormat: config.modelFormat
3372
+ });
3365
3373
  await this.renderLoadedAsset(subAsset, config);
3366
3374
  } else if (thumb) {
3367
3375
  this.viewport.replaceChildren();
@@ -3376,6 +3384,16 @@ var CssAvatarRenderer = class {
3376
3384
  }
3377
3385
  }
3378
3386
  }
3387
+ renderLoadingPlaceholder() {
3388
+ if (!this.viewport) return;
3389
+ this.viewport.replaceChildren();
3390
+ const doc = this.viewport.ownerDocument;
3391
+ const placeholder = doc.createElement("div");
3392
+ placeholder.className = "asiyst-avatar-loader";
3393
+ placeholder.setAttribute("aria-hidden", "true");
3394
+ placeholder.setAttribute("data-state", "loading");
3395
+ this.viewport.appendChild(placeholder);
3396
+ }
3379
3397
  renderFallback(isError = false) {
3380
3398
  if (!this.viewport) return;
3381
3399
  this.viewport.replaceChildren();
@@ -4155,11 +4173,10 @@ function transition(from, to) {
4155
4173
 
4156
4174
  // src/task/TaskEngine.ts
4157
4175
  var TaskEngine = class {
4158
- constructor(interaction, events, analytics, cloud) {
4176
+ constructor(interaction, events, analytics) {
4159
4177
  this.interaction = interaction;
4160
4178
  this.events = events;
4161
4179
  this.analytics = analytics;
4162
- this.cloud = cloud;
4163
4180
  this.status = TaskStatus.Idle;
4164
4181
  this.abort = false;
4165
4182
  }
@@ -4175,7 +4192,6 @@ var TaskEngine = class {
4175
4192
  this.events.emit("asiyst:task:started", { taskId: task.id });
4176
4193
  this.analytics.track("task_started", { taskId: task.id });
4177
4194
  this.analytics.track("guide_started", { taskId: task.id });
4178
- void this.cloud.sendTaskUpdate(task.id, this.status);
4179
4195
  try {
4180
4196
  for (const [index, step] of task.steps.entries()) {
4181
4197
  if (this.abort) {
@@ -4210,13 +4226,11 @@ var TaskEngine = class {
4210
4226
  }
4211
4227
  this.move(TaskStatus.StepCompleted);
4212
4228
  this.events.emit("asiyst:task:step-completed", { taskId: task.id, stepId: step.id });
4213
- void this.cloud.sendTaskUpdate(task.id, this.status, step.id);
4214
4229
  }
4215
4230
  this.move(TaskStatus.TaskCompleted);
4216
4231
  this.events.emit("asiyst:task:completed", { taskId: task.id });
4217
4232
  this.analytics.track("task_completed", { taskId: task.id });
4218
4233
  this.analytics.track("guide_completed", { taskId: task.id });
4219
- void this.cloud.sendTaskUpdate(task.id, this.status);
4220
4234
  this.move(TaskStatus.Idle);
4221
4235
  return TaskStatus.TaskCompleted;
4222
4236
  } catch (error) {
@@ -4291,6 +4305,7 @@ var ConversationPanel = class {
4291
4305
  this.onToggle = onToggle;
4292
4306
  this.conversationId = "";
4293
4307
  this.openState = false;
4308
+ this.submitting = false;
4294
4309
  const doc = root.ownerDocument;
4295
4310
  this.style = doc.createElement("style");
4296
4311
  this.style.textContent = `
@@ -4388,6 +4403,9 @@ var ConversationPanel = class {
4388
4403
  getConversationId() {
4389
4404
  return this.conversationId;
4390
4405
  }
4406
+ setConversationId(conversationId) {
4407
+ this.conversationId = conversationId;
4408
+ }
4391
4409
  open() {
4392
4410
  if (!this.conversationId) {
4393
4411
  this.conversationId = `conv_${Date.now().toString(36)}`;
@@ -4402,22 +4420,51 @@ var ConversationPanel = class {
4402
4420
  this.panel.hidden = true;
4403
4421
  this.onToggle(false);
4404
4422
  }
4405
- append(role, text) {
4423
+ append(role, text, citations = []) {
4406
4424
  const item = this.log.ownerDocument.createElement("div");
4407
4425
  item.className = "asiyst-msg";
4408
4426
  item.setAttribute("data-role", role);
4409
4427
  renderSafeText(item, text);
4428
+ for (const citation of citations) {
4429
+ if (!citation.url) continue;
4430
+ let url;
4431
+ try {
4432
+ url = new URL(citation.url);
4433
+ } catch {
4434
+ continue;
4435
+ }
4436
+ if (url.protocol !== "https:") continue;
4437
+ const link = this.log.ownerDocument.createElement("a");
4438
+ link.href = url.href;
4439
+ link.rel = "noopener noreferrer";
4440
+ link.target = "_blank";
4441
+ link.textContent = sanitizeText(citation.title, 160);
4442
+ const wrapper = this.log.ownerDocument.createElement("div");
4443
+ wrapper.appendChild(link);
4444
+ item.appendChild(wrapper);
4445
+ }
4410
4446
  this.log.appendChild(item);
4411
4447
  this.log.scrollTop = this.log.scrollHeight;
4412
4448
  }
4413
4449
  async submit() {
4450
+ if (this.submitting) return;
4414
4451
  const text = sanitizeText(this.input.value);
4415
4452
  if (!text) {
4416
4453
  return;
4417
4454
  }
4455
+ this.submitting = true;
4456
+ this.input.disabled = true;
4457
+ this.form.querySelector("button")?.setAttribute("disabled", "true");
4418
4458
  this.input.value = "";
4419
4459
  this.append("user", text);
4420
- await this.onSubmit(text);
4460
+ try {
4461
+ await this.onSubmit(text);
4462
+ } finally {
4463
+ this.submitting = false;
4464
+ this.input.disabled = false;
4465
+ this.form.querySelector("button")?.removeAttribute("disabled");
4466
+ this.input.focus();
4467
+ }
4421
4468
  }
4422
4469
  destroy() {
4423
4470
  if (this.keydownListener) {
@@ -4480,19 +4527,15 @@ function loadOrCreateInstallationId(projectId) {
4480
4527
  }
4481
4528
 
4482
4529
  // src/communication/RuntimeAuth.ts
4483
- var RUNTIME_AUDIENCE = "asiyst-sdk-runtime";
4484
- var RUNTIME_CAPABILITIES = [
4485
- "assistant:config",
4486
- "assistant:conversation",
4487
- "assistant:telemetry",
4488
- "assistant:heartbeat"
4489
- ];
4490
4530
  var RuntimeAuth = class {
4491
4531
  constructor(options) {
4492
4532
  this.options = options;
4493
4533
  }
4494
- async getToken(capability) {
4495
- if (this.token && this.isUsable(this.token) && this.token.capabilities.has(capability)) {
4534
+ setInstallationId(installationId) {
4535
+ this.options.installationId = installationId;
4536
+ }
4537
+ async getToken() {
4538
+ if (this.token && this.isUsable(this.token) && Date.now() < this.token.refreshAfter) {
4496
4539
  return this.token.value;
4497
4540
  }
4498
4541
  if (!this.requestInFlight) {
@@ -4501,33 +4544,38 @@ var RuntimeAuth = class {
4501
4544
  });
4502
4545
  }
4503
4546
  const token = await this.requestInFlight;
4504
- if (!token.capabilities.has(capability)) {
4505
- throw new AuthenticationError("ASIYST runtime authorization does not allow this operation.");
4506
- }
4507
4547
  return token.value;
4508
4548
  }
4509
4549
  invalidate() {
4510
4550
  this.token = void 0;
4511
4551
  }
4512
4552
  isUsable(token) {
4513
- return token.expiresAt - Date.now() > 3e4;
4553
+ return token.expiresAt > Date.now();
4514
4554
  }
4515
4555
  async issueToken() {
4556
+ const installationId = this.options.installationId;
4557
+ if (!installationId) {
4558
+ throw new AuthenticationError("ASIYST installation has not been verified.");
4559
+ }
4516
4560
  const controller = new AbortController();
4517
- const timeout = setTimeout(() => controller.abort(), 1e4);
4561
+ let timedOut = false;
4562
+ const timeout = setTimeout(() => {
4563
+ timedOut = true;
4564
+ controller.abort();
4565
+ }, 1e4);
4518
4566
  let response;
4519
4567
  try {
4520
4568
  const baseUrl = this.options.apiBaseUrl.replace(/\/$/, "");
4521
4569
  const payload = JSON.stringify({
4522
4570
  projectId: this.options.projectId,
4523
4571
  publicKey: this.options.publicKey,
4524
- installationId: this.options.installationId,
4572
+ installationId,
4525
4573
  origin: this.options.origin,
4526
- environment: this.options.environment,
4527
4574
  sdkVersion: SDK_VERSION,
4528
- capabilities: [...RUNTIME_CAPABILITIES]
4575
+ environment: this.options.environment,
4576
+ capabilities: ["assistant:config", "assistant:conversation", "assistant:heartbeat"]
4529
4577
  });
4530
- response = await fetch(`${baseUrl}/sdk/runtime/token`, {
4578
+ response = await fetch(contractApiUrl(baseUrl, API_ROUTES.runtimeToken), {
4531
4579
  method: "POST",
4532
4580
  headers: {
4533
4581
  Accept: "application/json",
@@ -4536,19 +4584,8 @@ var RuntimeAuth = class {
4536
4584
  body: payload,
4537
4585
  signal: controller.signal
4538
4586
  });
4539
- if (response.status === 404) {
4540
- response = await fetch(`${baseUrl}/api/v1/sdk/runtime/token`, {
4541
- method: "POST",
4542
- headers: {
4543
- Accept: "application/json",
4544
- "Content-Type": "application/json"
4545
- },
4546
- body: payload,
4547
- signal: controller.signal
4548
- });
4549
- }
4550
4587
  } catch {
4551
- throw new NetworkError("ASIYST runtime authentication is unavailable.");
4588
+ throw new NetworkError(timedOut ? "ASIYST runtime authentication request timed out." : "ASIYST runtime authentication is unavailable.");
4552
4589
  } finally {
4553
4590
  clearTimeout(timeout);
4554
4591
  }
@@ -4559,16 +4596,39 @@ var RuntimeAuth = class {
4559
4596
  body = void 0;
4560
4597
  }
4561
4598
  if (!response.ok) {
4562
- if (response.status === 403) {
4563
- throw new AuthenticationError("ASIYST runtime authorization was rejected.");
4599
+ if (response.status === 401 || response.status === 403) {
4600
+ const errorRecord = body && typeof body === "object" ? body.error : void 0;
4601
+ const errorBody = errorRecord && typeof errorRecord === "object" ? errorRecord : void 0;
4602
+ const code = typeof errorBody?.code === "string" ? errorBody.code : void 0;
4603
+ const installationErrorCodes = {
4604
+ INSTALLATION_NOT_FOUND: "Asiyst installation not found for this domain. Re-run `asiyst connect` and verify your project domain.",
4605
+ INSTALLATION_INACTIVE: "Asiyst installation is inactive. Check your project status in the Asiyst dashboard.",
4606
+ INSTALLATION_REVOKED: "Asiyst installation has been revoked. Re-run `asiyst connect` to register a new installation.",
4607
+ INSTALLATION_PROJECT_MISMATCH: "Asiyst installation does not match the configured project.",
4608
+ INSTALLATION_DOMAIN_MISMATCH: "Asiyst installation domain does not match the current website domain.",
4609
+ ORIGIN_MISMATCH: "Asiyst installation origin does not match the current website origin.",
4610
+ INSTALLATION_ENVIRONMENT_MISMATCH: "Asiyst installation environment does not match the current website environment.",
4611
+ RUNTIME_TOKEN_INVALID: "Asiyst runtime authorization token is invalid.",
4612
+ RUNTIME_TOKEN_EXPIRED: "Asiyst runtime authorization token has expired."
4613
+ };
4614
+ const knownMessage = code ? installationErrorCodes[code] : void 0;
4615
+ if (knownMessage) {
4616
+ throw new AuthenticationError(knownMessage);
4617
+ }
4618
+ throw new AuthenticationError(
4619
+ typeof errorBody?.message === "string" ? `ASIYST runtime authorization rejected: ${errorBody.message}` : "ASIYST runtime authorization was rejected."
4620
+ );
4564
4621
  }
4565
4622
  if (response.status === 429) {
4566
4623
  throw new NetworkError("ASIYST runtime authentication is rate limited.");
4567
4624
  }
4625
+ if (response.status === 503) {
4626
+ throw new NetworkError("ASIYST runtime authentication is unavailable.");
4627
+ }
4568
4628
  throw new NetworkError("ASIYST runtime authentication is unavailable.");
4569
4629
  }
4570
4630
  const data = body?.data;
4571
- 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))) {
4631
+ 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")) {
4572
4632
  throw new AuthenticationError("ASIYST returned an invalid runtime authorization response.");
4573
4633
  }
4574
4634
  const expiresAt = Date.parse(data.expiresAt);
@@ -4578,7 +4638,7 @@ var RuntimeAuth = class {
4578
4638
  const token = {
4579
4639
  value: data.token,
4580
4640
  expiresAt,
4581
- capabilities: new Set(data.capabilities)
4641
+ refreshAfter: expiresAt
4582
4642
  };
4583
4643
  this.token = token;
4584
4644
  return token;
@@ -4744,6 +4804,7 @@ var AsiystRuntime = class {
4744
4804
  this.rescanDebounced = debounce(() => this.rescan(), DOM_SCAN_DEBOUNCE_MS);
4745
4805
  this.isHeartbeatInFlight = false;
4746
4806
  this.lastHeartbeatTime = 0;
4807
+ this.nextHeartbeatAfterMs = HEARTBEAT_INTERVAL_MS;
4747
4808
  this.registrationSucceeded = false;
4748
4809
  if (!doc.body) {
4749
4810
  throw new InitializationError("document.body is not available");
@@ -4763,10 +4824,11 @@ var AsiystRuntime = class {
4763
4824
  apiBaseUrl: options.apiBaseUrl ?? DEFAULT_API_BASE_URL,
4764
4825
  projectId: options.projectId,
4765
4826
  publicKey: options.publicKey,
4766
- installationId: this.installationId,
4827
+ installationId: void 0,
4767
4828
  origin: win.location.origin,
4768
4829
  environment: this.environment
4769
4830
  }) : void 0;
4831
+ this.runtimeAuth = runtimeAuth;
4770
4832
  this.cloud = new CloudClient(transport, options.projectId, options.publicKey, runtimeAuth, this.visitorSessionId, options.avatarId);
4771
4833
  this.config = new ConfigManager(options, this.cloud, this.events);
4772
4834
  this.config.onConfigUpdated = (newConfig, prevConfig) => {
@@ -4798,21 +4860,19 @@ var AsiystRuntime = class {
4798
4860
  () => this.config.get()
4799
4861
  );
4800
4862
  const interaction = new InteractionEngine(this.avatar, this.resolver, () => this.config.get(), win);
4801
- this.tasks = new TaskEngine(interaction, this.events, this.analytics, this.cloud);
4863
+ this.tasks = new TaskEngine(interaction, this.events, this.analytics);
4802
4864
  this.workflows = new WorkflowEngine(this.cloud, this.tasks);
4803
4865
  this.panel = new ConversationPanel(
4804
4866
  this.host.chrome,
4805
4867
  (text) => this.handleUserMessage(text, doc),
4806
4868
  (open) => {
4807
- const convId = this.panel.getConversationId();
4808
- this.cloud.setConversationId(convId);
4809
4869
  this.renderer.setPanelOpen(open);
4810
4870
  if (open) {
4811
4871
  this.analytics.track("assistant_opened");
4812
- this.events.emit("asiyst:conversation:started", { conversationId: convId });
4813
4872
  } else {
4814
4873
  this.analytics.track("assistant_closed");
4815
- this.events.emit("asiyst:conversation:closed", { conversationId: convId });
4874
+ const conversationId = this.panel.getConversationId();
4875
+ if (conversationId) this.events.emit("asiyst:conversation:closed", { conversationId });
4816
4876
  }
4817
4877
  }
4818
4878
  );
@@ -4821,22 +4881,35 @@ var AsiystRuntime = class {
4821
4881
  this.observer.start(doc.documentElement);
4822
4882
  this.highlights.start();
4823
4883
  this.movement.start();
4824
- this.analytics.start();
4825
4884
  this.rescan();
4826
4885
  const figure = this.renderer.getFigure();
4827
4886
  if (figure) {
4828
4887
  this.figureClickListener = () => this.open();
4829
4888
  figure.addEventListener("click", this.figureClickListener);
4830
4889
  }
4831
- this.pagehideListener = () => {
4832
- void this.analytics.flush();
4833
- };
4834
- win.addEventListener("pagehide", this.pagehideListener);
4835
4890
  }
4836
4891
  async start() {
4837
4892
  this.events.emit("asiyst:initialized", { projectId: this.options.projectId });
4838
4893
  this.avatar.show();
4839
4894
  this.movement.goToAnchor();
4895
+ this.lifecycle.emit("sdk.verification_started", {
4896
+ projectId: this.options.projectId,
4897
+ origin: window.location.origin,
4898
+ environment: this.environment,
4899
+ installationId: this.installationId,
4900
+ sdkVersion: SDK_VERSION
4901
+ });
4902
+ try {
4903
+ await this.registerInstallation();
4904
+ } catch (error) {
4905
+ this.connectionStatus = "offline";
4906
+ this.verificationStatus = "error";
4907
+ this.events.emit("asiyst:error", {
4908
+ // Safe diagnostic code — does not expose secrets or signing details.
4909
+ code: "installation_registration_failed",
4910
+ message: error instanceof Error ? error.message : "Asiyst runtime connection failed."
4911
+ });
4912
+ }
4840
4913
  const cfg = await isolateAsync(() => this.config.refresh(), this.config.get());
4841
4914
  this.metricsTracker.record("configRetrieved");
4842
4915
  const domainCheck = validateWebsiteDomain(cfg, window.location.href);
@@ -4851,28 +4924,7 @@ var AsiystRuntime = class {
4851
4924
  }
4852
4925
  this.avatar.applyConfig(cfg);
4853
4926
  this.movement.goToAnchor();
4854
- this.lifecycle.emit("sdk.verification_started", {
4855
- projectId: this.options.projectId,
4856
- origin: window.location.origin,
4857
- environment: this.environment,
4858
- installationId: this.installationId,
4859
- sdkVersion: SDK_VERSION
4860
- });
4861
- void (async () => {
4862
- try {
4863
- await this.registerInstallation();
4864
- await this.sendHeartbeat();
4865
- const doc = this.host.host.ownerDocument;
4866
- this.startHeartbeatScheduler(doc);
4867
- } catch {
4868
- }
4869
- })();
4870
4927
  this.events.emit("asiyst:ready", { projectId: this.options.projectId, configVersion: cfg.version });
4871
- void this.cloud.sendTelemetryEvent("avatar_runtime_initialized", {
4872
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4873
- avatarName: cfg.avatarName,
4874
- publishedVersion: cfg.publishedVersion
4875
- });
4876
4928
  const assetTarget = cfg.assetUrl ?? cfg.thumbnailUrl;
4877
4929
  if (assetTarget) {
4878
4930
  try {
@@ -4885,6 +4937,16 @@ var AsiystRuntime = class {
4885
4937
  this.avatar.show();
4886
4938
  this.movement.goToAnchor();
4887
4939
  }
4940
+ try {
4941
+ await this.sendHeartbeat();
4942
+ } catch (error) {
4943
+ this.connectionStatus = "offline";
4944
+ this.verificationStatus = "error";
4945
+ this.events.emit("asiyst:error", {
4946
+ code: "runtime_connection_failed",
4947
+ message: error instanceof Error ? error.message : "Asiyst runtime connection failed."
4948
+ });
4949
+ }
4888
4950
  this.startConfigRevalidationScheduler();
4889
4951
  }
4890
4952
  async loadAvatarAsset(cfg, assetTarget) {
@@ -4892,10 +4954,6 @@ var AsiystRuntime = class {
4892
4954
  avatarId: this.options.avatarId ?? cfg.avatarId,
4893
4955
  assetUrl: assetTarget
4894
4956
  });
4895
- void this.cloud.sendTelemetryEvent("avatar_asset_loading_started", {
4896
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4897
- assetUrl: assetTarget
4898
- });
4899
4957
  try {
4900
4958
  const loaded = await this.renderer.loadAsset(cfg, this.metricsTracker);
4901
4959
  if (loaded) {
@@ -4908,13 +4966,6 @@ var AsiystRuntime = class {
4908
4966
  assetUrl,
4909
4967
  format
4910
4968
  });
4911
- void this.cloud.sendTelemetryEvent("avatar_asset_loaded", {
4912
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4913
- avatarName: cfg.avatarName,
4914
- assetUrl,
4915
- format,
4916
- publishedVersion: cfg.publishedVersion
4917
- });
4918
4969
  if (isRendered) {
4919
4970
  const metrics = this.metricsTracker.getMetrics();
4920
4971
  const durationMs = metrics?.durations.timeToFirstVisibleMs;
@@ -4923,13 +4974,6 @@ var AsiystRuntime = class {
4923
4974
  format,
4924
4975
  durationMs
4925
4976
  });
4926
- void this.cloud.sendTelemetryEvent("avatar_rendered", {
4927
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4928
- avatarName: cfg.avatarName,
4929
- format,
4930
- publishedVersion: cfg.publishedVersion,
4931
- durationMs
4932
- });
4933
4977
  }
4934
4978
  return true;
4935
4979
  } else {
@@ -4939,11 +4983,6 @@ var AsiystRuntime = class {
4939
4983
  error: err,
4940
4984
  stage: "renderer_init"
4941
4985
  });
4942
- void this.cloud.sendTelemetryEvent("avatar_render_failed", {
4943
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4944
- error: err,
4945
- stage: "renderer_init"
4946
- });
4947
4986
  return false;
4948
4987
  }
4949
4988
  } catch (error) {
@@ -4953,11 +4992,6 @@ var AsiystRuntime = class {
4953
4992
  error: err,
4954
4993
  stage: "asset_fetch"
4955
4994
  });
4956
- void this.cloud.sendTelemetryEvent("avatar_render_failed", {
4957
- avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
4958
- error: err,
4959
- stage: "asset_fetch"
4960
- });
4961
4995
  return false;
4962
4996
  }
4963
4997
  }
@@ -5004,6 +5038,7 @@ var AsiystRuntime = class {
5004
5038
  config: newConfig,
5005
5039
  previousVersion: prevConfig?.version
5006
5040
  });
5041
+ void this.sendHeartbeat();
5007
5042
  }
5008
5043
  async reloadConfig() {
5009
5044
  const updated = await this.config.refresh({ force: true });
@@ -5093,15 +5128,11 @@ var AsiystRuntime = class {
5093
5128
  clearInterval(this.configRevalidationTimer);
5094
5129
  this.configRevalidationTimer = void 0;
5095
5130
  }
5096
- const doc = this.host.host.ownerDocument;
5097
- if (doc && this.visibilityListener) {
5098
- doc.removeEventListener("visibilitychange", this.visibilityListener);
5099
- this.visibilityListener = void 0;
5131
+ if (this.heartbeatTimer) {
5132
+ clearTimeout(this.heartbeatTimer);
5133
+ this.heartbeatTimer = void 0;
5100
5134
  }
5101
5135
  this.isHeartbeatInFlight = false;
5102
- if (this.pagehideListener) {
5103
- win.removeEventListener("pagehide", this.pagehideListener);
5104
- }
5105
5136
  const figure = this.renderer.getFigure();
5106
5137
  if (figure && this.figureClickListener) {
5107
5138
  figure.removeEventListener("click", this.figureClickListener);
@@ -5118,26 +5149,20 @@ var AsiystRuntime = class {
5118
5149
  this.events.removeAll();
5119
5150
  await this.analytics.destroy();
5120
5151
  }
5121
- startHeartbeatScheduler(doc) {
5122
- if (this.heartbeatTimer) {
5123
- clearInterval(this.heartbeatTimer);
5152
+ async sendHeartbeat() {
5153
+ if (this.destroyed || this.isHeartbeatInFlight || !this.registrationSucceeded || !this.installationId) {
5154
+ return false;
5124
5155
  }
5125
- this.heartbeatTimer = setInterval(() => {
5126
- if (!this.destroyed) {
5127
- void this.sendHeartbeat(true);
5156
+ const state = this.renderer.getRenderState() === "error" ? "degraded" : "ready";
5157
+ if (this.lastReportedState === state) return true;
5158
+ const elapsed = Date.now() - this.lastHeartbeatTime;
5159
+ if (this.lastHeartbeatTime && elapsed < this.nextHeartbeatAfterMs) {
5160
+ if (!this.heartbeatTimer) {
5161
+ this.heartbeatTimer = setTimeout(() => {
5162
+ this.heartbeatTimer = void 0;
5163
+ void this.sendHeartbeat();
5164
+ }, this.nextHeartbeatAfterMs - elapsed);
5128
5165
  }
5129
- }, HEARTBEAT_INTERVAL_MS);
5130
- if (doc && typeof doc.addEventListener === "function") {
5131
- this.visibilityListener = () => {
5132
- if (!this.destroyed && doc.visibilityState === "visible" && Date.now() - this.lastHeartbeatTime > 3e4) {
5133
- void this.sendHeartbeat(true);
5134
- }
5135
- };
5136
- doc.addEventListener("visibilitychange", this.visibilityListener);
5137
- }
5138
- }
5139
- async sendHeartbeat(_isPeriodic = false) {
5140
- if (this.destroyed || this.isHeartbeatInFlight) {
5141
5166
  return false;
5142
5167
  }
5143
5168
  this.isHeartbeatInFlight = true;
@@ -5146,17 +5171,23 @@ var AsiystRuntime = class {
5146
5171
  const environment = this.environment;
5147
5172
  const installationId = this.installationId;
5148
5173
  try {
5149
- if (!this.registrationSucceeded && installationId) {
5150
- await this.registerInstallation();
5151
- }
5152
5174
  const heartbeat = await this.cloud.heartbeat({
5153
- origin,
5154
- environment,
5155
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
5175
+ installationId: this.installationId,
5176
+ sdkVersion: SDK_VERSION,
5177
+ state,
5178
+ avatarReady: this.renderer.getRenderState() === "ready",
5179
+ textChatReady: true,
5180
+ environment: this.environment,
5181
+ ...state === "degraded" ? { failureReason: "asset_load_failed" } : {}
5156
5182
  });
5157
5183
  this.lastHeartbeatTime = Date.now();
5184
+ if (heartbeat.ok) this.lastReportedState = state;
5185
+ this.nextHeartbeatAfterMs = Math.max(
5186
+ HEARTBEAT_INTERVAL_MS,
5187
+ heartbeat.nextHeartbeatAfterMs ?? heartbeat.retryAfterMs ?? HEARTBEAT_INTERVAL_MS
5188
+ );
5158
5189
  this.connectionStatus = heartbeat.ok ? "connected" : "disconnected";
5159
- this.verificationStatus = heartbeat.verificationStatus === "verified" ? "connected" : heartbeat.verificationStatus ?? (heartbeat.ok ? "connected" : "not_detected");
5190
+ this.verificationStatus = heartbeat.ok ? "connected" : "not_detected";
5160
5191
  if (heartbeat.ok) {
5161
5192
  if (!previousConnection) {
5162
5193
  this.events.emit("asiyst:runtime:connected", {
@@ -5173,32 +5204,21 @@ var AsiystRuntime = class {
5173
5204
  sdkVersion: SDK_VERSION
5174
5205
  });
5175
5206
  }
5176
- if (heartbeat.verificationStatus === "connected" || heartbeat.verificationStatus === "verified") {
5177
- this.lifecycle.emit("sdk.verified", {
5178
- projectId: this.options.projectId,
5179
- origin,
5180
- environment,
5181
- installationId,
5182
- sdkVersion: SDK_VERSION
5183
- });
5184
- }
5185
- if (heartbeat.versionOutdated) {
5186
- this.lifecycle.emit("sdk.version_outdated", {
5187
- projectId: this.options.projectId,
5188
- origin,
5189
- environment,
5190
- installationId,
5191
- sdkVersion: SDK_VERSION
5192
- });
5193
- }
5207
+ this.lifecycle.emit("sdk.verified", {
5208
+ projectId: this.options.projectId,
5209
+ origin,
5210
+ environment,
5211
+ installationId,
5212
+ sdkVersion: SDK_VERSION
5213
+ });
5194
5214
  return true;
5195
5215
  } else {
5196
- const reason = heartbeat.verificationStatus ?? "unverified";
5216
+ this.lastReportedState = void 0;
5197
5217
  this.lifecycle.emit("sdk.verification_failed", {
5198
5218
  projectId: this.options.projectId,
5199
5219
  origin,
5200
5220
  environment,
5201
- status: reason,
5221
+ status: "heartbeat_failed",
5202
5222
  reason: "heartbeat_failed"
5203
5223
  });
5204
5224
  if (previousConnection) {
@@ -5212,12 +5232,15 @@ var AsiystRuntime = class {
5212
5232
  environment,
5213
5233
  installationId,
5214
5234
  reason: "heartbeat_failed",
5215
- status: reason
5235
+ status: "heartbeat_failed"
5216
5236
  });
5217
5237
  }
5238
+ this.scheduleHeartbeatRetry();
5218
5239
  return false;
5219
5240
  }
5220
5241
  } catch (error) {
5242
+ this.lastHeartbeatTime = Date.now();
5243
+ this.lastReportedState = void 0;
5221
5244
  this.connectionStatus = "offline";
5222
5245
  this.verificationStatus = "error";
5223
5246
  this.lifecycle.emit("sdk.verification_failed", {
@@ -5228,6 +5251,10 @@ var AsiystRuntime = class {
5228
5251
  reason: "heartbeat_failed",
5229
5252
  category: error instanceof AuthenticationError ? "authorization" : "network"
5230
5253
  });
5254
+ this.events.emit("asiyst:error", {
5255
+ code: "runtime_heartbeat_failed",
5256
+ message: error instanceof Error ? error.message : "Asiyst heartbeat failed."
5257
+ });
5231
5258
  if (previousConnection) {
5232
5259
  this.events.emit("asiyst:runtime:disconnected", {
5233
5260
  projectId: this.options.projectId,
@@ -5247,73 +5274,72 @@ var AsiystRuntime = class {
5247
5274
  this.isHeartbeatInFlight = false;
5248
5275
  }
5249
5276
  }
5277
+ scheduleHeartbeatRetry() {
5278
+ if (this.destroyed || this.heartbeatTimer) return;
5279
+ const remaining = Math.max(0, this.nextHeartbeatAfterMs - (Date.now() - this.lastHeartbeatTime));
5280
+ this.heartbeatTimer = setTimeout(() => {
5281
+ this.heartbeatTimer = void 0;
5282
+ void this.sendHeartbeat();
5283
+ }, remaining);
5284
+ }
5250
5285
  async registerInstallation() {
5251
5286
  const origin = window.location.origin;
5252
5287
  const environment = this.environment;
5253
5288
  const installationId = this.installationId;
5254
5289
  if (!installationId) {
5255
- if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
5256
- console.debug("[asiyst] SDK installation identity is unavailable; registration skipped.");
5257
- }
5258
- return;
5290
+ throw new InitializationError("Asiyst could not establish a secure installation identity.");
5259
5291
  }
5260
- let lastError;
5261
- for (let attempt = 0; attempt < 2; attempt += 1) {
5262
- try {
5263
- await this.cloud.registerInstallation({
5264
- project_id: this.options.projectId,
5265
- public_key: this.options.publicKey,
5266
- installation_id: installationId,
5267
- origin,
5268
- environment,
5269
- sdk_version: SDK_VERSION
5270
- });
5271
- this.registrationSucceeded = true;
5272
- return;
5273
- } catch (error) {
5274
- lastError = error;
5275
- if (attempt === 1) {
5276
- if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
5277
- console.debug("[asiyst] SDK installation registration failed.", error);
5278
- }
5279
- this.lifecycle.emit("sdk.verification_failed", {
5280
- projectId: this.options.projectId,
5281
- origin,
5282
- environment,
5283
- installationId,
5284
- reason: "registration_failed",
5285
- category: error instanceof AuthenticationError ? "authorization" : "network"
5286
- });
5287
- return;
5288
- }
5289
- await new Promise((resolve) => setTimeout(resolve, 250));
5292
+ try {
5293
+ const verified = await this.cloud.registerInstallation({
5294
+ projectId: this.options.projectId,
5295
+ publicKey: this.options.publicKey,
5296
+ installationId,
5297
+ origin,
5298
+ environment,
5299
+ sdkVersion: SDK_VERSION
5300
+ });
5301
+ if (!verified.data.installationId) {
5302
+ throw new InitializationError("Asiyst returned no verified installation identifier.");
5290
5303
  }
5304
+ this.installationId = verified.data.installationId;
5305
+ this.runtimeAuth?.setInstallationId(verified.data.installationId);
5306
+ this.registrationSucceeded = true;
5307
+ } catch (error) {
5308
+ if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
5309
+ console.debug("[asiyst] SDK installation verification failed.", error);
5310
+ }
5311
+ this.lifecycle.emit("sdk.verification_failed", {
5312
+ projectId: this.options.projectId,
5313
+ origin,
5314
+ environment,
5315
+ installationId,
5316
+ reason: "registration_failed",
5317
+ category: error instanceof AuthenticationError ? "authorization" : "network"
5318
+ });
5319
+ throw error;
5291
5320
  }
5292
- this.lifecycle.emit("sdk.verification_failed", {
5293
- projectId: this.options.projectId,
5294
- origin,
5295
- environment,
5296
- installationId,
5297
- reason: "registration_failed",
5298
- category: lastError instanceof AuthenticationError ? "authorization" : "network"
5299
- });
5300
5321
  }
5301
5322
  rescan() {
5302
5323
  withIsolation(() => {
5303
5324
  const doc = this.host.host.ownerDocument;
5304
5325
  this.map.replace(inspectDocument(doc));
5305
- void this.cloud.sendWebsiteMap(this.map.snapshot(doc));
5306
5326
  });
5307
5327
  }
5308
5328
  async handleUserMessage(text, doc) {
5309
5329
  this.events.emit("asiyst:conversation:message", { role: "user", text });
5310
5330
  this.avatar.think();
5311
5331
  try {
5312
- const reply = await this.cloud.sendConversationMessage(text, doc.location.href);
5313
- this.panel.append("assistant", reply.message.text);
5332
+ const reply = await this.cloud.sendConversationMessage(
5333
+ text,
5334
+ doc.location.href,
5335
+ this.config.get().maxMessageChars
5336
+ );
5337
+ this.panel.setConversationId(reply.conversationId);
5338
+ this.cloud.setConversationId(reply.conversationId);
5339
+ this.events.emit("asiyst:conversation:started", { conversationId: reply.conversationId });
5340
+ this.panel.append("assistant", reply.message.text, reply.citations);
5314
5341
  this.avatar.speak(reply.message.text);
5315
5342
  this.events.emit("asiyst:conversation:message", { role: "assistant", text: reply.message.text });
5316
- await this.startTaskFromText(text, doc);
5317
5343
  } catch (error) {
5318
5344
  const message = error instanceof Error ? error.message : "Asiyst Cloud is unavailable";
5319
5345
  this.panel.append("assistant", message);
@@ -5337,6 +5363,9 @@ var Asiyst = {
5337
5363
  if (runtime) {
5338
5364
  throw new InitializationError("Asiyst is already initialized");
5339
5365
  }
5366
+ if (typeof document === "undefined" || typeof window === "undefined") {
5367
+ throw new InitializationError("Asiyst SDK can only be initialized in a browser environment.");
5368
+ }
5340
5369
  const credentials = validateInitOptions(options);
5341
5370
  const doc = document;
5342
5371
  const win = window;