@asiyst/sdk 0.1.30 → 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.29";
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,
@@ -914,7 +952,37 @@ var CloudClient = class {
914
952
  const errorBody = errorRecord && typeof errorRecord === "object" ? errorRecord : void 0;
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
- throw new AuthenticationError("Asiyst runtime authorization was rejected.");
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.",
970
+ INSTALLATION_NOT_FOUND: "Asiyst installation not found for this domain. Re-run `asiyst connect` and verify your project domain.",
971
+ INSTALLATION_INACTIVE: "Asiyst installation is inactive. Check your project status in the Asiyst dashboard.",
972
+ INSTALLATION_REVOKED: "Asiyst installation has been revoked. Re-run `asiyst connect` to register a new installation.",
973
+ INSTALLATION_PROJECT_MISMATCH: "Asiyst installation does not match the configured project.",
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.",
976
+ RUNTIME_TOKEN_INVALID: "Asiyst runtime authorization token is invalid. The SDK will attempt to re-authorize.",
977
+ RUNTIME_TOKEN_EXPIRED: "Asiyst runtime authorization token has expired. The SDK will re-authorize."
978
+ };
979
+ const knownMessage = typeof code === "string" ? installationErrorCodes[code] : void 0;
980
+ if (knownMessage) {
981
+ throw new AuthenticationError(knownMessage);
982
+ }
983
+ throw new AuthenticationError(
984
+ typeof errorBody?.message === "string" ? `Asiyst runtime authorization rejected: ${errorBody.message}` : "Asiyst runtime authorization was rejected."
985
+ );
918
986
  }
919
987
  if (response.status === 429) {
920
988
  throw new NetworkError("The assistant is rate limited. Wait before sending another message.");
@@ -1872,10 +1940,14 @@ var AssetLoader = class {
1872
1940
  const controller = new AbortController();
1873
1941
  this.inFlightControllers.add(controller);
1874
1942
  const abortSignal = options?.signal ? anySignal([controller.signal, options.signal]) : controller.signal;
1875
- const timeoutMs = options?.timeoutMs ?? 6e4;
1876
- 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";
1877
1949
  controller.abort();
1878
- }, timeoutMs);
1950
+ }, totalTimeoutMs);
1879
1951
  try {
1880
1952
  const cleanPath = (sanitizedUrl.split("?")[0] ?? "").toLowerCase();
1881
1953
  const isImageExtension = /\.(png|jpe?g|webp|svg|gif|avif)$/i.test(cleanPath);
@@ -1893,27 +1965,100 @@ var AssetLoader = class {
1893
1965
  durationMs: Date.now() - startTime
1894
1966
  };
1895
1967
  }
1968
+ const maxRetries = options?.maxRetries ?? 2;
1969
+ let attempt = 0;
1896
1970
  let response;
1897
- try {
1898
- response = await fetch(sanitizedUrl, {
1899
- method: "GET",
1900
- headers: {
1901
- Accept: "model/fbx, application/octet-stream, model/gltf-binary, image/*, application/json, */*"
1902
- },
1903
- signal: abortSignal
1904
- });
1905
- } catch (err) {
1906
- if (err instanceof Error && err.name === "AbortError") {
1907
- 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;
1908
2029
  }
1909
- throw new Error(`CORS or network policy blocked avatar asset retrieval from ${sanitizedUrl}`);
2030
+ break;
1910
2031
  }
1911
2032
  if (!response.ok) {
1912
- 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
+ });
1913
2054
  }
1914
2055
  const contentType = (response.headers.get("content-type") || "").toLowerCase();
1915
2056
  if (contentType.includes("text/html")) {
1916
- 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
+ });
1917
2062
  }
1918
2063
  if (isJsonExtension || contentType.includes("application/json")) {
1919
2064
  const text = await response.text();
@@ -1921,10 +2066,16 @@ var AssetLoader = class {
1921
2066
  try {
1922
2067
  manifest = JSON.parse(text);
1923
2068
  } catch {
1924
- 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
+ });
1925
2073
  }
1926
2074
  if (typeof manifest !== "object" || manifest === null || Array.isArray(manifest)) {
1927
- throw new Error("Invalid avatar manifest schema");
2075
+ throw new AsiystError({
2076
+ code: "ASSET_PARSE_FAILED",
2077
+ message: "Invalid avatar manifest schema"
2078
+ });
1928
2079
  }
