@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.cjs CHANGED
@@ -26,10 +26,20 @@ var THREE__namespace = /*#__PURE__*/_interopNamespace(THREE);
26
26
 
27
27
  // src/errors/index.ts
28
28
  var AsiystError = class extends Error {
29
- constructor(code, message) {
30
- super(message);
31
- this.name = "AsiystError";
32
- this.code = code;
29
+ constructor(optionsOrCode, legacyMessage, hint) {
30
+ if (typeof optionsOrCode === "object" && optionsOrCode !== null) {
31
+ super(optionsOrCode.message);
32
+ this.name = "AsiystError";
33
+ this.code = optionsOrCode.code;
34
+ this.hint = optionsOrCode.hint;
35
+ this.status = optionsOrCode.status;
36
+ this.cause = optionsOrCode.cause;
37
+ } else {
38
+ super(legacyMessage ?? optionsOrCode);
39
+ this.name = "AsiystError";
40
+ this.code = optionsOrCode;
41
+ this.hint = hint;
42
+ }
33
43
  }
34
44
  };
35
45
  var ConfigurationError = class extends AsiystError {
@@ -97,7 +107,7 @@ var ALL_ACTION_KINDS = [
97
107
  // src/core/constants.ts
98
108
  function resolveSdkVersion() {
99
109
  {
100
- return "0.1.31";
110
+ return "0.1.32";
101
111
  }
102
112
  }
103
113
  var SDK_VERSION = resolveSdkVersion();
@@ -637,6 +647,15 @@ var API_ROUTES = {
637
647
  installationRegister: "/sdk/installations/register",
638
648
  runtimeHeartbeat: "/sdk/heartbeat",
639
649
  chat: "/conversations/messages",
650
+ chatPrimary: "/conversations/messages",
651
+ chatFallback: "/ai/chat",
652
+ deviceAuthorize: "/cli/device/authorize",
653
+ deviceToken: "/cli/device/token",
654
+ deviceVerify: "/cli/device/verify",
655
+ deviceApprove: "/cli/device/approve",
656
+ deviceDeny: "/cli/device/deny",
657
+ authDeviceAuthorize: "/auth/device/authorize",
658
+ authDeviceToken: "/auth/device/token",
640
659
  projectApiKeyVerify: (projectId) => `/projects/${encodeURIComponent(projectId)}/api-key/verify`,
641
660
  sdkInstallationVerify: "/sdk/installations/verify"
642
661
  };
@@ -866,8 +885,8 @@ var CloudClient = class {
866
885
  const conversationPromise = (async () => {
867
886
  try {
868
887
  const requestConversationId = this.conversationId && isUuid(this.conversationId) ? this.conversationId : void 0;
869
- const response = await this.runtimeRequest({
870
- path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.chat),
888
+ let response = await this.runtimeRequest({
889
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.chatPrimary || API_ROUTES.chat),
871
890
  method: "POST",
872
891
  body: {
873
892
  projectId: this.projectId,
@@ -877,16 +896,35 @@ var CloudClient = class {
877
896
  pageUrl
878
897
  }
879
898
  }, "assistant:conversation");
880
- if (response.ok && response.data?.success === true) {
899
+ if (response.status === 404) {
900
+ response = await this.runtimeRequest({
901
+ path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.chatFallback),
902
+ method: "POST",
903
+ body: {
904
+ projectId: this.projectId,
905
+ text: trimmed,
906
+ message: trimmed,
907
+ ...requestConversationId ? { conversationId: requestConversationId } : {},
908
+ sessionId,
909
+ pageUrl
910
+ }
911
+ }, "assistant:conversation");
912
+ }
913
+ 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")) {
881
914
  const body = response.data;
915
+ const headerRequestId = response.headers?.get("x-request-id");
916
+ const bodyRequestId = typeof body?.requestId === "string" ? body.requestId : typeof body?.request_id === "string" ? body.request_id : void 0;
917
+ if (headerRequestId && bodyRequestId && headerRequestId !== bodyRequestId) {
918
+ throw new NetworkError("Asiyst returned a mismatched request identifier.");
919
+ }
882
920
  const message = body.message && typeof body.message === "object" ? body.message : void 0;
883
- const conversationId = body.conversationId;
921
+ 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)}`;
884
922
  const messageText = message?.text ?? body.response ?? body.answer;
885
- if (body.success !== true || typeof conversationId !== "string" || typeof messageText !== "string" || !messageText.trim() || message && message.role !== "assistant") {
923
+ if (typeof messageText !== "string" || !messageText.trim() || message && message.role && message.role !== "assistant") {
886
924
  throw new NetworkError("Asiyst returned an unsupported conversation response.");
887
925
  }
888
926
  this.conversationId = conversationId;
889
- const rawCitations = Array.isArray(body.sources) ? body.sources : [];
927
+ const rawCitations = Array.isArray(body.sources) ? body.sources : Array.isArray(body.citations) ? body.citations : [];
890
928
  return {
891
929
  requestId: typeof body.requestId === "string" ? body.requestId : void 0,
892
930
  conversationId,
@@ -915,11 +953,26 @@ var CloudClient = class {
915
953
  const code = typeof errorBody?.code === "string" ? errorBody.code : typeof errorRecord === "string" ? errorRecord : `HTTP_${response.status}`;
916
954
  if (response.status === 401 || response.status === 403) {
917
955
  const installationErrorCodes = {
956
+ ORIGIN_REQUIRED: "Origin header is required for runtime authorization.",
957
+ ORIGIN_NOT_APPROVED: "This origin is not approved for this project in the Asiyst dashboard.",
958
+ DOMAIN_MISMATCH: "Current website domain does not match approved domains for this project.",
959
+ PROJECT_MISMATCH: "Project configuration mismatch.",
960
+ PROJECT_DISABLED: "This Asiyst project is currently disabled.",
961
+ PROJECT_NOT_FOUND: "Asiyst project was not found. Verify your projectId.",
962
+ INVALID_PROJECT_ID: "The configured projectId is invalid.",
963
+ TOKEN_MISSING: "Runtime authorization token is missing.",
964
+ TOKEN_MALFORMED: "Runtime authorization token is malformed.",
965
+ TOKEN_SIGNATURE_INVALID: "Runtime token signature verification failed.",
966
+ TOKEN_EXPIRED: "Runtime authorization token has expired.",
967
+ TOKEN_CLAIMS_INVALID: "Runtime authorization token claims are invalid.",
968
+ ENVIRONMENT_MISMATCH: "SDK environment does not match runtime installation environment.",
969
+ INSUFFICIENT_SCOPE: "Runtime token lacks required assistant:conversation capability.",
918
970
  INSTALLATION_NOT_FOUND: "Asiyst installation not found for this domain. Re-run `asiyst connect` and verify your project domain.",
919
971
  INSTALLATION_INACTIVE: "Asiyst installation is inactive. Check your project status in the Asiyst dashboard.",
920
972
  INSTALLATION_REVOKED: "Asiyst installation has been revoked. Re-run `asiyst connect` to register a new installation.",
921
973
  INSTALLATION_PROJECT_MISMATCH: "Asiyst installation does not match the configured project.",
922
974
  INSTALLATION_DOMAIN_MISMATCH: "Asiyst installation domain does not match the current website domain.",
975
+ INSTALLATION_MISMATCH: "Asiyst installation does not match the request context.",
923
976
  RUNTIME_TOKEN_INVALID: "Asiyst runtime authorization token is invalid. The SDK will attempt to re-authorize.",
924
977
  RUNTIME_TOKEN_EXPIRED: "Asiyst runtime authorization token has expired. The SDK will re-authorize."
925
978
  };
@@ -1887,10 +1940,14 @@ var AssetLoader = class {
1887
1940
  const controller = new AbortController();
1888
1941
  this.inFlightControllers.add(controller);
1889
1942
  const abortSignal = options?.signal ? anySignal([controller.signal, options.signal]) : controller.signal;
1890
- const timeoutMs = options?.timeoutMs ?? 6e4;
1891
- const timeoutId = setTimeout(() => {
1943
+ const connectTimeoutMs = options?.timeouts?.connectTimeoutMs ?? 1e4;
1944
+ const stallTimeoutMs = options?.timeouts?.stallTimeoutMs ?? 15e3;
1945
+ const totalTimeoutMs = options?.timeouts?.totalTimeoutMs ?? options?.timeoutMs ?? 6e4;
1946
+ let timedOutReason;
1947
+ const totalTimeoutId = setTimeout(() => {
1948
+ timedOutReason = "total";
1892
1949
  controller.abort();
1893
- }, timeoutMs);
1950
+ }, totalTimeoutMs);
1894
1951
  try {
1895
1952
  const cleanPath = (sanitizedUrl.split("?")[0] ?? "").toLowerCase();
1896
1953
  const isImageExtension = /\.(png|jpe?g|webp|svg|gif|avif)$/i.test(cleanPath);
@@ -1908,27 +1965,100 @@ var AssetLoader = class {
1908
1965
  durationMs: Date.now() - startTime
1909
1966
  };
1910
1967
  }
1968
+ const maxRetries = options?.maxRetries ?? 2;
1969
+ let attempt = 0;
1911
1970
  let response;
1912
- try {
1913
- response = await fetch(sanitizedUrl, {
1914
- method: "GET",
1915
- headers: {
1916
- Accept: "model/fbx, application/octet-stream, model/gltf-binary, image/*, application/json, */*"
1917
- },
1918
- signal: abortSignal
1919
- });
1920
- } catch (err) {
1921
- if (err instanceof Error && err.name === "AbortError") {
1922
- throw new Error("Avatar asset request timed out or was aborted");
1971
+ while (true) {
1972
+ attempt++;
1973
+ let connectTimeoutId;
1974
+ try {
1975
+ const connectController = new AbortController();
1976
+ const connectSignal = anySignal([abortSignal, connectController.signal]);
1977
+ connectTimeoutId = setTimeout(() => {
1978
+ timedOutReason = "connect";
1979
+ connectController.abort();
1980
+ }, connectTimeoutMs);
1981
+ response = await fetch(sanitizedUrl, {
1982
+ method: "GET",
1983
+ headers: {
1984
+ Accept: "model/fbx, application/octet-stream, model/gltf-binary, image/*, application/json, */*"
1985
+ },
1986
+ signal: connectSignal
1987
+ });
1988
+ } catch (err) {
1989
+ if (connectTimeoutId) clearTimeout(connectTimeoutId);
1990
+ if (timedOutReason) {
1991
+ throw new AsiystError({
1992
+ code: "ASSET_TIMEOUT",
1993
+ message: `Avatar asset request timed out (${timedOutReason} timeout)`
1994
+ });
1995
+ }
1996
+ if (abortSignal.aborted || err instanceof Error && err.name === "AbortError") {
1997
+ if (options?.signal?.aborted || abortSignal.aborted) {
1998
+ const cancelErr = new AsiystError({
1999
+ code: "OPERATION_CANCELLED",
2000
+ message: "Avatar asset request was cancelled",
2001
+ cause: err
2002
+ });
2003
+ cancelErr.name = "AbortError";
2004
+ throw cancelErr;
2005
+ }
2006
+ throw new AsiystError({
2007
+ code: "ASSET_TIMEOUT",
2008
+ message: "Avatar asset request timed out or was aborted"
2009
+ });
2010
+ }
2011
+ if (attempt <= maxRetries && !abortSignal.aborted) {
2012
+ const delay = Math.min(1e3 * Math.pow(2, attempt - 1), 4e3);
2013
+ await new Promise((r) => setTimeout(r, delay));
2014
+ continue;
2015
+ }
2016
+ throw new AsiystError({
2017
+ code: "NETWORK_ERROR",
2018
+ message: `CORS or network policy blocked avatar asset retrieval from ${sanitizedUrl}`,
2019
+ cause: err
2020
+ });
2021
+ } finally {
2022
+ if (connectTimeoutId) clearTimeout(connectTimeoutId);
2023
+ }
2024
+ if (response.status >= 500 && attempt <= maxRetries) {
2025
+ const retryAfter = Number(response.headers.get("retry-after"));
2026
+ const delay = Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1e3 : Math.min(1e3 * Math.pow(2, attempt - 1), 4e3);
2027
+ await new Promise((r) => setTimeout(r, delay));
2028
+ continue;
1923
2029
  }
1924
- throw new Error(`CORS or network policy blocked avatar asset retrieval from ${sanitizedUrl}`);
2030
+ break;
1925
2031
  }
1926
2032
  if (!response.ok) {
1927
- throw new Error(`Avatar asset download failed: HTTP ${response.status} from ${sanitizedUrl}`);
2033
+ if (response.status === 403) {
2034
+ throw new AsiystError({
2035
+ code: "DOMAIN_NOT_APPROVED",
2036
+ status: 403,
2037
+ message: `Avatar asset request forbidden (HTTP 403) from ${sanitizedUrl}`,
2038
+ hint: "Check that the current website domain or origin is approved in the project settings."
2039
+ });
2040
+ }
2041
+ if (response.status === 404) {
2042
+ throw new AsiystError({
2043
+ code: "AVATAR_NOT_FOUND",
2044
+ status: 404,
2045
+ message: `Avatar asset not found (HTTP 404) at ${sanitizedUrl}`,
2046
+ hint: "Verify the avatarId and ensure a 3D model asset is published for this avatar."
2047
+ });
2048
+ }
2049
+ throw new AsiystError({
2050
+ code: "NETWORK_ERROR",
2051
+ status: response.status,
2052
+ message: `Avatar asset download failed: HTTP ${response.status} from ${sanitizedUrl}`
2053
+ });
1928
2054
  }
1929
2055
  const contentType = (response.headers.get("content-type") || "").toLowerCase();
1930
2056
  if (contentType.includes("text/html")) {
1931
- throw new Error(`Avatar asset request returned HTML instead of 3D asset from ${sanitizedUrl}`);
2057
+ throw new AsiystError({
2058
+ code: "ASSET_PARSE_FAILED",
2059
+ message: `Avatar asset request returned HTML instead of 3D asset from ${sanitizedUrl}`,
2060
+ hint: "The server returned a web page instead of 3D asset bytes. Check authentication or routing."
2061
+ });
1932
2062
  }
1933
2063
  if (isJsonExtension || contentType.includes("application/json")) {
1934
2064
  const text = await response.text();
@@ -1936,10 +2066,16 @@ var AssetLoader = class {
1936
2066
  try {
1937
2067
  manifest = JSON.parse(text);
1938
2068
  } catch {
1939
- throw new Error("Invalid avatar manifest: JSON decoding failed");
2069
+ throw new AsiystError({
2070
+ code: "ASSET_PARSE_FAILED",
2071
+ message: "Invalid avatar manifest: JSON decoding failed"
2072
+ });
1940
2073
  }
1941
2074
  if (typeof manifest !== "object" || manifest === null || Array.isArray(manifest)) {
1942
- throw new Error("Invalid avatar manifest schema");
2075
+ throw new AsiystError({
2076
+ code: "ASSET_PARSE_FAILED",
2077
+ message: "Invalid avatar manifest schema"
2078
+ });
1943
2079
  }
1944
2080
  return {
1945
2081
  format: "manifest",
@@ -1959,9 +2095,104 @@ var AssetLoader = class {
1959
2095
  durationMs: Date.now() - startTime
1960
2096
  };
1961
2097
  }
1962
- const arrayBuffer = await response.arrayBuffer();
2098
+ let arrayBuffer;
2099
+ const contentLengthHeader = response.headers.get("content-length");
2100
+ const contentLength = contentLengthHeader ? parseInt(contentLengthHeader, 10) : 0;
2101
+ const totalBytes = Number.isFinite(contentLength) && contentLength > 0 ? contentLength : void 0;
2102
+ const assetName = options?.assetName ?? cleanPath.split("/").pop() ?? "avatar";
2103
+ if (response.body && typeof response.body.getReader === "function") {
2104
+ const reader = response.body.getReader();
2105
+ const chunks = [];
2106
+ let loadedBytes = 0;
2107
+ let stallTimeoutId;
2108
+ const resetStallTimer = () => {
2109
+ if (stallTimeoutId) clearTimeout(stallTimeoutId);
2110
+ stallTimeoutId = setTimeout(() => {
2111
+ timedOutReason = "stall";
2112
+ controller.abort();
2113
+ }, stallTimeoutMs);
2114
+ };
2115
+ resetStallTimer();
2116
+ const onAbort = () => {
2117
+ try {
2118
+ void reader.cancel(timedOutReason || "aborted");
2119
+ } catch {
2120
+ }
2121
+ };
2122
+ abortSignal.addEventListener("abort", onAbort, { once: true });
2123
+ if (abortSignal.aborted) onAbort();
2124
+ try {
2125
+ while (true) {
2126
+ if (abortSignal.aborted) {
2127
+ const err = new AsiystError({
2128
+ code: "OPERATION_CANCELLED",
2129
+ message: "Avatar asset download was cancelled"
2130
+ });
2131
+ err.name = "AbortError";
2132
+ throw err;
2133
+ }
2134
+ const { done, value } = await reader.read();
2135
+ if (done) break;
2136
+ if (value) {
2137
+ chunks.push(value);
2138
+ loadedBytes += value.byteLength;
2139
+ resetStallTimer();
2140
+ const percentage = totalBytes ? Math.min(100, Math.round(loadedBytes / totalBytes * 100)) : void 0;
2141
+ options?.onProgress?.({
2142
+ stage: "downloading",
2143
+ loadedBytes,
2144
+ totalBytes,
2145
+ percentage,
2146
+ assetName
2147
+ });
2148
+ }
2149
+ }
2150
+ } catch (streamErr) {
2151
+ if (timedOutReason) {
2152
+ throw new AsiystError({
2153
+ code: "ASSET_TIMEOUT",
2154
+ message: `Avatar asset request timed out (${timedOutReason} timeout)`
2155
+ });
2156
+ }
2157
+ if (abortSignal.aborted) {
2158
+ const cancelErr = new AsiystError({
2159
+ code: "OPERATION_CANCELLED",
2160
+ message: "Avatar asset download was cancelled",
2161
+ cause: streamErr
2162
+ });
2163
+ cancelErr.name = "AbortError";
2164
+ throw cancelErr;
2165
+ }
2166
+ throw streamErr;
2167
+ } finally {
2168
+ if (stallTimeoutId) clearTimeout(stallTimeoutId);
2169
+ try {
2170
+ reader.releaseLock();
2171
+ } catch {
2172
+ }
2173
+ }
2174
+ const combined = new Uint8Array(loadedBytes);
2175
+ let offset = 0;
2176
+ for (const chunk of chunks) {
2177
+ combined.set(chunk, offset);
2178
+ offset += chunk.byteLength;
2179
+ }
2180
+ arrayBuffer = combined.buffer;
2181
+ } else {
2182
+ arrayBuffer = await response.arrayBuffer();
2183
+ options?.onProgress?.({
2184
+ stage: "downloading",
2185
+ loadedBytes: arrayBuffer.byteLength,
2186
+ totalBytes: arrayBuffer.byteLength,
2187
+ percentage: 100,
2188
+ assetName
2189
+ });
2190
+ }
1963
2191
  if (arrayBuffer.byteLength < 12) {
1964
- throw new Error("Avatar asset payload is too small to be a valid 3D container");
2192
+ throw new AsiystError({
2193
+ code: "ASSET_PARSE_FAILED",
2194
+ message: "Avatar asset payload is too small to be a valid 3D container"
2195
+ });
1965
2196
  }
1966
2197
  if (options?.integrity) {
1967
2198
  await verifyIntegrity(arrayBuffer, options.integrity);
@@ -1969,18 +2200,33 @@ var AssetLoader = class {
1969
2200
  const headerBytes = new Uint8Array(arrayBuffer, 0, Math.min(256, arrayBuffer.byteLength));
1970
2201
  const headerStr = new TextDecoder("utf-8", { fatal: false }).decode(headerBytes).trim();
1971
2202
  if (/^<!DOCTYPE\s+html/i.test(headerStr) || /^<html/i.test(headerStr)) {
1972
- throw new Error(`Avatar asset payload contains HTML error page instead of binary 3D container from ${sanitizedUrl}`);
2203
+ throw new AsiystError({
2204
+ code: "ASSET_PARSE_FAILED",
2205
+ message: `Avatar asset payload contains HTML error page instead of binary 3D container from ${sanitizedUrl}`
2206
+ });
1973
2207
  }
1974
2208
  const hasFbxSignature = this.isFbxBuffer(arrayBuffer);
1975
2209
  const hasGlbSignature = this.isGlbBuffer(arrayBuffer);
1976
2210
  const isFbx = hasFbxSignature || !hasGlbSignature && isFbxExtension;
1977
2211
  const isGlb = hasGlbSignature || !hasFbxSignature && isGlbExtension;
1978
2212
  if (isFbx && isGlb) {
1979
- throw new Error("Avatar asset format is ambiguous");
2213
+ throw new AsiystError({
2214
+ code: "ASSET_PARSE_FAILED",
2215
+ message: "Avatar asset format is ambiguous"
2216
+ });
1980
2217
  }
1981
2218
  if (isFbx) {
1982
2219
  if (options?.expectedFormat && options.expectedFormat !== "fbx") {
1983
- throw new Error(`Avatar asset format mismatch: expected ${options.expectedFormat}, received fbx`);
2220
+ throw new AsiystError({
2221
+ code: "ASSET_PARSE_FAILED",
2222
+ message: `Avatar asset format mismatch: expected ${options.expectedFormat}, received fbx`
2223
+ });
2224
+ }
2225
+ if (arrayBuffer.byteLength > 10 * 1024 * 1024) {
2226
+ const mb = (arrayBuffer.byteLength / (1024 * 1024)).toFixed(1);
2227
+ if (typeof console !== "undefined" && typeof console.warn === "function") {
2228
+ 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).`);
2229
+ }
1984
2230
  }
1985
2231
  const fbxHeader = this.parseFbxHeader(arrayBuffer);
1986
2232
  const resourcePath = sanitizedUrl.includes("/") ? sanitizedUrl.substring(0, sanitizedUrl.lastIndexOf("/") + 1) : "";
@@ -1995,10 +2241,16 @@ var AssetLoader = class {
1995
2241
  };
1996
2242
  }
1997
2243
  if (!isGlb) {
1998
- throw new Error("Avatar asset format is unsupported; expected FBX or GLB");
2244
+ throw new AsiystError({
2245
+ code: "ASSET_PARSE_FAILED",
2246
+ message: "Avatar asset format is unsupported; expected FBX or GLB"
2247
+ });
1999
2248
  }
2000
2249
  if (options?.expectedFormat && options.expectedFormat !== "glb") {
2001
- throw new Error(`Avatar asset format mismatch: expected ${options.expectedFormat}, received glb`);
2250
+ throw new AsiystError({
2251
+ code: "ASSET_PARSE_FAILED",
2252
+ message: `Avatar asset format mismatch: expected ${options.expectedFormat}, received glb`
2253
+ });
2002
2254
  }
2003
2255
  const parsedGlb = this.parseGlb(arrayBuffer);
2004
2256
  return {
@@ -2012,7 +2264,7 @@ var AssetLoader = class {
2012
2264
  durationMs: Date.now() - startTime
2013
2265
  };
2014
2266
  } finally {
2015
- clearTimeout(timeoutId);
2267
+ clearTimeout(totalTimeoutId);
2016
2268
  this.inFlightControllers.delete(controller);
2017
2269
  }
2018
2270
  }
@@ -2280,6 +2532,7 @@ var FbxRenderer = class {
2280
2532
  this.mixer = null;
2281
2533
  this.allAnimations = [];
2282
2534
  this.animationMetadataList = [];
2535
+ this.failedAnimations = /* @__PURE__ */ new Map();
2283
2536
  this.assetLoader = new AssetLoader();
2284
2537
  this.currentAction = null;
2285
2538
  this.animFrameId = null;
@@ -2596,9 +2849,11 @@ var FbxRenderer = class {
2596
2849
  });
2597
2850
  extractedClips = gltf.animations || [];
2598
2851
  }
