@asiyst/sdk 0.1.31 → 0.1.32

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
@@ -4,10 +4,20 @@ import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
4
4
 
5
5
  // src/errors/index.ts
6
6
  var AsiystError = class extends Error {
7
- constructor(code, message) {
8
- super(message);
9
- this.name = "AsiystError";
10
- this.code = code;
7
+ constructor(optionsOrCode, legacyMessage, hint) {
8
+ if (typeof optionsOrCode === "object" && optionsOrCode !== null) {
9
+ super(optionsOrCode.message);
10
+ this.name = "AsiystError";
11
+ this.code = optionsOrCode.code;
12
+ this.hint = optionsOrCode.hint;
13
+ this.status = optionsOrCode.status;
14
+ this.cause = optionsOrCode.cause;
15
+ } else {
16
+ super(legacyMessage ?? optionsOrCode);
17
+ this.name = "AsiystError";
18
+ this.code = optionsOrCode;
19
+ this.hint = hint;
20
+ }
11
21
  }
12
22
  };
13
23
  var ConfigurationError = class extends AsiystError {
@@ -75,7 +85,7 @@ var ALL_ACTION_KINDS = [
75
85
  // src/core/constants.ts
76
86
  function resolveSdkVersion() {
77
87
  {
78
- return "0.1.31";
88
+ return "0.1.32";
79
89
  }
80
90
  }
81
91
  var SDK_VERSION = resolveSdkVersion();
@@ -615,6 +625,15 @@ var API_ROUTES = {
615
625
  installationRegister: "/sdk/installations/register",
616
626
  runtimeHeartbeat: "/sdk/heartbeat",
617
627
  chat: "/conversations/messages",
628
+ chatPrimary: "/conversations/messages",
629
+ chatFallback: "/ai/chat",
630
+ deviceAuthorize: "/cli/device/authorize",
631
+ deviceToken: "/cli/device/token",
632
+ deviceVerify: "/cli/device/verify",
633
+ deviceApprove: "/cli/device/approve",
634
+ deviceDeny: "/cli/device/deny",
635
+ authDeviceAuthorize: "/auth/device/authorize",
636
+ authDeviceToken: "/auth/device/token",
618
637
  projectApiKeyVerify: (projectId) => `/projects/${encodeURIComponent(projectId)}/api-key/verify`,
619
638
  sdkInstallationVerify: "/sdk/installations/verify"
620
639
  };
@@ -844,8 +863,8 @@ var CloudClient = class {
844
863
  const conversationPromise = (async () => {
845
864
  try {
846
865
  const requestConversationId = this.conversationId && isUuid(this.conversationId) ? this.conversationId : void 0;
847
- const response = await this.runtimeRequest({
848
- path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.chat),
866
+ let response = await this.runtimeRequest({
867
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.chatPrimary || API_ROUTES.chat),
849
868
  method: "POST",
850
869
  body: {
851
870
  projectId: this.projectId,
@@ -855,16 +874,35 @@ var CloudClient = class {
855
874
  pageUrl
856
875
  }
857
876
  }, "assistant:conversation");
858
- if (response.ok && response.data?.success === true) {
877
+ if (response.status === 404) {
878
+ response = await this.runtimeRequest({
879
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.chatFallback),
880
+ method: "POST",
881
+ body: {
882
+ projectId: this.projectId,
883
+ text: trimmed,
884
+ message: trimmed,
885
+ ...requestConversationId ? { conversationId: requestConversationId } : {},
886
+ sessionId,
887
+ pageUrl
888
+ }
889
+ }, "assistant:conversation");
890
+ }
891
+ if (response.ok && (response.data?.success === true || typeof response.data?.response === "string" || typeof response.data?.answer === "string" || response.data?.message && typeof response.data.message === "object")) {
859
892
  const body = response.data;
893
+ const headerRequestId = response.headers?.get("x-request-id");
894
+ const bodyRequestId = typeof body?.requestId === "string" ? body.requestId : typeof body?.request_id === "string" ? body.request_id : void 0;
895
+ if (headerRequestId && bodyRequestId && headerRequestId !== bodyRequestId) {
896
+ throw new NetworkError("Asiyst returned a mismatched request identifier.");
897
+ }
860
898
  const message = body.message && typeof body.message === "object" ? body.message : void 0;
861
- const conversationId = body.conversationId;
899
+ const conversationId = (typeof body.conversationId === "string" ? body.conversationId : void 0) ?? (typeof body.conversation_id === "string" ? body.conversation_id : void 0) ?? requestConversationId ?? `conv_${Math.random().toString(36).slice(2, 10)}`;
862
900
  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") {
901
+ if (typeof messageText !== "string" || !messageText.trim() || message && message.role && message.role !== "assistant") {
864
902
  throw new NetworkError("Asiyst returned an unsupported conversation response.");
865
903
  }
866
904
  this.conversationId = conversationId;
867
- const rawCitations = Array.isArray(body.sources) ? body.sources : [];
905
+ const rawCitations = Array.isArray(body.sources) ? body.sources : Array.isArray(body.citations) ? body.citations : [];
868
906
  return {
869
907
  requestId: typeof body.requestId === "string" ? body.requestId : void 0,
870
908
  conversationId,
@@ -893,11 +931,26 @@ var CloudClient = class {
893
931
  const code = typeof errorBody?.code === "string" ? errorBody.code : typeof errorRecord === "string" ? errorRecord : `HTTP_${response.status}`;
894
932
  if (response.status === 401 || response.status === 403) {
895
933
  const installationErrorCodes = {
934
+ ORIGIN_REQUIRED: "Origin header is required for runtime authorization.",
935
+ ORIGIN_NOT_APPROVED: "This origin is not approved for this project in the Asiyst dashboard.",
936
+ DOMAIN_MISMATCH: "Current website domain does not match approved domains for this project.",
937
+ PROJECT_MISMATCH: "Project configuration mismatch.",
938
+ PROJECT_DISABLED: "This Asiyst project is currently disabled.",
939
+ PROJECT_NOT_FOUND: "Asiyst project was not found. Verify your projectId.",
940
+ INVALID_PROJECT_ID: "The configured projectId is invalid.",
941
+ TOKEN_MISSING: "Runtime authorization token is missing.",
942
+ TOKEN_MALFORMED: "Runtime authorization token is malformed.",
943
+ TOKEN_SIGNATURE_INVALID: "Runtime token signature verification failed.",
944
+ TOKEN_EXPIRED: "Runtime authorization token has expired.",
945
+ TOKEN_CLAIMS_INVALID: "Runtime authorization token claims are invalid.",
946
+ ENVIRONMENT_MISMATCH: "SDK environment does not match runtime installation environment.",
947
+ INSUFFICIENT_SCOPE: "Runtime token lacks required assistant:conversation capability.",
896
948
  INSTALLATION_NOT_FOUND: "Asiyst installation not found for this domain. Re-run `asiyst connect` and verify your project domain.",
897
949
  INSTALLATION_INACTIVE: "Asiyst installation is inactive. Check your project status in the Asiyst dashboard.",
898
950
  INSTALLATION_REVOKED: "Asiyst installation has been revoked. Re-run `asiyst connect` to register a new installation.",
899
951
  INSTALLATION_PROJECT_MISMATCH: "Asiyst installation does not match the configured project.",
900
952
  INSTALLATION_DOMAIN_MISMATCH: "Asiyst installation domain does not match the current website domain.",
953
+ INSTALLATION_MISMATCH: "Asiyst installation does not match the request context.",
901
954
  RUNTIME_TOKEN_INVALID: "Asiyst runtime authorization token is invalid. The SDK will attempt to re-authorize.",
902
955
  RUNTIME_TOKEN_EXPIRED: "Asiyst runtime authorization token has expired. The SDK will re-authorize."
903
956
  };
@@ -1865,10 +1918,14 @@ var AssetLoader = class {
1865
1918
  const controller = new AbortController();
1866
1919
  this.inFlightControllers.add(controller);
1867
1920
  const abortSignal = options?.signal ? anySignal([controller.signal, options.signal]) : controller.signal;
1868
- const timeoutMs = options?.timeoutMs ?? 6e4;
1869
- const timeoutId = setTimeout(() => {
1921
+ const connectTimeoutMs = options?.timeouts?.connectTimeoutMs ?? 1e4;
1922
+ const stallTimeoutMs = options?.timeouts?.stallTimeoutMs ?? 15e3;
1923
+ const totalTimeoutMs = options?.timeouts?.totalTimeoutMs ?? options?.timeoutMs ?? 6e4;
1924
+ let timedOutReason;
1925
+ const totalTimeoutId = setTimeout(() => {
1926
+ timedOutReason = "total";
1870
1927
  controller.abort();
1871
- }, timeoutMs);
1928
+ }, totalTimeoutMs);
1872
1929
  try {
1873
1930
  const cleanPath = (sanitizedUrl.split("?")[0] ?? "").toLowerCase();
1874
1931
  const isImageExtension = /\.(png|jpe?g|webp|svg|gif|avif)$/i.test(cleanPath);
@@ -1886,27 +1943,100 @@ var AssetLoader = class {
1886
1943
  durationMs: Date.now() - startTime
1887
1944
  };
1888
1945
  }
1946
+ const maxRetries = options?.maxRetries ?? 2;
1947
+ let attempt = 0;
1889
1948
  let response;
1890
- try {
1891
- response = await fetch(sanitizedUrl, {
1892
- method: "GET",
1893
- headers: {
1894
- Accept: "model/fbx, application/octet-stream, model/gltf-binary, image/*, application/json, */*"
1895
- },
1896
- signal: abortSignal
1897
- });
1898
- } catch (err) {
1899
- if (err instanceof Error && err.name === "AbortError") {
1900
- throw new Error("Avatar asset request timed out or was aborted");
1949
+ while (true) {
1950
+ attempt++;
1951
+ let connectTimeoutId;
1952
+ try {
1953
+ const connectController = new AbortController();
1954
+ const connectSignal = anySignal([abortSignal, connectController.signal]);
1955
+ connectTimeoutId = setTimeout(() => {
1956
+ timedOutReason = "connect";
1957
+ connectController.abort();
1958
+ }, connectTimeoutMs);
1959
+ response = await fetch(sanitizedUrl, {
1960
+ method: "GET",
1961
+ headers: {
1962
+ Accept: "model/fbx, application/octet-stream, model/gltf-binary, image/*, application/json, */*"
1963
+ },
1964
+ signal: connectSignal
1965
+ });
1966
+ } catch (err) {
1967
+ if (connectTimeoutId) clearTimeout(connectTimeoutId);
1968
+ if (timedOutReason) {
1969
+ throw new AsiystError({
1970
+ code: "ASSET_TIMEOUT",
1971
+ message: `Avatar asset request timed out (${timedOutReason} timeout)`
1972
+ });
1973
+ }
1974
+ if (abortSignal.aborted || err instanceof Error && err.name === "AbortError") {
1975
+ if (options?.signal?.aborted || abortSignal.aborted) {
1976
+ const cancelErr = new AsiystError({
1977
+ code: "OPERATION_CANCELLED",
1978
+ message: "Avatar asset request was cancelled",
1979
+ cause: err
1980
+ });
1981
+ cancelErr.name = "AbortError";
1982
+ throw cancelErr;
1983
+ }
1984
+ throw new AsiystError({
1985
+ code: "ASSET_TIMEOUT",
1986
+ message: "Avatar asset request timed out or was aborted"
1987
+ });
1988
+ }
1989
+ if (attempt <= maxRetries && !abortSignal.aborted) {
1990
+ const delay = Math.min(1e3 * Math.pow(2, attempt - 1), 4e3);
1991
+ await new Promise((r) => setTimeout(r, delay));
1992
+ continue;
1993
+ }
1994
+ throw new AsiystError({
1995
+ code: "NETWORK_ERROR",
1996
+ message: `CORS or network policy blocked avatar asset retrieval from ${sanitizedUrl}`,
1997
+ cause: err
1998
+ });
1999
+ } finally {
2000
+ if (connectTimeoutId) clearTimeout(connectTimeoutId);
2001
+ }
2002
+ if (response.status >= 500 && attempt <= maxRetries) {
2003
+ const retryAfter = Number(response.headers.get("retry-after"));
2004
+ const delay = Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1e3 : Math.min(1e3 * Math.pow(2, attempt - 1), 4e3);
2005
+ await new Promise((r) => setTimeout(r, delay));
2006
+ continue;
1901
2007
  }
1902
- throw new Error(`CORS or network policy blocked avatar asset retrieval from ${sanitizedUrl}`);
2008
+ break;
1903
2009
  }
1904
2010
  if (!response.ok) {
1905
- throw new Error(`Avatar asset download failed: HTTP ${response.status} from ${sanitizedUrl}`);
2011
+ if (response.status === 403) {
2012
+ throw new AsiystError({
2013
+ code: "DOMAIN_NOT_APPROVED",
2014
+ status: 403,
2015
+ message: `Avatar asset request forbidden (HTTP 403) from ${sanitizedUrl}`,
2016
+ hint: "Check that the current website domain or origin is approved in the project settings."
2017
+ });
2018
+ }
2019
+ if (response.status === 404) {
2020
+ throw new AsiystError({
2021
+ code: "AVATAR_NOT_FOUND",
2022
+ status: 404,
2023
+ message: `Avatar asset not found (HTTP 404) at ${sanitizedUrl}`,
2024
+ hint: "Verify the avatarId and ensure a 3D model asset is published for this avatar."
2025
+ });
2026
+ }
2027
+ throw new AsiystError({
2028
+ code: "NETWORK_ERROR",
2029
+ status: response.status,
2030
+ message: `Avatar asset download failed: HTTP ${response.status} from ${sanitizedUrl}`
2031
+ });
1906
2032
  }
1907
2033
  const contentType = (response.headers.get("content-type") || "").toLowerCase();
1908
2034
  if (contentType.includes("text/html")) {
1909
- throw new Error(`Avatar asset request returned HTML instead of 3D asset from ${sanitizedUrl}`);
2035
+ throw new AsiystError({
2036
+ code: "ASSET_PARSE_FAILED",
2037
+ message: `Avatar asset request returned HTML instead of 3D asset from ${sanitizedUrl}`,
2038
+ hint: "The server returned a web page instead of 3D asset bytes. Check authentication or routing."
2039
+ });
1910
2040
  }
1911
2041
  if (isJsonExtension || contentType.includes("application/json")) {
1912
2042
  const text = await response.text();
@@ -1914,10 +2044,16 @@ var AssetLoader = class {
1914
2044
  try {
1915
2045
  manifest = JSON.parse(text);
1916
2046
  } catch {
1917
- throw new Error("Invalid avatar manifest: JSON decoding failed");
2047
+ throw new AsiystError({
2048
+ code: "ASSET_PARSE_FAILED",
2049
+ message: "Invalid avatar manifest: JSON decoding failed"
2050
+ });
1918
2051
  }
1919
2052
  if (typeof manifest !== "object" || manifest === null || Array.isArray(manifest)) {
1920
- throw new Error("Invalid avatar manifest schema");
2053
+ throw new AsiystError({
2054
+ code: "ASSET_PARSE_FAILED",
2055
+ message: "Invalid avatar manifest schema"
2056
+ });
1921
2057
  }
1922
2058
  return {
1923
2059
  format: "manifest",
@@ -1937,9 +2073,104 @@ var AssetLoader = class {
1937
2073
  durationMs: Date.now() - startTime
1938
2074
  };
1939
2075
  }
1940
- const arrayBuffer = await response.arrayBuffer();
2076
+ let arrayBuffer;
2077
+ const contentLengthHeader = response.headers.get("content-length");
2078
+ const contentLength = contentLengthHeader ? parseInt(contentLengthHeader, 10) : 0;
2079
+ const totalBytes = Number.isFinite(contentLength) && contentLength > 0 ? contentLength : void 0;
2080
+ const assetName = options?.assetName ?? cleanPath.split("/").pop() ?? "avatar";
2081
+ if (response.body && typeof response.body.getReader === "function") {
2082
+ const reader = response.body.getReader();
2083
+ const chunks = [];
2084
+ let loadedBytes = 0;
2085
+ let stallTimeoutId;
2086
+ const resetStallTimer = () => {
2087
+ if (stallTimeoutId) clearTimeout(stallTimeoutId);
2088
+ stallTimeoutId = setTimeout(() => {
2089
+ timedOutReason = "stall";
2090
+ controller.abort();
2091
+ }, stallTimeoutMs);
2092
+ };
2093
+ resetStallTimer();
2094
+ const onAbort = () => {
2095
+ try {
2096
+ void reader.cancel(timedOutReason || "aborted");
2097
+ } catch {
2098
+ }
2099
+ };
2100
+ abortSignal.addEventListener("abort", onAbort, { once: true });
2101
+ if (abortSignal.aborted) onAbort();
2102
+ try {
2103
+ while (true) {
2104
+ if (abortSignal.aborted) {
2105
+ const err = new AsiystError({
2106
+ code: "OPERATION_CANCELLED",
2107
+ message: "Avatar asset download was cancelled"
2108
+ });
2109
+ err.name = "AbortError";
2110
+ throw err;
2111
+ }
2112
+ const { done, value } = await reader.read();
2113
+ if (done) break;
2114
+ if (value) {
2115
+ chunks.push(value);
2116
+ loadedBytes += value.byteLength;
2117
+ resetStallTimer();
2118
+ const percentage = totalBytes ? Math.min(100, Math.round(loadedBytes / totalBytes * 100)) : void 0;
2119
+ options?.onProgress?.({
2120
+ stage: "downloading",
2121
+ loadedBytes,
2122
+ totalBytes,
2123
+ percentage,
2124
+ assetName
2125
+ });
2126
+ }
2127
+ }
2128
+ } catch (streamErr) {
2129
+ if (timedOutReason) {
2130
+ throw new AsiystError({
2131
+ code: "ASSET_TIMEOUT",
2132
+ message: `Avatar asset request timed out (${timedOutReason} timeout)`
2133
+ });
2134
+ }
2135
+ if (abortSignal.aborted) {
2136
+ const cancelErr = new AsiystError({
2137
+ code: "OPERATION_CANCELLED",
2138
+ message: "Avatar asset download was cancelled",
2139
+ cause: streamErr
2140
+ });
2141
+ cancelErr.name = "AbortError";
2142
+ throw cancelErr;
2143
+ }
2144
+ throw streamErr;
2145
+ } finally {
2146
+ if (stallTimeoutId) clearTimeout(stallTimeoutId);
2147
+ try {
2148
+ reader.releaseLock();
2149
+ } catch {
2150
+ }
2151
+ }
2152
+ const combined = new Uint8Array(loadedBytes);
2153
+ let offset = 0;
2154
+ for (const chunk of chunks) {
2155
+ combined.set(chunk, offset);
2156
+ offset += chunk.byteLength;
2157
+ }
2158
+ arrayBuffer = combined.buffer;
2159
+ } else {
2160
+ arrayBuffer = await response.arrayBuffer();
2161
+ options?.onProgress?.({
2162
+ stage: "downloading",
2163
+ loadedBytes: arrayBuffer.byteLength,
2164
+ totalBytes: arrayBuffer.byteLength,
2165
+ percentage: 100,
2166
+ assetName
2167
+ });
2168
+ }
1941
2169
  if (arrayBuffer.byteLength < 12) {
1942
- throw new Error("Avatar asset payload is too small to be a valid 3D container");
2170
+ throw new AsiystError({
2171
+ code: "ASSET_PARSE_FAILED",
2172
+ message: "Avatar asset payload is too small to be a valid 3D container"
2173
+ });
1943
2174
  }
1944
2175
  if (options?.integrity) {
1945
2176
  await verifyIntegrity(arrayBuffer, options.integrity);
@@ -1947,18 +2178,33 @@ var AssetLoader = class {
1947
2178
  const headerBytes = new Uint8Array(arrayBuffer, 0, Math.min(256, arrayBuffer.byteLength));
1948
2179
  const headerStr = new TextDecoder("utf-8", { fatal: false }).decode(headerBytes).trim();
1949
2180
  if (/^<!DOCTYPE\s+html/i.test(headerStr) || /^<html/i.test(headerStr)) {
1950
- throw new Error(`Avatar asset payload contains HTML error page instead of binary 3D container from ${sanitizedUrl}`);
2181
+ throw new AsiystError({
2182
+ code: "ASSET_PARSE_FAILED",
2183
+ message: `Avatar asset payload contains HTML error page instead of binary 3D container from ${sanitizedUrl}`
2184
+ });
1951
2185
  }
1952
2186
  const hasFbxSignature = this.isFbxBuffer(arrayBuffer);
1953
2187
  const hasGlbSignature = this.isGlbBuffer(arrayBuffer);
1954
2188
  const isFbx = hasFbxSignature || !hasGlbSignature && isFbxExtension;
1955
2189
  const isGlb = hasGlbSignature || !hasFbxSignature && isGlbExtension;
1956
2190
  if (isFbx && isGlb) {
1957
- throw new Error("Avatar asset format is ambiguous");
2191
+ throw new AsiystError({
2192
+ code: "ASSET_PARSE_FAILED",
2193
+ message: "Avatar asset format is ambiguous"
2194
+ });
1958
2195
  }
1959
2196
  if (isFbx) {
1960
2197
  if (options?.expectedFormat && options.expectedFormat !== "fbx") {
1961
- throw new Error(`Avatar asset format mismatch: expected ${options.expectedFormat}, received fbx`);
2198
+ throw new AsiystError({
2199
+ code: "ASSET_PARSE_FAILED",
2200
+ message: `Avatar asset format mismatch: expected ${options.expectedFormat}, received fbx`
2201
+ });
2202
+ }
2203
+ if (arrayBuffer.byteLength > 10 * 1024 * 1024) {
2204
+ const mb = (arrayBuffer.byteLength / (1024 * 1024)).toFixed(1);
2205
+ if (typeof console !== "undefined" && typeof console.warn === "function") {
2206
+ console.warn(`[asiyst] Large FBX avatar asset detected (${mb} MB). Serving raw FBX over HTTP causes slow download and render delays. Recommendation: Optimize and convert to Draco-compressed GLB (< 3 MB).`);
2207
+ }
1962
2208
  }
1963
2209
  const fbxHeader = this.parseFbxHeader(arrayBuffer);
1964
2210
  const resourcePath = sanitizedUrl.includes("/") ? sanitizedUrl.substring(0, sanitizedUrl.lastIndexOf("/") + 1) : "";
@@ -1973,10 +2219,16 @@ var AssetLoader = class {
1973
2219
  };
1974
2220
  }
1975
2221
  if (!isGlb) {
1976
- throw new Error("Avatar asset format is unsupported; expected FBX or GLB");
2222
+ throw new AsiystError({
2223
+ code: "ASSET_PARSE_FAILED",
2224
+ message: "Avatar asset format is unsupported; expected FBX or GLB"
2225
+ });
1977
2226
  }
1978
2227
  if (options?.expectedFormat && options.expectedFormat !== "glb") {
1979
- throw new Error(`Avatar asset format mismatch: expected ${options.expectedFormat}, received glb`);
2228
+ throw new AsiystError({
2229
+ code: "ASSET_PARSE_FAILED",
2230
+ message: `Avatar asset format mismatch: expected ${options.expectedFormat}, received glb`
2231
+ });
1980
2232
  }
1981
2233
  const parsedGlb = this.parseGlb(arrayBuffer);
1982
2234
  return {
@@ -1990,7 +2242,7 @@ var AssetLoader = class {
1990
2242
  durationMs: Date.now() - startTime
1991
2243
  };
1992
2244
  } finally {
1993
- clearTimeout(timeoutId);
2245
+ clearTimeout(totalTimeoutId);
1994
2246
  this.inFlightControllers.delete(controller);
1995
2247
  }
1996
2248
  }
@@ -2258,6 +2510,7 @@ var FbxRenderer = class {
2258
2510
  this.mixer = null;
2259
2511
  this.allAnimations = [];
2260
2512
  this.animationMetadataList = [];
2513
+ this.failedAnimations = /* @__PURE__ */ new Map();
2261
2514
  this.assetLoader = new AssetLoader();
2262
2515
  this.currentAction = null;
2263
2516
  this.animFrameId = null;
@@ -2574,9 +2827,11 @@ var FbxRenderer = class {
2574
2827
  });
2575
2828
  extractedClips = gltf.animations || [];
2576
2829
  }
2830
+ let anyExtracted = false;
2577
2831
  for (const rawClip of extractedClips) {
2578
2832
  const retargeted = this.retargetClip(rawClip, this.rawObject);
2579
2833
  if (!retargeted) continue;
2834
+ anyExtracted = true;
2580
2835
  retargeted.name = anim.clipName || anim.name || rawClip.name;
2581
2836
  this.allAnimations.push(retargeted);
2582
2837
  this.animationMetadataList.push({
@@ -2588,9 +2843,21 @@ var FbxRenderer = class {
2588
2843
  clip: retargeted
2589
2844
  });
2590
2845
  }
2846
+ if (!anyExtracted && extractedClips.length > 0) {
2847
+ this.failedAnimations.set(anim.id || anim.name, {
2848
+ error: `Animation "${anim.name}" contains no compatible skeleton bone tracks`,
2849
+ code: "INCOMPATIBLE_SKELETON",
2850
+ id: anim.id
2851
+ });
2852
+ }
2591
2853
  } catch (err) {
2854
+ const msg = err instanceof Error ? err.message : String(err);
2855
+ this.failedAnimations.set(anim.id || anim.name, {
2856
+ error: msg,
2857
+ code: "LOAD_FAILED",
2858
+ id: anim.id
2859
+ });
2592
2860
  if (typeof console !== "undefined" && typeof console.warn === "function") {
2593
- const msg = err instanceof Error ? err.message : String(err);
2594
2861
  console.warn(`[asiyst] Failed to load external animation "${anim.name}": ${msg}`);
2595
2862
  }
2596
2863
  }
@@ -2604,6 +2871,13 @@ var FbxRenderer = class {
2604
2871
  }
2605
2872
  }
2606
2873
  }
2874
+ getFailedAnimations() {
2875
+ const list = [];
2876
+ for (const [name, info] of this.failedAnimations.entries()) {
2877
+ list.push({ name, id: info.id, error: info.error, code: info.code });
2878
+ }
2879
+ return list;
2880
+ }
2607
2881
  retargetClip(clip, targetObject) {
2608
2882
  const targetNodeNames = /* @__PURE__ */ new Set();
2609
2883
  const boneLookup = /* @__PURE__ */ new Map();
@@ -3061,6 +3335,70 @@ var AVATAR_CSS = `
3061
3335
  .asiyst-open-chat-btn svg {
3062
3336
  stroke: #fbbf24;
3063
3337
  }
3338
+ .asiyst-avatar-error-panel {
3339
+ display: flex;
3340
+ flex-direction: column;
3341
+ gap: 8px;
3342
+ padding: 12px;
3343
+ background: #0f172a;
3344
+ color: #f8fafc;
3345
+ border: 1px solid #ef4444;
3346
+ border-radius: 8px;
3347
+ font: 12px/1.4 system-ui, -apple-system, sans-serif;
3348
+ max-width: 220px;
3349
+ box-shadow: 0 10px 25px rgba(0, 0, 0, 0.4);
3350
+ pointer-events: auto;
3351
+ text-align: left;
3352
+ }
3353
+ .asiyst-avatar-error-title {
3354
+ font-weight: 700;
3355
+ color: #f87171;
3356
+ font-size: 13px;
3357
+ }
3358
+ .asiyst-avatar-error-code {
3359
+ font-family: monospace;
3360
+ background: rgba(239, 68, 68, 0.2);
3361
+ padding: 2px 4px;
3362
+ border-radius: 4px;
3363
+ color: #fca5a5;
3364
+ display: inline-block;
3365
+ }
3366
+ .asiyst-avatar-error-hint {
3367
+ font-size: 11px;
3368
+ color: #94a3b8;
3369
+ }
3370
+ .asiyst-avatar-error-chat {
3371
+ margin-top: 4px;
3372
+ font-size: 11px;
3373
+ color: #60a5fa;
3374
+ cursor: pointer;
3375
+ text-decoration: underline;
3376
+ }
3377
+ .asiyst-avatar-progress-container {
3378
+ display: flex;
3379
+ flex-direction: column;
3380
+ align-items: center;
3381
+ width: 140px;
3382
+ margin-top: 8px;
3383
+ pointer-events: none;
3384
+ }
3385
+ .asiyst-avatar-progress-bar {
3386
+ width: 100%;
3387
+ height: 4px;
3388
+ background: rgba(255, 255, 255, 0.15);
3389
+ border-radius: 2px;
3390
+ overflow: hidden;
3391
+ }
3392
+ .asiyst-avatar-progress-fill {
3393
+ height: 100%;
3394
+ background: #3b82f6;
3395
+ transition: width 0.2s ease;
3396
+ }
3397
+ .asiyst-avatar-progress-text {
3398
+ font-size: 10px;
3399
+ color: #94a3b8;
3400
+ margin-top: 4px;
3401
+ }
3064
3402
  @media (prefers-reduced-motion: reduce) {
3065
3403
  .asiyst-avatar.asiyst-animate { transition: none; }
3066
3404
  .asiyst-avatar-loader { animation: none; }
@@ -3084,6 +3422,9 @@ var CssAvatarRenderer = class {
3084
3422
  this.isAssetLoadedFlag = false;
3085
3423
  this.isFallbackFlag = false;
3086
3424
  }
3425
+ setFallbackOptions(opts) {
3426
+ this.fallbackOptions = opts;
3427
+ }
3087
3428
  setMetricsTracker(tracker) {
3088
3429
  this.metricsTracker = tracker;
3089
3430
  }
@@ -3225,10 +3566,13 @@ var CssAvatarRenderer = class {
3225
3566
  this.chatActionBtn.style.display = open ? "none" : "inline-flex";
3226
3567
  }
3227
3568
  }
3228
- async loadAsset(config, metricsTracker) {
3569
+ async loadAsset(config, metricsTracker, options) {
3229
3570
  if (metricsTracker) {
3230
3571
  this.metricsTracker = metricsTracker;
3231
3572
  }
3573
+ if (options?.fallback) {
3574
+ this.fallbackOptions = options.fallback;
3575
+ }
3232
3576
  const assetUrl = config.assetUrl ?? config.thumbnailUrl;
3233
3577
  if (!assetUrl) {
3234
3578
  this.renderState = "idle";
@@ -3264,7 +3608,12 @@ var CssAvatarRenderer = class {
3264
3608
  const asset = await this.assetLoader.load(assetUrl, {
3265
3609
  timeoutMs: 6e4,
3266
3610
  integrity: config.assetIntegrity,
3267
- expectedFormat: config.assetUrl ? config.modelFormat : void 0
3611
+ expectedFormat: config.assetUrl ? config.modelFormat : void 0,
3612
+ assetName: config.avatarName,
3613
+ onProgress: (p) => {
3614
+ this.updateProgress(p);
3615
+ options?.onProgress?.(p);
3616
+ }
3268
3617
  });
3269
3618
  this.metricsTracker?.record("assetDownloadComplete");
3270
3619
  const byteSize = asset.buffer?.byteLength ?? asset.bin?.byteLength ?? asset.size;
@@ -3294,28 +3643,153 @@ var CssAvatarRenderer = class {
3294
3643
  }
3295
3644
  return true;
3296
3645
  } catch (err) {
3297
- const message = err instanceof Error ? err.message : "Failed to load avatar asset";
3298
- this.lastErrorMessage = message;
3646
+ const errorObj = err instanceof Error ? err : new Error(String(err));
3647
+ this.lastErrorMessage = errorObj.message;
3299
3648
  this.renderState = "error";
3300
3649
  this.isAssetLoadedFlag = false;
3301
3650
  this.isFallbackFlag = true;
3651
+ if (this.nameTagEl) {
3652
+ this.nameTagEl.style.display = "none";
3653
+ }
3654
+ this.renderErrorState(errorObj, this.fallbackOptions);
3655
+ return false;
3656
+ }
3657
+ }
3658
+ updateProgress(progress) {
3659
+ if (!this.viewport || this.renderState !== "loading") return;
3660
+ const loader = this.viewport.querySelector(".asiyst-avatar-loader") ?? this.viewport.querySelector(".asiyst-avatar-loading-silhouette");
3661
+ if (!loader) return;
3662
+ let progressBox = loader.querySelector(".asiyst-avatar-progress-container");
3663
+ if (!progressBox) {
3664
+ const doc = this.viewport.ownerDocument;
3665
+ progressBox = doc.createElement("div");
3666
+ progressBox.className = "asiyst-avatar-progress-container";
3667
+ progressBox.innerHTML = `
3668
+ <div class="asiyst-avatar-progress-bar"><div class="asiyst-avatar-progress-fill" style="width: 0%"></div></div>
3669
+ <div class="asiyst-avatar-progress-text"></div>
3670
+ `;
3671
+ loader.appendChild(progressBox);
3672
+ }
3673
+ const fill = progressBox.querySelector(".asiyst-avatar-progress-fill");
3674
+ const text = progressBox.querySelector(".asiyst-avatar-progress-text");
3675
+ if (fill && typeof progress.percentage === "number") {
3676
+ fill.style.width = `${progress.percentage}%`;
3677
+ }
3678
+ if (text) {
3679
+ if (progress.loadedBytes && progress.totalBytes) {
3680
+ const loadedMb = (progress.loadedBytes / (1024 * 1024)).toFixed(1);
3681
+ const totalMb = (progress.totalBytes / (1024 * 1024)).toFixed(1);
3682
+ text.textContent = `${progress.stage || "Loading"} ${loadedMb}MB / ${totalMb}MB`;
3683
+ } else if (progress.loadedBytes) {
3684
+ const loadedMb = (progress.loadedBytes / (1024 * 1024)).toFixed(1);
3685
+ text.textContent = `${progress.stage || "Loading"} ${loadedMb}MB`;
3686
+ } else {
3687
+ text.textContent = progress.stage || "Loading...";
3688
+ }
3689
+ }
3690
+ }
3691
+ renderErrorState(error, fallbackOptions) {
3692
+ this.renderState = "error";
3693
+ this.isAssetLoadedFlag = false;
3694
+ this.isFallbackFlag = true;
3695
+ this.lastErrorMessage = error.message;
3696
+ if (!this.viewport) return;
3697
+ this.viewport.replaceChildren();
3698
+ const doc = this.viewport.ownerDocument;
3699
+ const opts = fallbackOptions ?? this.fallbackOptions;
3700
+ if (opts?.mode === "image" && opts.imageUrl) {
3701
+ if (this.figure) {
3702
+ this.figure.setAttribute("data-state", "ready");
3703
+ this.figure.classList.add("asiyst-3d-active");
3704
+ this.figure.classList.remove("asiyst-compact-launcher");
3705
+ this.figure.style.background = "transparent";
3706
+ }
3707
+ const img = doc.createElement("img");
3708
+ img.className = "asiyst-avatar-graphic";
3709
+ img.src = opts.imageUrl;
3710
+ img.alt = `${this.avatarName} fallback avatar`;
3711
+ this.viewport.appendChild(img);
3712
+ return;
3713
+ }
3714
+ if (opts?.mode === "chat-only") {
3302
3715
  if (this.figure) {
3303
- this.figure.setAttribute("data-state", "error");
3716
+ this.figure.setAttribute("data-state", "ready");
3304
3717
  this.figure.classList.remove("asiyst-3d-active");
3305
3718
  this.figure.classList.add("asiyst-compact-launcher");
3306
3719
  this.figure.style.width = `${this.size}px`;
3307
3720
  this.figure.style.height = `${this.size}px`;
3308
3721
  this.figure.style.background = this.accentColor;
3309
3722
  }
3310
- if (this.nameTagEl) {
3311
- this.nameTagEl.style.display = "none";
3312
- }
3313
- if (this.chatActionBtn) {
3314
- this.chatActionBtn.style.display = "none";
3723
+ this.renderFallback(false);
3724
+ return;
3725
+ }
3726
+ if (opts?.mode === "2d") {
3727
+ if (this.figure) {
3728
+ this.figure.setAttribute("data-state", "ready");
3729
+ this.figure.classList.remove("asiyst-3d-active");
3730
+ this.figure.classList.add("asiyst-compact-launcher");
3731
+ this.figure.style.width = `${this.size}px`;
3732
+ this.figure.style.height = `${this.size}px`;
3733
+ this.figure.style.background = this.accentColor;
3315
3734
  }
3316
3735
  this.renderFallback(true);
3317
- return false;
3736
+ return;
3737
+ }
3738
+ if (this.figure) {
3739
+ this.figure.setAttribute("data-state", "error");
3740
+ this.figure.classList.add("asiyst-3d-active");
3741
+ this.figure.classList.remove("asiyst-compact-launcher");
3742
+ this.figure.style.background = "transparent";
3318
3743
  }
3744
+ const isDev = typeof window !== "undefined" && (window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1" || window.location.hostname === "::1");
3745
+ const panel = doc.createElement("div");
3746
+ panel.className = "asiyst-avatar-error-panel";
3747
+ panel.setAttribute("data-fallback", "true");
3748
+ panel.setAttribute("data-state", "error");
3749
+ if (isDev) {
3750
+ const title = doc.createElement("div");
3751
+ title.className = "asiyst-avatar-error-title";
3752
+ title.textContent = "Avatar could not be loaded";
3753
+ const errCode = (error instanceof AsiystError ? error.code : "ERROR") || "ERROR";
3754
+ const codeDiv = doc.createElement("div");
3755
+ codeDiv.textContent = "Error: ";
3756
+ const codeSpan = doc.createElement("span");
3757
+ codeSpan.className = "asiyst-avatar-error-code";
3758
+ codeSpan.textContent = String(errCode);
3759
+ codeDiv.appendChild(codeSpan);
3760
+ const originDiv = doc.createElement("div");
3761
+ originDiv.className = "asiyst-avatar-error-hint";
3762
+ const currentOrigin = typeof window !== "undefined" ? window.location.origin : "unknown";
3763
+ originDiv.textContent = `Origin: ${currentOrigin}`;
3764
+ const hintDiv = doc.createElement("div");
3765
+ hintDiv.className = "asiyst-avatar-error-hint";
3766
+ const hintText = (error instanceof AsiystError ? error.hint : void 0) ?? (errCode === "DOMAIN_NOT_APPROVED" || errCode === "ORIGIN_NOT_APPROVED" ? "Add this development origin through the project's approved development-origin configuration." : error.message);
3767
+ hintDiv.textContent = `Fix: ${hintText}`;
3768
+ const chatLink = doc.createElement("div");
3769
+ chatLink.className = "asiyst-avatar-error-chat";
3770
+ chatLink.textContent = "Open chat widget \u2192";
3771
+ chatLink.addEventListener("click", (e) => {
3772
+ e.stopPropagation();
3773
+ this.onOpenChat?.();
3774
+ });
3775
+ panel.append(title, codeDiv, originDiv, hintDiv, chatLink);
3776
+ } else {
3777
+ const title = doc.createElement("div");
3778
+ title.className = "asiyst-avatar-error-title";
3779
+ title.textContent = "Your assistant is temporarily unavailable.";
3780
+ const sub = doc.createElement("div");
3781
+ sub.className = "asiyst-avatar-error-hint";
3782
+ sub.textContent = "You can still continue using chat.";
3783
+ const chatLink = doc.createElement("div");
3784
+ chatLink.className = "asiyst-avatar-error-chat";
3785
+ chatLink.textContent = "Open chat widget \u2192";
3786
+ chatLink.addEventListener("click", (e) => {
3787
+ e.stopPropagation();
3788
+ this.onOpenChat?.();
3789
+ });
3790
+ panel.append(title, sub, chatLink);
3791
+ }
3792
+ this.viewport.appendChild(panel);
3319
3793
  }
3320
3794
  renderLoader() {
3321
3795
  if (!this.viewport) return;
@@ -4802,6 +5276,11 @@ var AsiystRuntime = class {
4802
5276
  this.connectionStatus = "disconnected";
4803
5277
  this.verificationStatus = "not_detected";
4804
5278
  this.rescanDebounced = debounce(() => this.rescan(), DOM_SCAN_DEBOUNCE_MS);
5279
+ this.state = "idle";
5280
+ this.avatarLifecycleState = "initializing";
5281
+ this.chatLifecycleState = "initializing";
5282
+ this.isDebug = false;
5283
+ this.errorsObserved = [];
4805
5284
  this.isHeartbeatInFlight = false;
4806
5285
  this.lastHeartbeatTime = 0;
4807
5286
  this.nextHeartbeatAfterMs = HEARTBEAT_INTERVAL_MS;
@@ -4842,6 +5321,8 @@ var AsiystRuntime = class {
4842
5321
  () => this.map.list()
4843
5322
  );
4844
5323
  this.renderer = new CssAvatarRenderer();
5324
+ this.isDebug = Boolean(options.debug) || typeof win !== "undefined" && Boolean(win.location?.search?.includes("asiyst_debug=1"));
5325
+ this.renderer.setFallbackOptions(options.fallback);
4845
5326
  this.renderer.onOpenChat = () => this.open();
4846
5327
  this.renderer.mount(this.host.chrome, this.config.get());
4847
5328
  this.metricsTracker.record("sdkInit");
@@ -4888,6 +5369,47 @@ var AsiystRuntime = class {
4888
5369
  figure.addEventListener("click", this.figureClickListener);
4889
5370
  }
4890
5371
  }
5372
+ getState() {
5373
+ return this.state;
5374
+ }
5375
+ getAvatarState() {
5376
+ return this.avatarLifecycleState;
5377
+ }
5378
+ getChatState() {
5379
+ return this.chatLifecycleState;
5380
+ }
5381
+ setAvatarLifecycleState(next) {
5382
+ if (this.avatarLifecycleState === next) return;
5383
+ this.avatarLifecycleState = next;
5384
+ this.events.emit("asiyst:avatar:state", { state: next });
5385
+ }
5386
+ setChatLifecycleState(next) {
5387
+ if (this.chatLifecycleState === next) return;
5388
+ this.chatLifecycleState = next;
5389
+ this.events.emit("asiyst:chat:state", { state: next });
5390
+ }
5391
+ setState(nextState, details) {
5392
+ if (this.state === nextState) return;
5393
+ const prevState = this.state;
5394
+ this.state = nextState;
5395
+ if (this.isDebug) {
5396
+ console.log(`[asiyst] State transition: ${prevState} -> ${nextState}`, details ?? "");
5397
+ }
5398
+ this.events.emit("state", nextState);
5399
+ this.events.emit("asiyst:state", { state: nextState, previousState: prevState, details });
5400
+ }
5401
+ recordError(error) {
5402
+ const errObj = {
5403
+ code: "code" in error && error.code ? String(error.code) : "UNKNOWN_ERROR",
5404
+ message: error.message,
5405
+ hint: "hint" in error ? error.hint : void 0,
5406
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
5407
+ };
5408
+ this.errorsObserved.push(errObj);
5409
+ if (this.isDebug) {
5410
+ console.error("[asiyst] Error recorded:", errObj);
5411
+ }
5412
+ }
4891
5413
  async start() {
4892
5414
  this.events.emit("asiyst:initialized", { projectId: this.options.projectId });
4893
5415
  this.avatar.show();
@@ -4899,36 +5421,113 @@ var AsiystRuntime = class {
4899
5421
  installationId: this.installationId,
4900
5422
  sdkVersion: SDK_VERSION
4901
5423
  });
5424
+ this.setState("registering");
4902
5425
  try {
4903
5426
  await this.registerInstallation();
4904
5427
  } catch (error) {
4905
5428
  this.connectionStatus = "offline";
4906
5429
  this.verificationStatus = "error";
5430
+ const isDomainAuthFailure = error instanceof AuthenticationError && /domain|origin|authorized|approved/i.test(error.message) || error instanceof Error && /domain|origin is not approved/i.test(error.message);
5431
+ if (isDomainAuthFailure) {
5432
+ const isLocal = /^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i.test(window.location.hostname);
5433
+ const domainErr = new AsiystError({
5434
+ code: "DOMAIN_NOT_APPROVED",
5435
+ message: error instanceof Error ? error.message : "The website domain is not approved for this project.",
5436
+ hint: isLocal ? "Local development detected. Add 'localhost' or '127.0.0.1' to your approved domains in Asiyst Dashboard > Settings > Domains." : `Add '${window.location.hostname}' to your approved domains in Asiyst Dashboard > Settings > Domains.`,
5437
+ status: 403,
5438
+ cause: error
5439
+ });
5440
+ this.recordError(domainErr);
5441
+ this.renderer.renderErrorState(domainErr, this.options.fallback);
5442
+ this.setAvatarLifecycleState("error");
5443
+ this.setChatLifecycleState("error");
5444
+ this.setState("error", { reason: "domain_not_authorized", code: domainErr.code });
5445
+ this.events.emit("asiyst:error", {
5446
+ code: "domain_not_authorized",
5447
+ message: domainErr.message
5448
+ });
5449
+ this.events.emit("error", domainErr);
5450
+ return;
5451
+ }
5452
+ const asiystErr = error instanceof AsiystError ? error : new AsiystError({
5453
+ code: "AUTHENTICATION_FAILED",
5454
+ message: error instanceof Error ? error.message : "Asiyst runtime connection failed.",
5455
+ cause: error
5456
+ });
5457
+ this.recordError(asiystErr);
4907
5458
  this.events.emit("asiyst:error", {
4908
- // Safe diagnostic code — does not expose secrets or signing details.
4909
5459
  code: "installation_registration_failed",
4910
- message: error instanceof Error ? error.message : "Asiyst runtime connection failed."
5460
+ message: asiystErr.message
5461
+ });
5462
+ this.events.emit("error", asiystErr);
5463
+ }
5464
+ this.setState("authorizing");
5465
+ if (this.runtimeAuth && this.registrationSucceeded) {
5466
+ try {
5467
+ await this.runtimeAuth.getToken();
5468
+ } catch (authErr) {
5469
+ const asiystErr = authErr instanceof AsiystError ? authErr : new AsiystError({
5470
+ code: "AUTHENTICATION_FAILED",
5471
+ message: authErr instanceof Error ? authErr.message : "Runtime authorization failed.",
5472
+ cause: authErr
5473
+ });
5474
+ this.recordError(asiystErr);
5475
+ this.events.emit("asiyst:error", {
5476
+ code: "runtime_authorization_failed",
5477
+ message: asiystErr.message
5478
+ });
5479
+ this.events.emit("error", asiystErr);
5480
+ }
5481
+ }
5482
+ this.setState("fetching-config");
5483
+ let cfg;
5484
+ try {
5485
+ cfg = await isolateAsync(() => this.config.refresh(), this.config.get());
5486
+ this.metricsTracker.record("configRetrieved");
5487
+ } catch (configErr) {
5488
+ const asiystErr = new AsiystError({
5489
+ code: "CONFIG_INVALID",
5490
+ message: configErr instanceof Error ? configErr.message : "Failed to load project configuration.",
5491
+ cause: configErr
4911
5492
  });
5493
+ this.recordError(asiystErr);
5494
+ this.events.emit("error", asiystErr);
5495
+ cfg = this.config.get();
4912
5496
  }
4913
- const cfg = await isolateAsync(() => this.config.refresh(), this.config.get());
4914
- this.metricsTracker.record("configRetrieved");
4915
5497
  const domainCheck = validateWebsiteDomain(cfg, window.location.href);
4916
5498
  if (!domainCheck.allowed) {
4917
5499
  this.connectionStatus = "disconnected";
4918
5500
  this.verificationStatus = "not_detected";
5501
+ const isLocal = /^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i.test(window.location.hostname);
5502
+ const domainErr = new AsiystError({
5503
+ code: "DOMAIN_NOT_APPROVED",
5504
+ message: `This website domain (${window.location.hostname}) is not authorized for the current Asiyst project.`,
5505
+ hint: isLocal ? "Local development detected. Add 'localhost' or '127.0.0.1' to your approved domains in Asiyst Dashboard > Settings > Domains." : `Add '${window.location.hostname}' to your approved domains in Asiyst Dashboard > Settings > Domains.`,
5506
+ status: 403
5507
+ });
5508
+ this.recordError(domainErr);
5509
+ this.renderer.renderErrorState(domainErr, this.options.fallback);
5510
+ this.setAvatarLifecycleState("error");
5511
+ this.setChatLifecycleState("error");
5512
+ this.setState("error", { reason: "domain_not_authorized", code: domainErr.code });
4919
5513
  this.events.emit("asiyst:error", {
4920
5514
  code: "domain_not_authorized",
4921
- message: "This website is not authorized for the current Asiyst project."
5515
+ message: domainErr.message
4922
5516
  });
5517
+ this.events.emit("error", domainErr);
4923
5518
  return;
4924
5519
  }
4925
5520
  this.avatar.applyConfig(cfg);
4926
5521
  this.movement.goToAnchor();
5522
+ this.setChatLifecycleState("ready");
5523
+ this.setState("loading-avatar");
5524
+ this.setAvatarLifecycleState("loading");
4927
5525
  this.events.emit("asiyst:ready", { projectId: this.options.projectId, configVersion: cfg.version });
4928
5526
  const assetTarget = cfg.assetUrl ?? cfg.thumbnailUrl;
5527
+ let avatarLoadedSuccessfully = false;
4929
5528
  if (assetTarget) {
4930
5529
  try {
4931
- await this.loadAvatarAsset(cfg, assetTarget);
5530
+ avatarLoadedSuccessfully = await this.loadAvatarAsset(cfg, assetTarget);
4932
5531
  } finally {
4933
5532
  this.avatar.show();
4934
5533
  this.movement.goToAnchor();
@@ -4936,6 +5535,17 @@ var AsiystRuntime = class {
4936
5535
  } else {
4937
5536
  this.avatar.show();
4938
5537
  this.movement.goToAnchor();
5538
+ avatarLoadedSuccessfully = true;
5539
+ }
5540
+ if (avatarLoadedSuccessfully || this.renderer.getRenderState() === "ready") {
5541
+ this.setAvatarLifecycleState("ready");
5542
+ } else {
5543
+ this.setAvatarLifecycleState("error");
5544
+ }
5545
+ if (avatarLoadedSuccessfully || this.renderer.getRenderState() === "ready" || this.options.fallback?.mode) {
5546
+ this.setState("ready");
5547
+ } else {
5548
+ this.setState("error", { reason: "avatar_load_failed" });
4939
5549
  }
4940
5550
  try {
4941
5551
  await this.sendHeartbeat();
@@ -4955,7 +5565,13 @@ var AsiystRuntime = class {
4955
5565
  assetUrl: assetTarget
4956
5566
  });
4957
5567
  try {
4958
- const loaded = await this.renderer.loadAsset(cfg, this.metricsTracker);
5568
+ const loaded = await this.renderer.loadAsset(cfg, this.metricsTracker, {
5569
+ onProgress: (p) => {
5570
+ this.events.emit("progress", p);
5571
+ this.events.emit("asiyst:progress", p);
5572
+ },
5573
+ fallback: this.options.fallback
5574
+ });
4959
5575
  if (loaded) {
4960
5576
  this.movement.goToAnchor();
4961
5577
  const format = this.renderer.getLoadedFormat();
@@ -4978,6 +5594,10 @@ var AsiystRuntime = class {
4978
5594
  return true;
4979
5595
  } else {
4980
5596
  const err = this.renderer.getLastError() ?? "Avatar asset loading failed";
5597
+ this.recordError({
5598
+ code: "AVATAR_LOAD_FAILED",
5599
+ message: err
5600
+ });
4981
5601
  this.events.emit("asiyst:avatar:error", {
4982
5602
  avatarId: this.options.avatarId ?? cfg.avatarId,
4983
5603
  error: err,
@@ -4987,6 +5607,7 @@ var AsiystRuntime = class {
4987
5607
  }
4988
5608
  } catch (error) {
4989
5609
  const err = error instanceof Error ? error.message : "Avatar asset rendering failed";
5610
+ this.recordError(error instanceof Error ? error : new Error(err));
4990
5611
  this.events.emit("asiyst:avatar:error", {
4991
5612
  avatarId: this.options.avatarId ?? cfg.avatarId,
4992
5613
  error: err,
@@ -5086,6 +5707,104 @@ var AsiystRuntime = class {
5086
5707
  getAvatarPerformanceMetrics() {
5087
5708
  return this.metricsTracker.getMetrics();
5088
5709
  }
5710
+ async diagnose() {
5711
+ const startTime = typeof performance !== "undefined" && performance.now ? performance.now() : Date.now();
5712
+ const origin = typeof window !== "undefined" && window.location ? window.location.origin : "";
5713
+ let webglSupported = false;
5714
+ let rendererAvailable = false;
5715
+ try {
5716
+ if (typeof document !== "undefined") {
5717
+ const testCanvas = document.createElement("canvas");
5718
+ const gl = testCanvas.getContext("webgl2") || testCanvas.getContext("webgl");
5719
+ if (gl) {
5720
+ webglSupported = true;
5721
+ rendererAvailable = true;
5722
+ }
5723
+ }
5724
+ } catch {
5725
+ webglSupported = false;
5726
+ rendererAvailable = false;
5727
+ }
5728
+ const registration = {
5729
+ ok: this.registrationSucceeded,
5730
+ status: this.registrationSucceeded ? 200 : void 0,
5731
+ code: this.registrationSucceeded ? void 0 : "REGISTRATION_FAILED",
5732
+ message: this.registrationSucceeded ? "Installation registered successfully" : "Installation registration failed or incomplete"
5733
+ };
5734
+ let authorization;
5735
+ try {
5736
+ if (this.runtimeAuth) {
5737
+ const token = await this.runtimeAuth.getToken();
5738
+ authorization = {
5739
+ ok: Boolean(token),
5740
+ status: 200,
5741
+ message: "Runtime authorization token valid"
5742
+ };
5743
+ } else {
5744
+ authorization = {
5745
+ ok: false,
5746
+ code: "NO_AUTH_PROVIDER",
5747
+ message: "No runtime auth provider configured"
5748
+ };
5749
+ }
5750
+ } catch (authErr) {
5751
+ authorization = {
5752
+ ok: false,
5753
+ status: authErr?.status ?? 403,
5754
+ code: authErr?.code ?? "AUTHENTICATION_FAILED",
5755
+ message: authErr instanceof Error ? authErr.message : "Authorization failed"
5756
+ };
5757
+ }
5758
+ const cfg = this.config.get();
5759
+ const runtimeConfig = {
5760
+ ok: Boolean(cfg && cfg.version !== void 0),
5761
+ status: cfg ? 200 : void 0,
5762
+ message: cfg ? "Runtime configuration loaded" : "Runtime configuration unavailable"
5763
+ };
5764
+ const avatarId = this.options.avatarId ?? cfg.avatarId ?? "default";
5765
+ const assets = [];
5766
+ if (cfg.assetUrl) {
5767
+ assets.push({
5768
+ name: "mesh",
5769
+ format: cfg.modelFormat ?? "fbx",
5770
+ loaded: this.renderer.isAssetLoaded()
5771
+ });
5772
+ }
5773
+ if (cfg.animations && Array.isArray(cfg.animations)) {
5774
+ for (const anim of cfg.animations) {
5775
+ assets.push({
5776
+ name: anim.name || anim.assetUrl || "animation",
5777
+ format: "fbx",
5778
+ loaded: this.renderer.isAssetLoaded()
5779
+ });
5780
+ }
5781
+ }
5782
+ const endTime = typeof performance !== "undefined" && performance.now ? performance.now() : Date.now();
5783
+ const durationMs = Math.round(endTime - startTime);
5784
+ return {
5785
+ sdkVersion: SDK_VERSION,
5786
+ origin,
5787
+ state: this.state,
5788
+ registration,
5789
+ authorization,
5790
+ runtimeConfig,
5791
+ avatar: {
5792
+ avatarId,
5793
+ format: this.renderer.getLoadedFormat() ?? cfg.modelFormat,
5794
+ assets
5795
+ },
5796
+ webgl: {
5797
+ supported: webglSupported,
5798
+ rendererAvailable
5799
+ },
5800
+ errors: this.errorsObserved.map((e) => ({
5801
+ code: e.code,
5802
+ message: e.message,
5803
+ hint: e.hint
5804
+ })),
5805
+ durationMs
5806
+ };
5807
+ }
5089
5808
  avatarApi() {
5090
5809
  return this.avatar;
5091
5810
  }
@@ -5120,6 +5839,7 @@ var AsiystRuntime = class {
5120
5839
  return;
5121
5840
  }
5122
5841
  this.destroyed = true;
5842
+ this.setState("idle");
5123
5843
  if (this.heartbeatTimer) {
5124
5844
  clearInterval(this.heartbeatTimer);
5125
5845
  this.heartbeatTimer = void 0;
@@ -5382,6 +6102,18 @@ var Asiyst = {
5382
6102
  initPromise = void 0;
5383
6103
  await current.destroy(window);
5384
6104
  },
6105
+ getState() {
6106
+ return runtime ? runtime.getState() : "idle";
6107
+ },
6108
+ getAvatarState() {
6109
+ return runtime ? runtime.getAvatarState() : "initializing";
6110
+ },
6111
+ getChatState() {
6112
+ return runtime ? runtime.getChatState() : "initializing";
6113
+ },
6114
+ async diagnose() {
6115
+ return requireRuntime().diagnose();
6116
+ },
5385
6117
  open() {
5386
6118
  withIsolation(() => requireRuntime().open());
5387
6119
  },