1929
2080
  return {
1930
2081
  format: "manifest",
@@ -1944,9 +2095,104 @@ var AssetLoader = class {
1944
2095
  durationMs: Date.now() - startTime
1945
2096
  };
1946
2097
  }
1947
- 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
+ }
1948
2191
  if (arrayBuffer.byteLength < 12) {
1949
- 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
+ });
1950
2196
  }
1951
2197
  if (options?.integrity) {
1952
2198
  await verifyIntegrity(arrayBuffer, options.integrity);
@@ -1954,18 +2200,33 @@ var AssetLoader = class {
1954
2200
  const headerBytes = new Uint8Array(arrayBuffer, 0, Math.min(256, arrayBuffer.byteLength));
1955
2201
  const headerStr = new TextDecoder("utf-8", { fatal: false }).decode(headerBytes).trim();
1956
2202
  if (/^<!DOCTYPE\s+html/i.test(headerStr) || /^<html/i.test(headerStr)) {
1957
- 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
+ });
1958
2207
  }
1959
2208
  const hasFbxSignature = this.isFbxBuffer(arrayBuffer);
1960
2209
  const hasGlbSignature = this.isGlbBuffer(arrayBuffer);
1961
2210
  const isFbx = hasFbxSignature || !hasGlbSignature && isFbxExtension;
1962
2211
  const isGlb = hasGlbSignature || !hasFbxSignature && isGlbExtension;
1963
2212
  if (isFbx && isGlb) {
1964
- 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
+ });
1965
2217
  }
1966
2218
  if (isFbx) {
1967
2219
  if (options?.expectedFormat && options.expectedFormat !== "fbx") {
1968
- 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
+ }
1969
2230
  }
1970
2231
  const fbxHeader = this.parseFbxHeader(arrayBuffer);
1971
2232
  const resourcePath = sanitizedUrl.includes("/") ? sanitizedUrl.substring(0, sanitizedUrl.lastIndexOf("/") + 1) : "";
@@ -1980,15 +2241,22 @@ var AssetLoader = class {
1980
2241
  };
1981
2242
  }
1982
2243
  if (!isGlb) {
1983
- 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
+ });
1984
2248
  }
1985
2249
  if (options?.expectedFormat && options.expectedFormat !== "glb") {
1986
- 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
+ });
1987
2254
  }
1988
2255
  const parsedGlb = this.parseGlb(arrayBuffer);
1989
2256
  return {
1990
2257
  format: "glb",
1991
2258
  url: sanitizedUrl,
2259
+ buffer: arrayBuffer,
1992
2260
  json: parsedGlb.json,
1993
2261
  bin: parsedGlb.bin,
1994
2262
  meshes: parsedGlb.meshes,
@@ -1996,7 +2264,7 @@ var AssetLoader = class {
1996
2264
  durationMs: Date.now() - startTime
1997
2265
  };
1998
2266
  } finally {
1999
- clearTimeout(timeoutId);
2267
+ clearTimeout(totalTimeoutId);
2000
2268
  this.inFlightControllers.delete(controller);
2001
2269
  }
2002
2270
  }