2852
+ let anyExtracted = false;
2599
2853
  for (const rawClip of extractedClips) {
2600
2854
  const retargeted = this.retargetClip(rawClip, this.rawObject);
2601
2855
  if (!retargeted) continue;
2856
+ anyExtracted = true;
2602
2857
  retargeted.name = anim.clipName || anim.name || rawClip.name;
2603
2858
  this.allAnimations.push(retargeted);
2604
2859
  this.animationMetadataList.push({
@@ -2610,9 +2865,21 @@ var FbxRenderer = class {
2610
2865
  clip: retargeted
2611
2866
  });
2612
2867
  }
2868
+ if (!anyExtracted && extractedClips.length > 0) {
2869
+ this.failedAnimations.set(anim.id || anim.name, {
2870
+ error: `Animation "${anim.name}" contains no compatible skeleton bone tracks`,
2871
+ code: "INCOMPATIBLE_SKELETON",
2872
+ id: anim.id
2873
+ });
2874
+ }
2613
2875
  } catch (err) {
2876
+ const msg = err instanceof Error ? err.message : String(err);
2877
+ this.failedAnimations.set(anim.id || anim.name, {
2878
+ error: msg,
2879
+ code: "LOAD_FAILED",
2880
+ id: anim.id
2881
+ });
2614
2882
  if (typeof console !== "undefined" && typeof console.warn === "function") {
2615
- const msg = err instanceof Error ? err.message : String(err);
2616
2883
  console.warn(`[asiyst] Failed to load external animation "${anim.name}": ${msg}`);
2617
2884
  }
2618
2885
  }
