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