@@ -2264,6 +2532,7 @@ var FbxRenderer = class {
2264
2532
  this.mixer = null;
2265
2533
  this.allAnimations = [];
2266
2534
  this.animationMetadataList = [];
2535
+ this.failedAnimations = /* @__PURE__ */ new Map();
2267
2536
  this.assetLoader = new AssetLoader();
2268
2537
  this.currentAction = null;
2269
2538
  this.animFrameId = null;
@@ -2378,7 +2647,7 @@ var FbxRenderer = class {
2378
2647
  const loader = new GLTFLoader_js.GLTFLoader();
2379
2648
  try {
2380
2649
  const gltf = await new Promise((resolve, reject) => {
2381
- const glbBuffer = asset.bin.buffer.slice(asset.bin.byteOffset, asset.bin.byteOffset + asset.bin.byteLength);
2650
+ const glbBuffer = asset.buffer ? asset.buffer : asset.bin.buffer.slice(asset.bin.byteOffset, asset.bin.byteOffset + asset.bin.byteLength);
2382
2651
  loader.parse(glbBuffer, asset.url, resolve, reject);
2383
2652
  });
2384
2653
  rawObject = gltf.scene;
@@ -2572,7 +2841,7 @@ var FbxRenderer = class {
2572
2841
  } else if (loaded.format === "glb") {
2573
2842
  const loader = new GLTFLoader_js.GLTFLoader();
2574
2843
  const gltf = await new Promise((resolve, reject) => {
2575
- const glbBuffer = loaded.bin.buffer.slice(
2844
+ const glbBuffer = loaded.buffer ? loaded.buffer : loaded.bin.buffer.slice(
2576
2845
  loaded.bin.byteOffset,
2577
2846
  loaded.bin.byteOffset + loaded.bin.byteLength
2578
2847
  );
@@ -2580,9 +2849,11 @@ var FbxRenderer = class {
2580
2849
  });
2581
2850
  extractedClips = gltf.animations || [];
2582
2851
  }
2852
+ let anyExtracted = false;
2583
2853
  for (const rawClip of extractedClips) {
2584
2854
  const retargeted = this.retargetClip(rawClip, this.rawObject);
2585
2855
  if (!retargeted) continue;
2856
+ anyExtracted = true;
2586
2857
  retargeted.name = anim.clipName || anim.name || rawClip.name;
2587
2858
  this.allAnimations.push(retargeted);
2588
2859
  this.animationMetadataList.push({
@@ -2594,9 +2865,21 @@ var FbxRenderer = class {
2594
2865
  clip: retargeted
2595
2866
  });
2596
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
+ }
2597
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
+ });
2598
2882
  if (typeof console !== "undefined" && typeof console.warn === "function") {
2599
- const msg = err instanceof Error ? err.message : String(err);
2600
2883
  console.warn(`[asiyst] Failed to load external animation "${anim.name}": ${msg}`);
2601
2884
  }
2602
2885
  }
@@ -2610,6 +2893,13 @@ var FbxRenderer = class {
2610
2893
  }
2611
2894
  }
2612
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
+ }
2613
2903
  retargetClip(clip, targetObject) {
2614
2904
  const targetNodeNames = /* @__PURE__ */ new Set();
2615
2905
  const boneLookup = /* @__PURE__ */ new Map();
@@ -3067,6 +3357,70 @@ var AVATAR_CSS = `
3067
3357
  .asiyst-open-chat-btn svg {
3068
3358
  stroke: #fbbf24;
3069
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
+ }
3070
3424
  @media (prefers-reduced-motion: reduce) {
3071
3425
  .asiyst-avatar.asiyst-animate { transition: none; }
3072
3426
  .asiyst-avatar-loader { animation: none; }
@@ -3090,6 +3444,9 @@ var CssAvatarRenderer = class {
3090
3444
  this.isAssetLoadedFlag = false;
3091
3445
  this.isFallbackFlag = false;
3092
3446
  }
3447
+ setFallbackOptions(opts) {
3448
+ this.fallbackOptions = opts;
3449
+ }
3093
3450
  setMetricsTracker(tracker) {
3094
3451
  this.metricsTracker = tracker;
3095
3452
  }
@@ -3200,6 +3557,8 @@ var CssAvatarRenderer = class {
3200
3557
  if (!this.isAssetLoadedFlag && this.viewport) {
3201
3558
  if (this.renderState === "error") {
3202
3559
  this.renderFallback(true);
3560
+ } else if (this.renderState === "loading") {
3561
+ this.renderLoadingPlaceholder();
3203
3562
  } else {
3204
3563
  this.viewport.replaceChildren();
3205
3564
  }
@@ -3229,10 +3588,13 @@ var CssAvatarRenderer = class {
3229
3588
  this.chatActionBtn.style.display = open ? "none" : "inline-flex";
3230
3589
  }
3231
3590
  }
3232
- async loadAsset(config, metricsTracker) {
3591
+ async loadAsset(config, metricsTracker, options) {
3233
3592
  if (metricsTracker) {
3234
3593
  this.metricsTracker = metricsTracker;
3235
3594
  }
3595
+ if (options?.fallback) {
3596
+ this.fallbackOptions = options.fallback;
3597
+ }
3236
3598
  const assetUrl = config.assetUrl ?? config.thumbnailUrl;
3237
3599
  if (!assetUrl) {
3238
3600
  this.renderState = "idle";
@@ -3268,7 +3630,12 @@ var CssAvatarRenderer = class {
3268
3630
  const asset = await this.assetLoader.load(assetUrl, {
3269
3631
  timeoutMs: 6e4,
3270
3632
  integrity: config.assetIntegrity,
3271
- 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
+ }
3272
3639
  });
3273
3640
  this.metricsTracker?.record("assetDownloadComplete");
3274
3641
  const byteSize = asset.buffer?.byteLength ?? asset.bin?.byteLength ?? asset.size;
@@ -3298,28 +3665,153 @@ var CssAvatarRenderer = class {
3298
3665
  }
3299
3666
  return true;
3300
3667
  } catch (err) {
3301
- const message = err instanceof Error ? err.message : "Failed to load avatar asset";
3302
- this.lastErrorMessage = message;
3668
+ const errorObj = err instanceof Error ? err : new Error(String(err));
3669
+ this.lastErrorMessage = errorObj.message;
3303
3670
  this.renderState = "error";
3304
3671
  this.isAssetLoadedFlag = false;
3305
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") {
3306
3737
  if (this.figure) {
3307
- this.figure.setAttribute("data-state", "error");
3738
+ this.figure.setAttribute("data-state", "ready");
3308
3739
  this.figure.classList.remove("asiyst-3d-active");
3309
3740
  this.figure.classList.add("asiyst-compact-launcher");
3310
3741
  this.figure.style.width = `${this.size}px`;
3311
3742
  this.figure.style.height = `${this.size}px`;
3312
3743
  this.figure.style.background = this.accentColor;
3313
3744
  }
3314
- if (this.nameTagEl) {
3315
- this.nameTagEl.style.display = "none";
3316
- }
3317
- if (this.chatActionBtn) {
3318
- 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;
3319
3756
  }
3320
3757
  this.renderFallback(true);
3321
- 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";
3322
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);
3323
3815
  }
3324
3816
  renderLoader() {
3325
3817
  if (!this.viewport) return;
@@ -3388,6 +3880,16 @@ var CssAvatarRenderer = class {
3388
3880
  }
3389
3881
  }
3390
3882
  }
3883
+ renderLoadingPlaceholder() {
3884
+ if (!this.viewport) return;
3885
+ this.viewport.replaceChildren();
3886
+ const doc = this.viewport.ownerDocument;
3887
+ const placeholder = doc.createElement("div");
3888
+ placeholder.className = "asiyst-avatar-loader";
3889
+ placeholder.setAttribute("aria-hidden", "true");
3890
+ placeholder.setAttribute("data-state", "loading");
3891
+ this.viewport.appendChild(placeholder);
3892
+ }
3391
3893
  renderFallback(isError = false) {
3392
3894
  if (!this.viewport) return;
3393
3895
  this.viewport.replaceChildren();
@@ -4590,8 +5092,28 @@ var RuntimeAuth = class {
4590
5092
  body = void 0;
4591
5093
  }
4592
5094
  if (!response.ok) {
4593
- if (response.status === 403) {
4594
- throw new AuthenticationError("ASIYST runtime authorization was rejected.");
5095
+ if (response.status === 401 || response.status === 403) {
5096
+ const errorRecord = body && typeof body === "object" ? body.error : void 0;
5097
+ const errorBody = errorRecord && typeof errorRecord === "object" ? errorRecord : void 0;
5098
+ const code = typeof errorBody?.code === "string" ? errorBody.code : void 0;
5099
+ const installationErrorCodes = {
5100
+ INSTALLATION_NOT_FOUND: "Asiyst installation not found for this domain. Re-run `asiyst connect` and verify your project domain.",
5101
+ INSTALLATION_INACTIVE: "Asiyst installation is inactive. Check your project status in the Asiyst dashboard.",
5102
+ INSTALLATION_REVOKED: "Asiyst installation has been revoked. Re-run `asiyst connect` to register a new installation.",
5103
+ INSTALLATION_PROJECT_MISMATCH: "Asiyst installation does not match the configured project.",
5104
+ INSTALLATION_DOMAIN_MISMATCH: "Asiyst installation domain does not match the current website domain.",
5105
+ ORIGIN_MISMATCH: "Asiyst installation origin does not match the current website origin.",
5106
+ INSTALLATION_ENVIRONMENT_MISMATCH: "Asiyst installation environment does not match the current website environment.",
5107
+ RUNTIME_TOKEN_INVALID: "Asiyst runtime authorization token is invalid.",
5108
+ RUNTIME_TOKEN_EXPIRED: "Asiyst runtime authorization token has expired."
5109
+ };
5110
+ const knownMessage = code ? installationErrorCodes[code] : void 0;
5111
+ if (knownMessage) {
5112
+ throw new AuthenticationError(knownMessage);
5113
+ }
5114
+ throw new AuthenticationError(
5115
+ typeof errorBody?.message === "string" ? `ASIYST runtime authorization rejected: ${errorBody.message}` : "ASIYST runtime authorization was rejected."
5116
+ );
4595
5117
  }
4596
5118
  if (response.status === 429) {
4597
5119
  throw new NetworkError("ASIYST runtime authentication is rate limited.");
@@ -4602,7 +5124,7 @@ var RuntimeAuth = class {
4602
5124
  throw new NetworkError("ASIYST runtime authentication is unavailable.");
4603
5125
  }
4604
5126
  const data = body?.data;
4605
- if (body?.success !== true || !data || typeof data.token !== "string" || data.token.length < 20 || data.tokenType !== "Bearer" || data.audience !== "asiyst-sdk-runtime" || typeof data.expiresAt !== "string" || data.expiresIn !== 300 || !Array.isArray(data.capabilities) || !data.capabilities.includes("assistant:config") || !data.capabilities.includes("assistant:conversation") || !data.capabilities.includes("assistant:heartbeat")) {
5127
+ if (body?.success !== true || !data || typeof data.token !== "string" || data.token.length < 20 || data.tokenType !== "Bearer" || data.audience !== "asiyst-sdk-runtime" || typeof data.expiresAt !== "string" || typeof data.expiresIn !== "number" || data.expiresIn <= 0 || !Array.isArray(data.capabilities) || !data.capabilities.includes("assistant:config") || !data.capabilities.includes("assistant:conversation") || !data.capabilities.includes("assistant:heartbeat")) {
4606
5128
  throw new AuthenticationError("ASIYST returned an invalid runtime authorization response.");
4607
5129
  }
4608
5130
  const expiresAt = Date.parse(data.expiresAt);
@@ -4776,6 +5298,11 @@ var AsiystRuntime = class {
4776
5298
  this.connectionStatus = "disconnected";
4777
5299
  this.verificationStatus = "not_detected";
4778
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 = [];
4779
5306
  this.isHeartbeatInFlight = false;
4780
5307
  this.lastHeartbeatTime = 0;
4781
5308
  this.nextHeartbeatAfterMs = HEARTBEAT_INTERVAL_MS;
@@ -4816,6 +5343,8 @@ var AsiystRuntime = class {
4816
5343
  () => this.map.list()
4817
5344
  );
4818
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);
4819
5348
  this.renderer.onOpenChat = () => this.open();
4820
5349
  this.renderer.mount(this.host.chrome, this.config.get());
4821
5350
  this.metricsTracker.record("sdkInit");
@@ -4862,6 +5391,47 @@ var AsiystRuntime = class {
4862
5391
  figure.addEventListener("click", this.figureClickListener);
4863
5392
  }
4864
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
+ }
4865
5435
  async start() {
4866
5436
  this.events.emit("asiyst:initialized", { projectId: this.options.projectId });
4867
5437
  this.avatar.show();
@@ -4873,36 +5443,113 @@ var AsiystRuntime = class {
4873
5443
  installationId: this.installationId,
4874
5444
  sdkVersion: SDK_VERSION
4875
5445
  });
5446
+ this.setState("registering");
4876
5447
  try {
4877
5448
  await this.registerInstallation();
4878
5449
  } catch (error) {
4879
5450
  this.connectionStatus = "offline";
4880
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);
4881
5480
  this.events.emit("asiyst:error", {
4882
- code: "runtime_connection_failed",
4883
- message: error instanceof Error ? error.message : "Asiyst runtime connection failed."
5481
+ code: "installation_registration_failed",
5482
+ message: asiystErr.message
4884
5483
  });
4885
- return;
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
5514
+ });
5515
+ this.recordError(asiystErr);
5516
+ this.events.emit("error", asiystErr);
5517
+ cfg = this.config.get();
4886
5518
  }
4887
- const cfg = await isolateAsync(() => this.config.refresh(), this.config.get());
4888
- this.metricsTracker.record("configRetrieved");
4889
5519
  const domainCheck = validateWebsiteDomain(cfg, window.location.href);
4890
5520
  if (!domainCheck.allowed) {
4891
5521
  this.connectionStatus = "disconnected";
4892
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 });
4893
5535
  this.events.emit("asiyst:error", {
4894
5536
  code: "domain_not_authorized",
4895
- message: "This website is not authorized for the current Asiyst project."
5537
+ message: domainErr.message
4896
5538
  });
5539
+ this.events.emit("error", domainErr);
4897
5540
  return;
4898
5541
  }
4899
5542
  this.avatar.applyConfig(cfg);
4900
5543
  this.movement.goToAnchor();
5544
+ this.setChatLifecycleState("ready");
5545
+ this.setState("loading-avatar");
5546
+ this.setAvatarLifecycleState("loading");
4901
5547
  this.events.emit("asiyst:ready", { projectId: this.options.projectId, configVersion: cfg.version });
4902
5548
  const assetTarget = cfg.assetUrl ?? cfg.thumbnailUrl;
5549
+ let avatarLoadedSuccessfully = false;
4903
5550
  if (assetTarget) {
4904
5551
  try {
4905
- await this.loadAvatarAsset(cfg, assetTarget);
5552
+ avatarLoadedSuccessfully = await this.loadAvatarAsset(cfg, assetTarget);
4906
5553
  } finally {
4907
5554
  this.avatar.show();
4908
5555
  this.movement.goToAnchor();
@@ -4910,6 +5557,17 @@ var AsiystRuntime = class {
4910
5557
  } else {
4911
5558
  this.avatar.show();
4912
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" });
4913
5571
  }
4914
5572
  try {
4915
5573
  await this.sendHeartbeat();
@@ -4929,7 +5587,13 @@ var AsiystRuntime = class {
4929
5587
  assetUrl: assetTarget
4930
5588
  });
4931
5589
  try {
4932
- 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
+ });
4933
5597
  if (loaded) {
4934
5598
  this.movement.goToAnchor();
4935
5599
  const format = this.renderer.getLoadedFormat();
@@ -4952,6 +5616,10 @@ var AsiystRuntime = class {
4952
5616
  return true;
4953
5617
  } else {
4954
5618
  const err = this.renderer.getLastError() ?? "Avatar asset loading failed";
5619
+ this.recordError({
5620
+ code: "AVATAR_LOAD_FAILED",
5621
+ message: err
5622
+ });
4955
5623
  this.events.emit("asiyst:avatar:error", {
4956
5624
  avatarId: this.options.avatarId ?? cfg.avatarId,
4957
5625
  error: err,
@@ -4961,6 +5629,7 @@ var AsiystRuntime = class {
4961
5629
  }
4962
5630
  } catch (error) {
4963
5631
  const err = error instanceof Error ? error.message : "Avatar asset rendering failed";
5632
+ this.recordError(error instanceof Error ? error : new Error(err));
4964
5633
  this.events.emit("asiyst:avatar:error", {
4965
5634
  avatarId: this.options.avatarId ?? cfg.avatarId,
4966
5635
  error: err,
@@ -5060,6 +5729,104 @@ var AsiystRuntime = class {
5060
5729
  getAvatarPerformanceMetrics() {
5061
5730
  return this.metricsTracker.getMetrics();
5062
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
+ }
5063
5830
  avatarApi() {
5064
5831
  return this.avatar;
5065
5832
  }
@@ -5094,6 +5861,7 @@ var AsiystRuntime = class {
5094
5861
  return;
5095
5862
  }
5096
5863
  this.destroyed = true;
5864
+ this.setState("idle");
5097
5865
  if (this.heartbeatTimer) {
5098
5866
  clearInterval(this.heartbeatTimer);
5099
5867
  this.heartbeatTimer = void 0;
@@ -5356,6 +6124,18 @@ var Asiyst = {
5356
6124
  initPromise = void 0;
5357
6125
  await current.destroy(window);
5358
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
+ },
5359
6139
  open() {
5360
6140
  withIsolation(() => requireRuntime().open());
5361
6141
  },