@@ -2626,6 +2893,13 @@ var FbxRenderer = class {
2626
2893
  }
2627
2894
  }
2628
2895
  }
2896
+ getFailedAnimations() {
2897
+ const list = [];
2898
+ for (const [name, info] of this.failedAnimations.entries()) {
2899
+ list.push({ name, id: info.id, error: info.error, code: info.code });
2900
+ }
2901
+ return list;
2902
+ }
2629
2903
  retargetClip(clip, targetObject) {
2630
2904
  const targetNodeNames = /* @__PURE__ */ new Set();
2631
2905
  const boneLookup = /* @__PURE__ */ new Map();
@@ -3083,6 +3357,70 @@ var AVATAR_CSS = `
3083
3357
  .asiyst-open-chat-btn svg {
3084
3358
  stroke: #fbbf24;
3085
3359
  }
3360
+ .asiyst-avatar-error-panel {
3361
+ display: flex;
3362
+ flex-direction: column;
3363
+ gap: 8px;
3364
+ padding: 12px;
3365
+ background: #0f172a;
3366
+ color: #f8fafc;
3367
+ border: 1px solid #ef4444;
3368
+ border-radius: 8px;
3369
+ font: 12px/1.4 system-ui, -apple-system, sans-serif;
3370
+ max-width: 220px;
3371
+ box-shadow: 0 10px 25px rgba(0, 0, 0, 0.4);
3372
+ pointer-events: auto;
3373
+ text-align: left;
3374
+ }
3375
+ .asiyst-avatar-error-title {
3376
+ font-weight: 700;
3377
+ color: #f87171;
3378
+ font-size: 13px;
3379
+ }
3380
+ .asiyst-avatar-error-code {
3381
+ font-family: monospace;
3382
+ background: rgba(239, 68, 68, 0.2);
3383
+ padding: 2px 4px;
3384
+ border-radius: 4px;
3385
+ color: #fca5a5;
3386
+ display: inline-block;
3387
+ }
3388
+ .asiyst-avatar-error-hint {
3389
+ font-size: 11px;
3390
+ color: #94a3b8;
3391
+ }
3392
+ .asiyst-avatar-error-chat {
3393
+ margin-top: 4px;
3394
+ font-size: 11px;
3395
+ color: #60a5fa;
3396
+ cursor: pointer;
3397
+ text-decoration: underline;
3398
+ }
3399
+ .asiyst-avatar-progress-container {
3400
+ display: flex;
3401
+ flex-direction: column;
3402
+ align-items: center;
3403
+ width: 140px;
3404
+ margin-top: 8px;
3405
+ pointer-events: none;
3406
+ }
3407
+ .asiyst-avatar-progress-bar {
3408
+ width: 100%;
3409
+ height: 4px;
3410
+ background: rgba(255, 255, 255, 0.15);
3411
+ border-radius: 2px;
3412
+ overflow: hidden;
3413
+ }
3414
+ .asiyst-avatar-progress-fill {
3415
+ height: 100%;
3416
+ background: #3b82f6;
3417
+ transition: width 0.2s ease;
3418
+ }
3419
+ .asiyst-avatar-progress-text {
3420
+ font-size: 10px;
3421
+ color: #94a3b8;
3422
+ margin-top: 4px;
3423
+ }
3086
3424
  @media (prefers-reduced-motion: reduce) {
3087
3425
  .asiyst-avatar.asiyst-animate { transition: none; }
3088
3426
  .asiyst-avatar-loader { animation: none; }
@@ -3106,6 +3444,9 @@ var CssAvatarRenderer = class {
3106
3444
  this.isAssetLoadedFlag = false;
3107
3445
  this.isFallbackFlag = false;
3108
3446
  }
3447
+ setFallbackOptions(opts) {
3448
+ this.fallbackOptions = opts;
3449
+ }
3109
3450
  setMetricsTracker(tracker) {
3110
3451
  this.metricsTracker = tracker;
3111
3452
  }
@@ -3247,10 +3588,13 @@ var CssAvatarRenderer = class {
3247
3588
  this.chatActionBtn.style.display = open ? "none" : "inline-flex";
3248
3589
  }
3249
3590
  }
3250
- async loadAsset(config, metricsTracker) {
3591
+ async loadAsset(config, metricsTracker, options) {
3251
3592
  if (metricsTracker) {
3252
3593
  this.metricsTracker = metricsTracker;
3253
3594
  }
3595
+ if (options?.fallback) {
3596
+ this.fallbackOptions = options.fallback;
3597
+ }
3254
3598
  const assetUrl = config.assetUrl ?? config.thumbnailUrl;
3255
3599
  if (!assetUrl) {
3256
3600
  this.renderState = "idle";
@@ -3286,7 +3630,12 @@ var CssAvatarRenderer = class {
3286
3630
  const asset = await this.assetLoader.load(assetUrl, {
3287
3631
  timeoutMs: 6e4,
3288
3632
  integrity: config.assetIntegrity,
3289
- expectedFormat: config.assetUrl ? config.modelFormat : void 0
3633
+ expectedFormat: config.assetUrl ? config.modelFormat : void 0,
3634
+ assetName: config.avatarName,
3635
+ onProgress: (p) => {
3636
+ this.updateProgress(p);
3637
+ options?.onProgress?.(p);
3638
+ }
3290
3639
  });
3291
3640
  this.metricsTracker?.record("assetDownloadComplete");
3292
3641
  const byteSize = asset.buffer?.byteLength ?? asset.bin?.byteLength ?? asset.size;
@@ -3316,28 +3665,153 @@ var CssAvatarRenderer = class {
3316
3665
  }
3317
3666
  return true;
3318
3667
  } catch (err) {
3319
- const message = err instanceof Error ? err.message : "Failed to load avatar asset";
3320
- this.lastErrorMessage = message;
3668
+ const errorObj = err instanceof Error ? err : new Error(String(err));
3669
+ this.lastErrorMessage = errorObj.message;
3321
3670
  this.renderState = "error";
3322
3671
  this.isAssetLoadedFlag = false;
3323
3672
  this.isFallbackFlag = true;
3673
+ if (this.nameTagEl) {
3674
+ this.nameTagEl.style.display = "none";
3675
+ }
3676
+ this.renderErrorState(errorObj, this.fallbackOptions);
3677
+ return false;
3678
+ }
3679
+ }
3680
+ updateProgress(progress) {
3681
+ if (!this.viewport || this.renderState !== "loading") return;
3682
+ const loader = this.viewport.querySelector(".asiyst-avatar-loader") ?? this.viewport.querySelector(".asiyst-avatar-loading-silhouette");
3683
+ if (!loader) return;
3684
+ let progressBox = loader.querySelector(".asiyst-avatar-progress-container");
3685
+ if (!progressBox) {
3686
+ const doc = this.viewport.ownerDocument;
3687
+ progressBox = doc.createElement("div");
3688
+ progressBox.className = "asiyst-avatar-progress-container";
3689
+ progressBox.innerHTML = `
3690
+ <div class="asiyst-avatar-progress-bar"><div class="asiyst-avatar-progress-fill" style="width: 0%"></div></div>
3691
+ <div class="asiyst-avatar-progress-text"></div>
3692
+ `;
3693
+ loader.appendChild(progressBox);
3694
+ }
3695
+ const fill = progressBox.querySelector(".asiyst-avatar-progress-fill");
3696
+ const text = progressBox.querySelector(".asiyst-avatar-progress-text");
3697
+ if (fill && typeof progress.percentage === "number") {
3698
+ fill.style.width = `${progress.percentage}%`;
3699
+ }
3700
+ if (text) {
3701
+ if (progress.loadedBytes && progress.totalBytes) {
3702
+ const loadedMb = (progress.loadedBytes / (1024 * 1024)).toFixed(1);
3703
+ const totalMb = (progress.totalBytes / (1024 * 1024)).toFixed(1);
3704
+ text.textContent = `${progress.stage || "Loading"} ${loadedMb}MB / ${totalMb}MB`;
3705
+ } else if (progress.loadedBytes) {
3706
+ const loadedMb = (progress.loadedBytes / (1024 * 1024)).toFixed(1);
3707
+ text.textContent = `${progress.stage || "Loading"} ${loadedMb}MB`;
3708
+ } else {
3709
+ text.textContent = progress.stage || "Loading...";
3710
+ }
3711
+ }
3712
+ }
3713
+ renderErrorState(error, fallbackOptions) {
3714
+ this.renderState = "error";
3715
+ this.isAssetLoadedFlag = false;
3716
+ this.isFallbackFlag = true;
3717
+ this.lastErrorMessage = error.message;
3718
+ if (!this.viewport) return;
3719
+ this.viewport.replaceChildren();
3720
+ const doc = this.viewport.ownerDocument;
3721
+ const opts = fallbackOptions ?? this.fallbackOptions;
3722
+ if (opts?.mode === "image" && opts.imageUrl) {
3723
+ if (this.figure) {
3724
+ this.figure.setAttribute("data-state", "ready");
3725
+ this.figure.classList.add("asiyst-3d-active");
3726
+ this.figure.classList.remove("asiyst-compact-launcher");
3727
+ this.figure.style.background = "transparent";
3728
+ }
3729
+ const img = doc.createElement("img");
3730
+ img.className = "asiyst-avatar-graphic";
3731
+ img.src = opts.imageUrl;
3732
+ img.alt = `${this.avatarName} fallback avatar`;
3733
+ this.viewport.appendChild(img);
3734
+ return;
3735
+ }
3736
+ if (opts?.mode === "chat-only") {
3324
3737
  if (this.figure) {
3325
- this.figure.setAttribute("data-state", "error");
3738
+ this.figure.setAttribute("data-state", "ready");
3326
3739
  this.figure.classList.remove("asiyst-3d-active");
3327
3740
  this.figure.classList.add("asiyst-compact-launcher");
3328
3741
  this.figure.style.width = `${this.size}px`;
3329
3742
  this.figure.style.height = `${this.size}px`;
3330
3743
  this.figure.style.background = this.accentColor;
3331
3744
  }
3332
- if (this.nameTagEl) {
3333
- this.nameTagEl.style.display = "none";
3334
- }
3335
- if (this.chatActionBtn) {
3336
- this.chatActionBtn.style.display = "none";
3745
+ this.renderFallback(false);
3746
+ return;
3747
+ }
3748
+ if (opts?.mode === "2d") {
3749
+ if (this.figure) {
3750
+ this.figure.setAttribute("data-state", "ready");
3751
+ this.figure.classList.remove("asiyst-3d-active");
3752
+ this.figure.classList.add("asiyst-compact-launcher");
3753
+ this.figure.style.width = `${this.size}px`;
3754
+ this.figure.style.height = `${this.size}px`;
3755
+ this.figure.style.background = this.accentColor;
3337
3756
  }
3338
3757
  this.renderFallback(true);
3339
- return false;
3758
+ return;
3759
+ }
3760
+ if (this.figure) {
3761
+ this.figure.setAttribute("data-state", "error");
3762
+ this.figure.classList.add("asiyst-3d-active");
3763
+ this.figure.classList.remove("asiyst-compact-launcher");
3764
+ this.figure.style.background = "transparent";
3340
3765
  }
3766
+ const isDev = typeof window !== "undefined" && (window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1" || window.location.hostname === "::1");
3767
+ const panel = doc.createElement("div");
3768
+ panel.className = "asiyst-avatar-error-panel";
3769
+ panel.setAttribute("data-fallback", "true");
3770
+ panel.setAttribute("data-state", "error");
3771
+ if (isDev) {
3772
+ const title = doc.createElement("div");
3773
+ title.className = "asiyst-avatar-error-title";
3774
+ title.textContent = "Avatar could not be loaded";
3775
+ const errCode = (error instanceof AsiystError ? error.code : "ERROR") || "ERROR";
3776
+ const codeDiv = doc.createElement("div");
3777
+ codeDiv.textContent = "Error: ";
3778
+ const codeSpan = doc.createElement("span");
3779
+ codeSpan.className = "asiyst-avatar-error-code";
3780
+ codeSpan.textContent = String(errCode);
3781
+ codeDiv.appendChild(codeSpan);
3782
+ const originDiv = doc.createElement("div");
3783
+ originDiv.className = "asiyst-avatar-error-hint";
3784
+ const currentOrigin = typeof window !== "undefined" ? window.location.origin : "unknown";
3785
+ originDiv.textContent = `Origin: ${currentOrigin}`;
3786
+ const hintDiv = doc.createElement("div");
3787
+ hintDiv.className = "asiyst-avatar-error-hint";
3788
+ 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);
3789
+ hintDiv.textContent = `Fix: ${hintText}`;
3790
+ const chatLink = doc.createElement("div");
3791
+ chatLink.className = "asiyst-avatar-error-chat";
3792
+ chatLink.textContent = "Open chat widget \u2192";
3793
+ chatLink.addEventListener("click", (e) => {
3794
+ e.stopPropagation();
3795
+ this.onOpenChat?.();
3796
+ });
3797
+ panel.append(title, codeDiv, originDiv, hintDiv, chatLink);
3798
+ } else {
3799
+ const title = doc.createElement("div");
3800
+ title.className = "asiyst-avatar-error-title";
3801
+ title.textContent = "Your assistant is temporarily unavailable.";
3802
+ const sub = doc.createElement("div");
3803
+ sub.className = "asiyst-avatar-error-hint";
3804
+ sub.textContent = "You can still continue using chat.";
3805
+ const chatLink = doc.createElement("div");
3806
+ chatLink.className = "asiyst-avatar-error-chat";
3807
+ chatLink.textContent = "Open chat widget \u2192";
3808
+ chatLink.addEventListener("click", (e) => {
3809
+ e.stopPropagation();
3810
+ this.onOpenChat?.();
3811
+ });
3812
+ panel.append(title, sub, chatLink);
3813
+ }
3814
+ this.viewport.appendChild(panel);
3341
3815
  }
3342
3816
  renderLoader() {
3343
3817
  if (!this.viewport) return;
@@ -4824,6 +5298,11 @@ var AsiystRuntime = class {
4824
5298
  this.connectionStatus = "disconnected";
4825
5299
  this.verificationStatus = "not_detected";
4826
5300
  this.rescanDebounced = debounce(() => this.rescan(), DOM_SCAN_DEBOUNCE_MS);
5301
+ this.state = "idle";
5302
+ this.avatarLifecycleState = "initializing";
5303
+ this.chatLifecycleState = "initializing";
5304
+ this.isDebug = false;
5305
+ this.errorsObserved = [];
4827
5306
  this.isHeartbeatInFlight = false;
4828
5307
  this.lastHeartbeatTime = 0;
4829
5308
  this.nextHeartbeatAfterMs = HEARTBEAT_INTERVAL_MS;
@@ -4864,6 +5343,8 @@ var AsiystRuntime = class {
4864
5343
  () => this.map.list()
4865
5344
  );
4866
5345
  this.renderer = new CssAvatarRenderer();
5346
+ this.isDebug = Boolean(options.debug) || typeof win !== "undefined" && Boolean(win.location?.search?.includes("asiyst_debug=1"));
5347
+ this.renderer.setFallbackOptions(options.fallback);
4867
5348
  this.renderer.onOpenChat = () => this.open();
4868
5349
  this.renderer.mount(this.host.chrome, this.config.get());
4869
5350
  this.metricsTracker.record("sdkInit");
@@ -4910,6 +5391,47 @@ var AsiystRuntime = class {
4910
5391
  figure.addEventListener("click", this.figureClickListener);
4911
5392
  }
4912
5393
  }
5394
+ getState() {
5395
+ return this.state;
5396
+ }
5397
+ getAvatarState() {
5398
+ return this.avatarLifecycleState;
5399
+ }
5400
+ getChatState() {
5401
+ return this.chatLifecycleState;
5402
+ }
5403
+ setAvatarLifecycleState(next) {
5404
+ if (this.avatarLifecycleState === next) return;
5405
+ this.avatarLifecycleState = next;
5406
+ this.events.emit("asiyst:avatar:state", { state: next });
5407
+ }
5408
+ setChatLifecycleState(next) {
5409
+ if (this.chatLifecycleState === next) return;
5410
+ this.chatLifecycleState = next;
5411
+ this.events.emit("asiyst:chat:state", { state: next });
5412
+ }
5413
+ setState(nextState, details) {
5414
+ if (this.state === nextState) return;
5415
+ const prevState = this.state;
5416
+ this.state = nextState;
5417
+ if (this.isDebug) {
5418
+ console.log(`[asiyst] State transition: ${prevState} -> ${nextState}`, details ?? "");
5419
+ }
5420
+ this.events.emit("state", nextState);
5421
+ this.events.emit("asiyst:state", { state: nextState, previousState: prevState, details });
5422
+ }
5423
+ recordError(error) {
5424
+ const errObj = {
5425
+ code: "code" in error && error.code ? String(error.code) : "UNKNOWN_ERROR",
5426
+ message: error.message,
5427
+ hint: "hint" in error ? error.hint : void 0,
5428
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
5429
+ };
5430
+ this.errorsObserved.push(errObj);
5431
+ if (this.isDebug) {
5432
+ console.error("[asiyst] Error recorded:", errObj);
5433
+ }
5434
+ }
4913
5435
  async start() {
4914
5436
  this.events.emit("asiyst:initialized", { projectId: this.options.projectId });
4915
5437
  this.avatar.show();
@@ -4921,36 +5443,113 @@ var AsiystRuntime = class {
4921
5443
  installationId: this.installationId,
4922
5444
  sdkVersion: SDK_VERSION
4923
5445
  });
5446
+ this.setState("registering");
4924
5447
  try {
4925
5448
  await this.registerInstallation();
4926
5449
  } catch (error) {
4927
5450
  this.connectionStatus = "offline";
4928
5451
  this.verificationStatus = "error";
5452
+ 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);
5453
+ if (isDomainAuthFailure) {
5454
+ const isLocal = /^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i.test(window.location.hostname);
5455
+ const domainErr = new AsiystError({
5456
+ code: "DOMAIN_NOT_APPROVED",
5457
+ message: error instanceof Error ? error.message : "The website domain is not approved for this project.",
5458
+ 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.`,
5459
+ status: 403,
5460
+ cause: error
5461
+ });
5462
+ this.recordError(domainErr);
5463
+ this.renderer.renderErrorState(domainErr, this.options.fallback);
5464
+ this.setAvatarLifecycleState("error");
5465
+ this.setChatLifecycleState("error");
5466
+ this.setState("error", { reason: "domain_not_authorized", code: domainErr.code });
5467
+ this.events.emit("asiyst:error", {
5468
+ code: "domain_not_authorized",
5469
+ message: domainErr.message
5470
+ });
5471
+ this.events.emit("error", domainErr);
5472
+ return;
5473
+ }
5474
+ const asiystErr = error instanceof AsiystError ? error : new AsiystError({
5475
+ code: "AUTHENTICATION_FAILED",
5476
+ message: error instanceof Error ? error.message : "Asiyst runtime connection failed.",
5477
+ cause: error
5478
+ });
5479
+ this.recordError(asiystErr);
4929
5480
  this.events.emit("asiyst:error", {
4930
- // Safe diagnostic code — does not expose secrets or signing details.
4931
5481
  code: "installation_registration_failed",
4932
- message: error instanceof Error ? error.message : "Asiyst runtime connection failed."
5482
+ message: asiystErr.message
5483
+ });
5484
+ this.events.emit("error", asiystErr);
5485
+ }
5486
+ this.setState("authorizing");
5487
+ if (this.runtimeAuth && this.registrationSucceeded) {
5488
+ try {
5489
+ await this.runtimeAuth.getToken();
5490
+ } catch (authErr) {
5491
+ const asiystErr = authErr instanceof AsiystError ? authErr : new AsiystError({
5492
+ code: "AUTHENTICATION_FAILED",
5493
+ message: authErr instanceof Error ? authErr.message : "Runtime authorization failed.",
5494
+ cause: authErr
5495
+ });
5496
+ this.recordError(asiystErr);
5497
+ this.events.emit("asiyst:error", {
5498
+ code: "runtime_authorization_failed",
5499
+ message: asiystErr.message
5500
+ });
5501
+ this.events.emit("error", asiystErr);
5502
+ }
5503
+ }
5504
+ this.setState("fetching-config");
5505
+ let cfg;
5506
+ try {
5507
+ cfg = await isolateAsync(() => this.config.refresh(), this.config.get());
5508
+ this.metricsTracker.record("configRetrieved");
5509
+ } catch (configErr) {
5510
+ const asiystErr = new AsiystError({
5511
+ code: "CONFIG_INVALID",
5512
+ message: configErr instanceof Error ? configErr.message : "Failed to load project configuration.",
5513
+ cause: configErr
4933
5514
  });
5515
+ this.recordError(asiystErr);
5516
+ this.events.emit("error", asiystErr);
5517
+ cfg = this.config.get();
4934
5518
  }
4935
- const cfg = await isolateAsync(() => this.config.refresh(), this.config.get());
4936
- this.metricsTracker.record("configRetrieved");
4937
5519
  const domainCheck = validateWebsiteDomain(cfg, window.location.href);
4938
5520
  if (!domainCheck.allowed) {
4939
5521
  this.connectionStatus = "disconnected";
4940
5522
  this.verificationStatus = "not_detected";
5523
+ const isLocal = /^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i.test(window.location.hostname);
5524
+ const domainErr = new AsiystError({
5525
+ code: "DOMAIN_NOT_APPROVED",
5526
+ message: `This website domain (${window.location.hostname}) is not authorized for the current Asiyst project.`,
5527
+ 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.`,
5528
+ status: 403
5529
+ });
5530
+ this.recordError(domainErr);
5531
+ this.renderer.renderErrorState(domainErr, this.options.fallback);
5532
+ this.setAvatarLifecycleState("error");
5533
+ this.setChatLifecycleState("error");
5534
+ this.setState("error", { reason: "domain_not_authorized", code: domainErr.code });
4941
5535
  this.events.emit("asiyst:error", {
4942
5536
  code: "domain_not_authorized",
4943
- message: "This website is not authorized for the current Asiyst project."
5537
+ message: domainErr.message
4944
5538
  });
5539
+ this.events.emit("error", domainErr);
4945
5540
  return;
4946
5541
  }
4947
5542
  this.avatar.applyConfig(cfg);
4948
5543
  this.movement.goToAnchor();
5544
+ this.setChatLifecycleState("ready");
5545
+ this.setState("loading-avatar");
5546
+ this.setAvatarLifecycleState("loading");
4949
5547
  this.events.emit("asiyst:ready", { projectId: this.options.projectId, configVersion: cfg.version });
4950
5548
  const assetTarget = cfg.assetUrl ?? cfg.thumbnailUrl;
5549
+ let avatarLoadedSuccessfully = false;
4951
5550
  if (assetTarget) {
4952
5551
  try {
4953
- await this.loadAvatarAsset(cfg, assetTarget);
5552
+ avatarLoadedSuccessfully = await this.loadAvatarAsset(cfg, assetTarget);
4954
5553
  } finally {
4955
5554
  this.avatar.show();
4956
5555
  this.movement.goToAnchor();
@@ -4958,6 +5557,17 @@ var AsiystRuntime = class {
4958
5557
  } else {
4959
5558
  this.avatar.show();
4960
5559
  this.movement.goToAnchor();
5560
+ avatarLoadedSuccessfully = true;
5561
+ }
5562
+ if (avatarLoadedSuccessfully || this.renderer.getRenderState() === "ready") {
5563
+ this.setAvatarLifecycleState("ready");
5564
+ } else {
5565
+ this.setAvatarLifecycleState("error");
5566
+ }
5567
+ if (avatarLoadedSuccessfully || this.renderer.getRenderState() === "ready" || this.options.fallback?.mode) {
5568
+ this.setState("ready");
5569
+ } else {
5570
+ this.setState("error", { reason: "avatar_load_failed" });
4961
5571
  }
4962
5572
  try {
4963
5573
  await this.sendHeartbeat();
@@ -4977,7 +5587,13 @@ var AsiystRuntime = class {
4977
5587
  assetUrl: assetTarget
4978
5588
  });
4979
5589
  try {
4980
- const loaded = await this.renderer.loadAsset(cfg, this.metricsTracker);
5590
+ const loaded = await this.renderer.loadAsset(cfg, this.metricsTracker, {
5591
+ onProgress: (p) => {
5592
+ this.events.emit("progress", p);
5593
+ this.events.emit("asiyst:progress", p);
5594
+ },
5595
+ fallback: this.options.fallback
5596
+ });
4981
5597
  if (loaded) {
4982
5598
  this.movement.goToAnchor();
4983
5599
  const format = this.renderer.getLoadedFormat();
@@ -5000,6 +5616,10 @@ var AsiystRuntime = class {
5000
5616
  return true;
5001
5617
  } else {
5002
5618
  const err = this.renderer.getLastError() ?? "Avatar asset loading failed";
5619
+ this.recordError({
5620
+ code: "AVATAR_LOAD_FAILED",
5621
+ message: err
5622
+ });
5003
5623
  this.events.emit("asiyst:avatar:error", {
5004
5624
  avatarId: this.options.avatarId ?? cfg.avatarId,
5005
5625
  error: err,
@@ -5009,6 +5629,7 @@ var AsiystRuntime = class {
5009
5629
  }
5010
5630
  } catch (error) {
5011
5631
  const err = error instanceof Error ? error.message : "Avatar asset rendering failed";
5632
+ this.recordError(error instanceof Error ? error : new Error(err));
5012
5633
  this.events.emit("asiyst:avatar:error", {
5013
5634
  avatarId: this.options.avatarId ?? cfg.avatarId,
5014
5635
  error: err,
@@ -5108,6 +5729,104 @@ var AsiystRuntime = class {
5108
5729
  getAvatarPerformanceMetrics() {
5109
5730
  return this.metricsTracker.getMetrics();
5110
5731
  }
5732
+ async diagnose() {
5733
+ const startTime = typeof performance !== "undefined" && performance.now ? performance.now() : Date.now();
5734
+ const origin = typeof window !== "undefined" && window.location ? window.location.origin : "";
5735
+ let webglSupported = false;
5736
+ let rendererAvailable = false;
5737
+ try {
5738
+ if (typeof document !== "undefined") {
5739
+ const testCanvas = document.createElement("canvas");
5740
+ const gl = testCanvas.getContext("webgl2") || testCanvas.getContext("webgl");
5741
+ if (gl) {
5742
+ webglSupported = true;
5743
+ rendererAvailable = true;
5744
+ }
5745
+ }
5746
+ } catch {
5747
+ webglSupported = false;
5748
+ rendererAvailable = false;
5749
+ }
5750
+ const registration = {
5751
+ ok: this.registrationSucceeded,
5752
+ status: this.registrationSucceeded ? 200 : void 0,
5753
+ code: this.registrationSucceeded ? void 0 : "REGISTRATION_FAILED",
5754
+ message: this.registrationSucceeded ? "Installation registered successfully" : "Installation registration failed or incomplete"
5755
+ };
5756
+ let authorization;
5757
+ try {
5758
+ if (this.runtimeAuth) {
5759
+ const token = await this.runtimeAuth.getToken();
5760
+ authorization = {
5761
+ ok: Boolean(token),
5762
+ status: 200,
5763
+ message: "Runtime authorization token valid"
5764
+ };
5765
+ } else {
5766
+ authorization = {
5767
+ ok: false,
5768
+ code: "NO_AUTH_PROVIDER",
5769
+ message: "No runtime auth provider configured"
5770
+ };
5771
+ }
5772
+ } catch (authErr) {
5773
+ authorization = {
5774
+ ok: false,
5775
+ status: authErr?.status ?? 403,
5776
+ code: authErr?.code ?? "AUTHENTICATION_FAILED",
5777
+ message: authErr instanceof Error ? authErr.message : "Authorization failed"
5778
+ };
5779
+ }
5780
+ const cfg = this.config.get();
5781
+ const runtimeConfig = {
5782
+ ok: Boolean(cfg && cfg.version !== void 0),
5783
+ status: cfg ? 200 : void 0,
5784
+ message: cfg ? "Runtime configuration loaded" : "Runtime configuration unavailable"
5785
+ };
5786
+ const avatarId = this.options.avatarId ?? cfg.avatarId ?? "default";
5787
+ const assets = [];
5788
+ if (cfg.assetUrl) {
5789
+ assets.push({
5790
+ name: "mesh",
5791
+ format: cfg.modelFormat ?? "fbx",
5792
+ loaded: this.renderer.isAssetLoaded()
5793
+ });
5794
+ }
5795
+ if (cfg.animations && Array.isArray(cfg.animations)) {
5796
+ for (const anim of cfg.animations) {
5797
+ assets.push({
5798
+ name: anim.name || anim.assetUrl || "animation",
5799
+ format: "fbx",
5800
+ loaded: this.renderer.isAssetLoaded()
5801
+ });
5802
+ }
5803
+ }
5804
+ const endTime = typeof performance !== "undefined" && performance.now ? performance.now() : Date.now();
5805
+ const durationMs = Math.round(endTime - startTime);
5806
+ return {
5807
+ sdkVersion: SDK_VERSION,
5808
+ origin,
5809
+ state: this.state,
5810
+ registration,
5811
+ authorization,
5812
+ runtimeConfig,
5813
+ avatar: {
5814
+ avatarId,
5815
+ format: this.renderer.getLoadedFormat() ?? cfg.modelFormat,
5816
+ assets
5817
+ },
5818
+ webgl: {
5819
+ supported: webglSupported,
5820
+ rendererAvailable
5821
+ },
5822
+ errors: this.errorsObserved.map((e) => ({
5823
+ code: e.code,
5824
+ message: e.message,
5825
+ hint: e.hint
5826
+ })),
5827
+ durationMs
5828
+ };
5829
+ }
5111
5830
  avatarApi() {
5112
5831
  return this.avatar;
5113
5832
  }
@@ -5142,6 +5861,7 @@ var AsiystRuntime = class {
5142
5861
  return;
5143
5862
  }
5144
5863
  this.destroyed = true;
5864
+ this.setState("idle");
5145
5865
  if (this.heartbeatTimer) {
5146
5866
  clearInterval(this.heartbeatTimer);
5147
5867
  this.heartbeatTimer = void 0;
@@ -5404,6 +6124,18 @@ var Asiyst = {
5404
6124
  initPromise = void 0;
5405
6125
  await current.destroy(window);
5406
6126
  },
6127
+ getState() {
6128
+ return runtime ? runtime.getState() : "idle";
6129
+ },
6130
+ getAvatarState() {
6131
+ return runtime ? runtime.getAvatarState() : "initializing";
6132
+ },
6133
+ getChatState() {
6134
+ return runtime ? runtime.getChatState() : "initializing";
6135
+ },
6136
+ async diagnose() {
6137
+ return requireRuntime().diagnose();
6138
+ },
5407
6139
  open() {
5408
6140
  withIsolation(() => requireRuntime().open());
5409
6141
  },