@asiyst/sdk 0.1.33 → 0.1.35

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
@@ -85,7 +85,7 @@ var ALL_ACTION_KINDS = [
85
85
  // src/core/constants.ts
86
86
  function resolveSdkVersion() {
87
87
  {
88
- return "0.1.33";
88
+ return "0.1.35";
89
89
  }
90
90
  }
91
91
  var SDK_VERSION = resolveSdkVersion();
@@ -355,23 +355,50 @@ function fallbackConfig() {
355
355
  };
356
356
  }
357
357
  function parseAnimations(value) {
358
- if (!Array.isArray(value)) return void 0;
358
+ if (!value) return void 0;
359
359
  const list = [];
360
- for (const item of value) {
361
- if (isRecord(item) && typeof item.name === "string") {
362
- list.push({
363
- id: typeof item.id === "string" ? sanitizeText(item.id, 64) : void 0,
364
- name: sanitizeText(item.name, 64),
365
- intent: typeof item.intent === "string" ? sanitizeText(item.intent, 64) : void 0,
366
- clipName: typeof item.clipName === "string" ? sanitizeText(item.clipName, 64) : void 0,
367
- loopMode: typeof item.loopMode === "string" ? sanitizeText(item.loopMode, 32) : void 0,
368
- durationMs: typeof item.durationMs === "number" ? item.durationMs : void 0,
369
- assetUrl: typeof item.assetUrl === "string" ? item.assetUrl : null,
370
- integrity: typeof item.integrity === "string" ? item.integrity : void 0
371
- });
360
+ if (Array.isArray(value)) {
361
+ for (const item of value) {
362
+ if (isRecord(item) && (typeof item.name === "string" || typeof item.id === "string" || typeof item.intent === "string")) {
363
+ const resolvedUrl = typeof item.assetUrl === "string" && item.assetUrl.trim() ? item.assetUrl.trim() : typeof item.downloadUrl === "string" && item.downloadUrl.trim() ? item.downloadUrl.trim() : typeof item.url === "string" && item.url.trim() ? item.url.trim() : null;
364
+ const name = typeof item.name === "string" && item.name.trim() ? sanitizeText(item.name, 64) : typeof item.intent === "string" && item.intent.trim() ? sanitizeText(item.intent, 64) : sanitizeText(String(item.id ?? "animation"), 64);
365
+ list.push({
366
+ id: typeof item.id === "string" ? sanitizeText(item.id, 64) : typeof item.animationId === "string" ? sanitizeText(item.animationId, 64) : void 0,
367
+ animationId: typeof item.animationId === "string" ? sanitizeText(item.animationId, 64) : void 0,
368
+ name,
369
+ normalizedName: typeof item.normalizedName === "string" ? sanitizeText(item.normalizedName, 64) : void 0,
370
+ category: typeof item.category === "string" ? sanitizeText(item.category, 64) : void 0,
371
+ intent: typeof item.intent === "string" ? sanitizeText(item.intent, 64) : void 0,
372
+ clipName: typeof item.clipName === "string" ? sanitizeText(item.clipName, 64) : void 0,
373
+ loopMode: typeof item.loopMode === "string" ? sanitizeText(item.loopMode, 32) : typeof item.loop === "boolean" ? item.loop ? "loop" : "once" : void 0,
374
+ loop: typeof item.loop === "boolean" ? item.loop : void 0,
375
+ durationMs: typeof item.durationMs === "number" ? item.durationMs : void 0,
376
+ duration: typeof item.duration === "number" ? item.duration : null,
377
+ status: typeof item.status === "string" ? sanitizeText(item.status, 32) : void 0,
378
+ format: typeof item.format === "string" ? sanitizeText(item.format, 16) : void 0,
379
+ assetUrl: resolvedUrl,
380
+ downloadUrl: typeof item.downloadUrl === "string" ? item.downloadUrl.trim() : resolvedUrl ?? void 0,
381
+ integrity: typeof item.integrity === "string" ? item.integrity : typeof item.sha256 === "string" ? `sha256-${item.sha256}` : void 0
382
+ });
383
+ }
384
+ }
385
+ return list;
386
+ }
387
+ if (isRecord(value)) {
388
+ for (const [key, urlVal] of Object.entries(value)) {
389
+ if (typeof urlVal === "string" && urlVal.trim()) {
390
+ list.push({
391
+ id: sanitizeText(key, 64),
392
+ name: sanitizeText(key, 64),
393
+ intent: sanitizeText(key, 64),
394
+ assetUrl: urlVal.trim(),
395
+ downloadUrl: urlVal.trim()
396
+ });
397
+ }
372
398
  }
399
+ return list.length > 0 ? list : void 0;
373
400
  }
374
- return list;
401
+ return void 0;
375
402
  }
376
403
  function parseBranding(value) {
377
404
  if (!isRecord(value)) return void 0;
@@ -392,13 +419,16 @@ function normalizeProjectConfig(raw) {
392
419
  "",
393
420
  128
394
421
  ) || void 0;
395
- const assetUrl = typeof raw.assetUrl === "string" && raw.assetUrl ? raw.assetUrl : typeof rawAvatarRecord?.assetUrl === "string" && rawAvatarRecord.assetUrl ? rawAvatarRecord.assetUrl : typeof rawAvatarRecord?.modelUrl === "string" && rawAvatarRecord.modelUrl ? rawAvatarRecord.modelUrl : typeof rawConfigRecord?.assetUrl === "string" && rawConfigRecord.assetUrl ? rawConfigRecord.assetUrl : typeof rawManifestRecord?.assetUrl === "string" && rawManifestRecord.assetUrl ? rawManifestRecord.assetUrl : typeof rawManifestRecord?.modelUrl === "string" && rawManifestRecord.modelUrl ? rawManifestRecord.modelUrl : void 0;
422
+ const rawAvatarCharacter = isRecord(rawAvatarRecord?.character) ? rawAvatarRecord.character : void 0;
423
+ const rawManifestCharacter = isRecord(rawManifestRecord?.character) ? rawManifestRecord.character : void 0;
424
+ const rawCharacter = isRecord(raw.character) ? raw.character : void 0;
425
+ const assetUrl = typeof raw.assetUrl === "string" && raw.assetUrl ? raw.assetUrl : typeof raw.modelUrl === "string" && raw.modelUrl ? raw.modelUrl : typeof rawCharacter?.downloadUrl === "string" && rawCharacter.downloadUrl ? rawCharacter.downloadUrl : typeof rawCharacter?.assetUrl === "string" && rawCharacter.assetUrl ? rawCharacter.assetUrl : typeof rawAvatarRecord?.assetUrl === "string" && rawAvatarRecord.assetUrl ? rawAvatarRecord.assetUrl : typeof rawAvatarRecord?.modelUrl === "string" && rawAvatarRecord.modelUrl ? rawAvatarRecord.modelUrl : typeof rawAvatarCharacter?.downloadUrl === "string" && rawAvatarCharacter.downloadUrl ? rawAvatarCharacter.downloadUrl : typeof rawAvatarCharacter?.assetUrl === "string" && rawAvatarCharacter.assetUrl ? rawAvatarCharacter.assetUrl : typeof rawConfigRecord?.assetUrl === "string" && rawConfigRecord.assetUrl ? rawConfigRecord.assetUrl : typeof rawManifestCharacter?.downloadUrl === "string" && rawManifestCharacter.downloadUrl ? rawManifestCharacter.downloadUrl : typeof rawManifestCharacter?.assetUrl === "string" && rawManifestCharacter.assetUrl ? rawManifestCharacter.assetUrl : typeof rawManifestRecord?.assetUrl === "string" && rawManifestRecord.assetUrl ? rawManifestRecord.assetUrl : typeof rawManifestRecord?.modelUrl === "string" && rawManifestRecord.modelUrl ? rawManifestRecord.modelUrl : void 0;
396
426
  const thumbnailUrl = typeof raw.thumbnailUrl === "string" ? raw.thumbnailUrl : typeof rawAvatarRecord?.thumbnailUrl === "string" ? rawAvatarRecord.thumbnailUrl : typeof rawConfigRecord?.thumbnailUrl === "string" ? rawConfigRecord.thumbnailUrl : typeof rawManifestRecord?.thumbnailUrl === "string" ? rawManifestRecord.thumbnailUrl : rawAvatarRecord?.thumbnailUrl === null ? null : void 0;
397
- const rawModelFormat = raw.modelFormat ?? rawAvatarRecord?.modelFormat ?? rawConfigRecord?.modelFormat ?? rawManifestRecord?.modelFormat;
427
+ const rawModelFormat = raw.modelFormat ?? raw.format ?? rawCharacter?.format ?? rawAvatarRecord?.modelFormat ?? rawAvatarRecord?.format ?? rawAvatarCharacter?.format ?? rawConfigRecord?.modelFormat ?? rawManifestCharacter?.format ?? rawManifestRecord?.modelFormat ?? rawManifestRecord?.characterFormat;
398
428
  const modelFormat = rawModelFormat === "fbx" || rawModelFormat === "glb" ? rawModelFormat : void 0;
399
429
  const publishedVersion = typeof raw.publishedVersion === "string" ? raw.publishedVersion : typeof rawAvatarRecord?.version === "string" ? rawAvatarRecord.version : typeof rawManifestRecord?.version === "string" ? rawManifestRecord.version : void 0;
400
430
  const animations = parseAnimations(
401
- raw.animations ?? rawAvatarRecord?.animations ?? rawConfigRecord?.animations
431
+ raw.animations ?? raw.separateAnimations ?? rawAvatarRecord?.separateAnimations ?? rawAvatarRecord?.animations ?? rawConfigRecord?.animations ?? rawManifestRecord?.separateAnimations ?? rawManifestRecord?.animations
402
432
  );
403
433
  const branding = parseBranding(raw.branding ?? rawAvatarRecord?.branding);
404
434
  const avatarName = asString(
@@ -408,9 +438,11 @@ function normalizeProjectConfig(raw) {
408
438
  );
409
439
  const avatar = typeof raw.avatar === "string" ? asString(raw.avatar, base.avatar, 64) : avatarId ?? base.avatar;
410
440
  const position = ANCHORS.includes(raw.position) ? raw.position : base.position;
441
+ const projectId = typeof raw.projectId === "string" && raw.projectId.trim() ? sanitizeText(raw.projectId, 128) : typeof rawConfigRecord?.projectId === "string" && rawConfigRecord.projectId.trim() ? sanitizeText(rawConfigRecord.projectId, 128) : typeof rawAvatarRecord?.projectId === "string" && rawAvatarRecord.projectId.trim() ? sanitizeText(rawAvatarRecord.projectId, 128) : base.projectId;
411
442
  return {
412
443
  schemaVersion: CONFIG_SCHEMA_VERSION,
413
444
  version: asNumber(raw.version, base.version, 0, Number.MAX_SAFE_INTEGER),
445
+ projectId,
414
446
  avatarName,
415
447
  avatar,
416
448
  avatarId,
@@ -519,8 +551,26 @@ var HttpTransport = class {
519
551
  getAvatarId() {
520
552
  return this.options.avatarId;
521
553
  }
554
+ buildRequestUrl(rawPath) {
555
+ const base = /^https?:\/\//i.test(rawPath) ? rawPath : `${this.options.apiBaseUrl.replace(/\/$/, "")}${rawPath.startsWith("/") ? rawPath : `/${rawPath}`}`;
556
+ try {
557
+ const parsed = new URL(base, typeof location !== "undefined" ? location.href : "https://asiyst.com");
558
+ if (parsed.pathname.startsWith("/api/v1/") && this.options.projectId && !parsed.searchParams.has("projectId")) {
559
+ parsed.searchParams.set("projectId", this.options.projectId);
560
+ }
561
+ if (parsed.pathname.startsWith("/api/v1/") && this.options.publicKey && !parsed.searchParams.has("publicKey") && (parsed.pathname.includes("/runtime/avatar") || parsed.pathname.includes("/runtime/register") || parsed.pathname.includes("/installations/register") || parsed.pathname.includes("/runtime/token") || parsed.pathname.includes("/manifest"))) {
562
+ parsed.searchParams.set("publicKey", this.options.publicKey);
563
+ }
564
+ if (parsed.pathname.includes("/runtime/avatar") && this.options.avatarId && !parsed.searchParams.has("avatarId")) {
565
+ parsed.searchParams.set("avatarId", this.options.avatarId);
566
+ }
567
+ return parsed.toString();
568
+ } catch {
569
+ return base;
570
+ }
571
+ }
522
572
  async request(req) {
523
- const url = /^https?:\/\//i.test(req.path) ? req.path : `${this.options.apiBaseUrl.replace(/\/$/, "")}${req.path}`;
573
+ const url = this.buildRequestUrl(req.path);
524
574
  const requestId = req.requestId || generateRequestId();
525
575
  const timeoutMs = req.timeoutMs ?? this.options.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS;
526
576
  const isSafeOrIdempotent = req.method === "GET" || Boolean(req.idempotent);
@@ -547,21 +597,45 @@ var HttpTransport = class {
547
597
  }
548
598
  }
549
599
  try {
550
- let response;
551
- response = await fetch(url, {
600
+ const defaultHeaders = {
601
+ Accept: "application/json",
602
+ "X-Asiyst-Project-Id": this.options.projectId,
603
+ "X-Asiyst-Public-Key": this.options.publicKey,
604
+ "X-Asiyst-Project-Key": this.options.publicKey,
605
+ ...this.options.avatarId ? { "X-Asiyst-Avatar-Id": this.options.avatarId } : {},
606
+ "X-Asiyst-SDK-Version": SDK_VERSION,
607
+ "X-Asiyst-Request-Id": requestId,
608
+ ...req.sessionId ? { "X-Asiyst-Session-Id": req.sessionId } : {},
609
+ ...req.conversationId ? { "X-Asiyst-Conversation-Id": req.conversationId } : {},
610
+ ...req.authorizationToken ? { Authorization: `Bearer ${req.authorizationToken}` } : {}
611
+ };
612
+ if (req.body !== void 0) {
613
+ defaultHeaders["Content-Type"] = "application/json";
614
+ }
615
+ const mergedHeaders = new Headers();
616
+ for (const [key, value] of Object.entries(defaultHeaders)) {
617
+ mergedHeaders.set(key, value);
618
+ }
619
+ if (req.headers) {
620
+ if (typeof req.headers.forEach === "function" && !Array.isArray(req.headers)) {
621
+ req.headers.forEach((value, key) => {
622
+ mergedHeaders.set(key, value);
623
+ });
624
+ } else if (Array.isArray(req.headers)) {
625
+ for (const [key, value] of req.headers) {
626
+ mergedHeaders.set(key, value);
627
+ }
628
+ } else if (typeof req.headers === "object") {
629
+ for (const [key, value] of Object.entries(req.headers)) {
630
+ if (value !== void 0 && value !== null) {
631
+ mergedHeaders.set(key, String(value));
632
+ }
633
+ }
634
+ }
635
+ }
636
+ const response = await fetch(url, {
552
637
  method: req.method,
553
- headers: req.headers ?? {
554
- Accept: "application/json",
555
- "Content-Type": "application/json",
556
- "X-Asiyst-Project-Id": this.options.projectId,
557
- "X-Asiyst-Public-Key": this.options.publicKey,
558
- ...this.options.avatarId ? { "X-Asiyst-Avatar-Id": this.options.avatarId } : {},
559
- "X-Asiyst-SDK-Version": SDK_VERSION,
560
- "X-Asiyst-Request-Id": requestId,
561
- ...req.sessionId ? { "X-Asiyst-Session-Id": req.sessionId } : {},
562
- ...req.conversationId ? { "X-Asiyst-Conversation-Id": req.conversationId } : {},
563
- ...req.authorizationToken ? { Authorization: `Bearer ${req.authorizationToken}` } : {}
564
- },
638
+ headers: mergedHeaders,
565
639
  body: req.body === void 0 ? void 0 : JSON.stringify(req.body),
566
640
  signal: controller.signal
567
641
  });
@@ -637,11 +711,21 @@ var API_ROUTES = {
637
711
  deviceVerify: "/cli/device/verify",
638
712
  deviceApprove: "/cli/device/approve",
639
713
  deviceDeny: "/cli/device/deny",
714
+ cliConnectStart: "/cli/connect/start",
715
+ cliConnectExchange: "/cli/connect/exchange",
716
+ cliWhoami: "/cli/whoami",
717
+ cliProject: (projectId) => `/cli/projects/${encodeURIComponent(projectId)}`,
718
+ cliProjectStatus: (projectId) => `/cli/projects/${encodeURIComponent(projectId)}/status`,
719
+ cliAvatarImport: (projectId) => `/cli/projects/${encodeURIComponent(projectId)}/avatars/import`,
720
+ cliAvatarVerify: (projectId, avatarId) => `/cli/projects/${encodeURIComponent(projectId)}/avatars/${encodeURIComponent(avatarId)}/verify`,
640
721
  authDeviceAuthorize: "/auth/device/authorize",
641
722
  authDeviceToken: "/auth/device/token",
642
723
  projectApiKeyVerify: (projectId) => `/projects/${encodeURIComponent(projectId)}/api-key/verify`,
643
724
  sdkInstallationVerify: "/sdk/installations/verify",
644
725
  avatarManifest: (projectId, avatarId) => `/projects/${encodeURIComponent(projectId)}/avatars/${encodeURIComponent(avatarId)}/manifest`,
726
+ projectAvatarManifest: (projectId, avatarId) => `/projects/${encodeURIComponent(projectId)}/avatars/${encodeURIComponent(avatarId)}/manifest`,
727
+ projectAvatarAsset: (projectId, avatarId) => `/projects/${encodeURIComponent(projectId)}/avatars/${encodeURIComponent(avatarId)}/asset`,
728
+ projectAvatarAnimationAsset: (projectId, avatarId, animationId) => `/projects/${encodeURIComponent(projectId)}/avatars/${encodeURIComponent(avatarId)}/animations/${encodeURIComponent(animationId)}/asset`,
645
729
  avatarRuntimeConfig: (projectId) => `/projects/${encodeURIComponent(projectId)}/avatar/runtime-config`
646
730
  };
647
731
  var API_LIMITS = {
@@ -730,63 +814,287 @@ var CloudClient = class {
730
814
  getConfigMetadata() {
731
815
  return this.configMetadata;
732
816
  }
817
+ withProjectQuery(rawUrl, extra) {
818
+ try {
819
+ const baseOrigin = contractApiBaseUrl(this.getApiBaseUrl());
820
+ const parsed = new URL(rawUrl, baseOrigin);
821
+ if (this.projectId && !parsed.searchParams.has("projectId")) {
822
+ parsed.searchParams.set("projectId", this.projectId);
823
+ }
824
+ if (extra) {
825
+ for (const [k, v] of Object.entries(extra)) {
826
+ if (v !== void 0 && v !== "" && !parsed.searchParams.has(k)) {
827
+ parsed.searchParams.set(k, v);
828
+ }
829
+ }
830
+ }
831
+ return parsed.toString();
832
+ } catch {
833
+ return rawUrl;
834
+ }
835
+ }
836
+ resolveAssetUrl(rawUrl) {
837
+ if (typeof rawUrl !== "string") return void 0;
838
+ const trimmed = rawUrl.trim();
839
+ if (!trimmed) return void 0;
840
+ if (/^https?:\/\//i.test(trimmed)) return trimmed;
841
+ try {
842
+ const baseOrigin = contractApiBaseUrl(this.getApiBaseUrl()).replace(/\/+$/, "");
843
+ return `${baseOrigin}${trimmed.startsWith("/") ? trimmed : `/${trimmed}`}`;
844
+ } catch {
845
+ return trimmed;
846
+ }
847
+ }
733
848
  async fetchConfig(etag, cachedConfig) {
734
- const response = await this.transport.request({
735
- path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.runtimeAvatar),
736
- method: "GET",
737
- idempotent: true,
738
- retries: 2,
739
- headers: {
740
- Accept: "application/json",
741
- "X-Asiyst-Public-Key": this.publicKey,
742
- "X-Asiyst-Project-Id": this.projectId,
743
- ...this.avatarId ? { "X-Asiyst-Avatar-Id": this.avatarId } : {},
744
- ...etag ? { "If-None-Match": etag } : {}
849
+ const runtimeAvatarUrl = this.withProjectQuery(
850
+ contractApiUrl(this.getApiBaseUrl(), API_ROUTES.runtimeAvatar),
851
+ {
852
+ publicKey: this.publicKey || void 0,
853
+ avatarId: this.avatarId || void 0
745
854
  }
746
- });
855
+ );
856
+ let response;
857
+ try {
858
+ response = await this.transport.request({
859
+ path: runtimeAvatarUrl,
860
+ method: "GET",
861
+ idempotent: true,
862
+ retries: 2,
863
+ headers: {
864
+ Accept: "application/json",
865
+ "X-Asiyst-Public-Key": this.publicKey,
866
+ "X-Asiyst-Project-Key": this.publicKey,
867
+ "X-Asiyst-Project-Id": this.projectId,
868
+ ...this.avatarId ? { "X-Asiyst-Avatar-Id": this.avatarId } : {},
869
+ ...etag ? { "If-None-Match": etag } : {}
870
+ }
871
+ });
872
+ } catch (err) {
873
+ throw new AsiystError({
874
+ code: "CORS_OR_NETWORK_FAILURE",
875
+ status: 0,
876
+ message: err instanceof Error ? `CORS or network failure while fetching avatar runtime configuration: ${err.message}` : "CORS or network failure while fetching avatar runtime configuration.",
877
+ hint: "Verify that your website origin is approved in the Asiyst project settings and that the API endpoint is reachable.",
878
+ cause: err
879
+ });
880
+ }
747
881
  if (response.status === 304 && cachedConfig) {
748
- this.configMetadata = {
749
- etag: response.headers?.get("etag") ?? etag,
750
- maxAgeMs: 0,
751
- staleIfErrorMs: 0
752
- };
753
- return cachedConfig;
882
+ if (!this.avatarId || cachedConfig.avatarId === this.avatarId) {
883
+ this.configMetadata = {
884
+ etag: response.headers?.get("etag") ?? etag,
885
+ maxAgeMs: 0,
886
+ staleIfErrorMs: 0
887
+ };
888
+ return cachedConfig;
889
+ }
754
890
  }
755
891
  if (!response.ok || !response.data) {
756
- const body = response.data;
757
- const code = body?.error?.code ?? `HTTP_${response.status}`;
892
+ const rawBody = response.data;
893
+ const errObj = rawBody?.error && typeof rawBody.error === "object" ? rawBody.error : void 0;
894
+ const code = (errObj?.code ?? (typeof rawBody?.code === "string" ? rawBody.code : void 0) ?? `HTTP_${response.status}`).toUpperCase();
895
+ const message = errObj?.message ?? (typeof rawBody?.message === "string" ? rawBody.message : void 0);
896
+ if (response.status === 0) {
897
+ throw new AsiystError({
898
+ code: "CORS_OR_NETWORK_FAILURE",
899
+ status: 0,
900
+ message: message ?? "Browser CORS or network failure blocked the runtime avatar configuration request.",
901
+ hint: "Ensure this website origin is approved in your Asiyst project domain settings."
902
+ });
903
+ }
904
+ if (code === "AVATAR_NOT_IMPORTED" || code === "AVATAR_UNPUBLISHED" || code === "UNPUBLISHED_AVATAR") {
905
+ throw new AsiystError({
906
+ code: "AVATAR_NOT_IMPORTED",
907
+ status: response.status,
908
+ message: message ?? `Avatar${this.avatarId ? ` "${this.avatarId}"` : ""} is not imported or published for project "${this.projectId}".`,
909
+ hint: "Run `npx asiyst avatar import <avatarId>` and confirm the backend completes the import."
910
+ });
911
+ }
912
+ if (response.status === 404 || code === "AVATAR_NOT_FOUND" || code === "NOT_FOUND") {
913
+ throw new AsiystError({
914
+ code: "AVATAR_NOT_FOUND",
915
+ status: 404,
916
+ message: message ?? `Avatar${this.avatarId ? ` "${this.avatarId}"` : ""} was not found for project "${this.projectId}".`,
917
+ hint: "Verify the avatarId in Asiyst.init() and in your Asiyst project."
918
+ });
919
+ }
920
+ if (code === "PROJECT_MISMATCH" || code === "API_KEY_PROJECT_MISMATCH" || code === "WRONG_PROJECT") {
921
+ throw new AsiystError({
922
+ code: "PROJECT_MISMATCH",
923
+ status: response.status || 403,
924
+ message: message ?? `Avatar or public key does not belong to project "${this.projectId}".`,
925
+ hint: "Verify that projectId, publicKey, and avatarId belong to the same Asiyst project."
926
+ });
927
+ }
928
+ if (code === "ORIGIN_NOT_APPROVED" || code === "DOMAIN_NOT_APPROVED" || code === "DOMAIN_MISMATCH") {
929
+ throw new AsiystError({
930
+ code: "DOMAIN_NOT_APPROVED",
931
+ status: response.status || 403,
932
+ message: message ?? `Origin is not approved for project "${this.projectId}" (${code}).`,
933
+ hint: "Add your website domain/origin to the approved domains in Asiyst Dashboard."
934
+ });
935
+ }
936
+ if (code === "MISSING_CHARACTER_FILE" || code === "ASSET_UNAVAILABLE") {
937
+ throw new AsiystError({
938
+ code: "MISSING_CHARACTER_FILE",
939
+ status: response.status,
940
+ message: message ?? "Avatar character FBX/GLB file is missing or unavailable."
941
+ });
942
+ }
758
943
  if (response.status === 401 || response.status === 403) {
759
- throw new AuthenticationError(body?.error?.message ?? `Asiyst runtime avatar configuration was rejected (${code}).`);
944
+ const authErr = new AuthenticationError(
945
+ message ?? `Asiyst runtime avatar configuration was rejected (${code}).`
946
+ );
947
+ throw authErr;
760
948
  }
761
- throw new NetworkError(body?.error?.message ?? `Asiyst runtime avatar configuration is unavailable (${code}).`);
949
+ throw new NetworkError(message ?? `Asiyst runtime avatar configuration is unavailable (${code}).`);
762
950
  }
763
- const data = response.data;
764
- if (data.success !== true || data.projectId !== this.projectId || typeof data.avatarId !== "string" || !data.config || typeof data.config !== "object" || Array.isArray(data.config)) {
951
+ const rawRoot = response.data;
952
+ const data = rawRoot.data && typeof rawRoot.data === "object" && !Array.isArray(rawRoot.data) ? rawRoot.data : rawRoot;
953
+ const rawConfig = data.config && typeof data.config === "object" && !Array.isArray(data.config) ? data.config : void 0;
954
+ const rawAvatar = data.avatar && typeof data.avatar === "object" && !Array.isArray(data.avatar) ? data.avatar : {};
955
+ let manifest = data.manifest && typeof data.manifest === "object" && !Array.isArray(data.manifest) ? data.manifest : {};
956
+ const returnedProjectId = typeof data.projectId === "string" ? data.projectId : typeof rawConfig?.projectId === "string" ? rawConfig.projectId : typeof rawAvatar.projectId === "string" ? rawAvatar.projectId : void 0;
957
+ if (rawRoot.success === false || data.success === false) {
765
958
  throw new ConfigurationError("Asiyst returned an invalid runtime configuration response.");
766
959
  }
767
- const rawConfig = data.config;
768
- const rawAvatar = data.avatar && typeof data.avatar === "object" ? data.avatar : {};
769
- const manifest = data.manifest && typeof data.manifest === "object" ? data.manifest : {};
770
- const modelFormat = [data.format, data.modelFormat, rawConfig.modelFormat, rawAvatar.modelFormat].find((format) => typeof format === "string");
960
+ if (!returnedProjectId || returnedProjectId !== this.projectId) {
961
+ if (!returnedProjectId) {
962
+ throw new ConfigurationError("Asiyst returned an invalid runtime configuration response.");
963
+ }
964
+ throw new AsiystError({
965
+ code: "PROJECT_MISMATCH",
966
+ status: 403,
967
+ message: `Project mismatch: expected "${this.projectId}", received "${returnedProjectId}".`,
968
+ hint: "Verify that the avatar and publicKey belong to the configured projectId."
969
+ });
970
+ }
971
+ if (data.imported === false || rawAvatar.imported === false || rawAvatar.isPublished === false || rawAvatar.status === "unpublished") {
972
+ throw new AsiystError({
973
+ code: "AVATAR_NOT_IMPORTED",
974
+ status: 404,
975
+ message: `Avatar "${this.avatarId ?? String(data.avatarId ?? "unknown")}" is not imported or published for project "${this.projectId}".`,
976
+ hint: "Publish the avatar in Avatar Studio and import it with `npx asiyst avatar import <avatarId>`."
977
+ });
978
+ }
979
+ const returnedAvatarId = typeof data.avatarId === "string" && data.avatarId.trim() ? data.avatarId.trim() : typeof rawAvatar.avatarId === "string" && rawAvatar.avatarId.trim() ? rawAvatar.avatarId.trim() : typeof rawAvatar.id === "string" && rawAvatar.id.trim() ? rawAvatar.id.trim() : typeof rawConfig?.avatarId === "string" && rawConfig.avatarId.trim() ? rawConfig.avatarId.trim() : void 0;
980
+ if (!returnedAvatarId) {
981
+ throw new ConfigurationError("Asiyst returned an invalid runtime configuration response.");
982
+ }
983
+ if (this.avatarId && returnedAvatarId !== this.avatarId && rawAvatar.id !== this.avatarId) {
984
+ throw new AsiystError({
985
+ code: "AVATAR_NOT_IMPORTED",
986
+ status: 409,
987
+ message: `Requested avatar "${this.avatarId}" does not match the project's imported avatar ("${returnedAvatarId}").`,
988
+ hint: `Run \`npx asiyst avatar import ${this.avatarId}\` to import this avatar into project "${this.projectId}".`
989
+ });
990
+ }
991
+ const cfgObj = rawConfig ?? {};
992
+ const extractCharacterUrl = (m) => {
993
+ const dChar = data.character && typeof data.character === "object" && !Array.isArray(data.character) ? data.character : void 0;
994
+ const mChar2 = m.character && typeof m.character === "object" && !Array.isArray(m.character) ? m.character : void 0;
995
+ const aChar = rawAvatar.character && typeof rawAvatar.character === "object" && !Array.isArray(rawAvatar.character) ? rawAvatar.character : void 0;
996
+ const candidate = [
997
+ cfgObj.assetUrl,
998
+ cfgObj.modelUrl,
999
+ rawAvatar.assetUrl,
1000
+ rawAvatar.modelUrl,
1001
+ dChar?.downloadUrl,
1002
+ dChar?.assetUrl,
1003
+ aChar?.downloadUrl,
1004
+ aChar?.assetUrl,
1005
+ mChar2?.downloadUrl,
1006
+ mChar2?.assetUrl,
1007
+ m.assetUrl,
1008
+ m.modelUrl,
1009
+ data.assetUrl,
1010
+ data.modelUrl
1011
+ ].find((val) => typeof val === "string" && val.trim().length > 0);
1012
+ return this.resolveAssetUrl(candidate);
1013
+ };
1014
+ let assetUrl = extractCharacterUrl(manifest);
1015
+ if (!assetUrl && typeof data.manifestUrl === "string" && data.manifestUrl.trim()) {
1016
+ try {
1017
+ const fetchedManifest = await this.fetchManifest(this.resolveAssetUrl(data.manifestUrl));
1018
+ if (fetchedManifest && typeof fetchedManifest === "object") {
1019
+ manifest = { ...manifest, ...fetchedManifest };
1020
+ assetUrl = extractCharacterUrl(manifest);
1021
+ }
1022
+ } catch {
1023
+ }
1024
+ }
1025
+ const mChar = manifest.character && typeof manifest.character === "object" && !Array.isArray(manifest.character) ? manifest.character : void 0;
1026
+ const modelFormat = [
1027
+ data.format,
1028
+ data.modelFormat,
1029
+ cfgObj.modelFormat,
1030
+ rawAvatar.modelFormat,
1031
+ rawAvatar.format,
1032
+ mChar?.format,
1033
+ manifest.modelFormat,
1034
+ manifest.characterFormat
1035
+ ].find((format) => typeof format === "string" && format.trim().length > 0);
771
1036
  if (modelFormat && modelFormat !== "fbx" && modelFormat !== "glb") {
772
1037
  throw new ConfigurationError(`Asiyst returned an unsupported avatar format: ${modelFormat}.`);
773
1038
  }
774
- const assetUrl = typeof rawConfig.assetUrl === "string" ? rawConfig.assetUrl : typeof rawAvatar.assetUrl === "string" ? rawAvatar.assetUrl : typeof rawAvatar.modelUrl === "string" ? rawAvatar.modelUrl : typeof manifest.assetUrl === "string" ? manifest.assetUrl : void 0;
775
- const animations = Array.isArray(rawConfig.animations) ? rawConfig.animations : Array.isArray(data.animations) ? data.animations : Array.isArray(rawAvatar.animations) ? rawAvatar.animations : [];
1039
+ const rawAnimsSource = Array.isArray(cfgObj.animations) && cfgObj.animations.length > 0 ? cfgObj.animations : Array.isArray(data.separateAnimations) && data.separateAnimations.length > 0 ? data.separateAnimations : Array.isArray(data.animations) && data.animations.length > 0 ? data.animations : Array.isArray(rawAvatar.separateAnimations) && rawAvatar.separateAnimations.length > 0 ? rawAvatar.separateAnimations : Array.isArray(rawAvatar.animations) && rawAvatar.animations.length > 0 ? rawAvatar.animations : Array.isArray(manifest.separateAnimations) && manifest.separateAnimations.length > 0 ? manifest.separateAnimations : manifest.animations;
1040
+ const normalizeAnimationEntries = (source) => {
1041
+ if (Array.isArray(source)) {
1042
+ return source.filter((item) => Boolean(item && typeof item === "object" && !Array.isArray(item))).map((item) => {
1043
+ const rawAnimUrl = typeof item.assetUrl === "string" && item.assetUrl.trim() ? item.assetUrl.trim() : typeof item.downloadUrl === "string" && item.downloadUrl.trim() ? item.downloadUrl.trim() : typeof item.url === "string" && item.url.trim() ? item.url.trim() : void 0;
1044
+ const resolvedAnimUrl = this.resolveAssetUrl(rawAnimUrl);
1045
+ return {
1046
+ ...item,
1047
+ assetUrl: resolvedAnimUrl ?? (item.assetUrl === null ? null : void 0),
1048
+ downloadUrl: resolvedAnimUrl ?? (typeof item.downloadUrl === "string" ? item.downloadUrl : void 0)
1049
+ };
1050
+ });
1051
+ }
1052
+ if (source && typeof source === "object" && !Array.isArray(source)) {
1053
+ const entries = [];
1054
+ for (const [intentOrName, urlVal] of Object.entries(source)) {
1055
+ if (typeof urlVal === "string" && urlVal.trim()) {
1056
+ const resolved = this.resolveAssetUrl(urlVal);
1057
+ entries.push({
1058
+ id: intentOrName,
1059
+ name: intentOrName,
1060
+ intent: intentOrName,
1061
+ assetUrl: resolved,
1062
+ downloadUrl: resolved
1063
+ });
1064
+ }
1065
+ }
1066
+ return entries;
1067
+ }
1068
+ return [];
1069
+ };
1070
+ const animations = normalizeAnimationEntries(rawAnimsSource);
776
1071
  const revision = typeof data.configRevision === "string" ? data.configRevision : typeof data.publishedVersionId === "string" ? data.publishedVersionId : "0";
777
1072
  const version = Number.parseInt(revision, 10);
1073
+ const thumbnailUrl = this.resolveAssetUrl(
1074
+ typeof cfgObj.thumbnailUrl === "string" ? cfgObj.thumbnailUrl : typeof rawAvatar.thumbnailUrl === "string" ? rawAvatar.thumbnailUrl : typeof manifest.thumbnailUrl === "string" ? manifest.thumbnailUrl : void 0
1075
+ );
1076
+ if ((cfgObj.assetUrl === null || rawAvatar.assetUrl === null || mChar?.downloadUrl === null || data.missingCharacterFile === true) && !assetUrl && !thumbnailUrl) {
1077
+ throw new AsiystError({
1078
+ code: "MISSING_CHARACTER_FILE",
1079
+ status: 404,
1080
+ message: `Avatar "${returnedAvatarId}" is missing its character FBX/GLB file.`,
1081
+ hint: "Upload a valid character FBX or GLB file in Avatar Studio and republish the avatar."
1082
+ });
1083
+ }
778
1084
  const config = normalizeProjectConfig({
779
- ...rawConfig,
780
- avatarId: data.avatarId,
781
- avatarName: typeof rawAvatar.name === "string" ? rawAvatar.name : rawConfig.avatarName,
1085
+ ...cfgObj,
1086
+ projectId: returnedProjectId,
1087
+ avatarId: returnedAvatarId,
1088
+ avatarName: typeof rawAvatar.name === "string" ? rawAvatar.name : typeof data.name === "string" ? data.name : cfgObj.avatarName,
782
1089
  assetUrl,
1090
+ thumbnailUrl: thumbnailUrl ?? (rawAvatar.thumbnailUrl === null ? null : void 0),
783
1091
  modelFormat,
784
1092
  publishedVersion: typeof data.publishedVersionId === "string" ? data.publishedVersionId : revision,
785
1093
  version: Number.isFinite(version) ? version : 0,
786
1094
  animations,
787
- theme: rawConfig.theme ?? rawAvatar.theme,
788
- personality: rawConfig.personality,
789
- behavior: rawConfig.behavior ?? rawAvatar.behavior,
1095
+ theme: cfgObj.theme ?? rawAvatar.theme,
1096
+ personality: cfgObj.personality,
1097
+ behavior: cfgObj.behavior ?? rawAvatar.behavior,
790
1098
  maxMessageChars: API_LIMITS.maxMessageChars
791
1099
  });
792
1100
  this.configMetadata = {
@@ -817,12 +1125,18 @@ var CloudClient = class {
817
1125
  }
818
1126
  async registerInstallation(registration) {
819
1127
  const response = await this.transport.request({
820
- path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.installationRegister),
1128
+ path: this.withProjectQuery(
1129
+ contractApiUrl(this.getApiBaseUrl(), API_ROUTES.installationRegister),
1130
+ { publicKey: registration.publicKey }
1131
+ ),
821
1132
  method: "POST",
822
1133
  headers: {
823
1134
  Accept: "application/json",
824
1135
  "Content-Type": "application/json",
825
- "X-Asiyst-SDK-Version": registration.sdkVersion
1136
+ "X-Asiyst-SDK-Version": registration.sdkVersion,
1137
+ "X-Asiyst-Project-Id": registration.projectId,
1138
+ "X-Asiyst-Public-Key": registration.publicKey,
1139
+ "X-Asiyst-Project-Key": registration.publicKey
826
1140
  },
827
1141
  body: {
828
1142
  projectId: registration.projectId,
@@ -845,14 +1159,18 @@ var CloudClient = class {
845
1159
  }
846
1160
  async registerRuntime(registration) {
847
1161
  const response = await this.transport.request({
848
- path: contractApiUrl(this.getApiBaseUrl(), API_ROUTES.runtimeRegister),
1162
+ path: this.withProjectQuery(
1163
+ contractApiUrl(this.getApiBaseUrl(), API_ROUTES.runtimeRegister),
1164
+ { publicKey: registration.publicKey }
1165
+ ),
849
1166
  method: "POST",
850
1167
  headers: {
851
1168
  Accept: "application/json",
852
1169
  "Content-Type": "application/json",
853
1170
  "X-Asiyst-SDK-Version": registration.sdkVersion || "",
854
1171
  "X-Asiyst-Project-Id": registration.projectId,
855
- "X-Asiyst-Public-Key": registration.publicKey
1172
+ "X-Asiyst-Public-Key": registration.publicKey,
1173
+ "X-Asiyst-Project-Key": registration.publicKey
856
1174
  },
857
1175
  body: {
858
1176
  projectId: registration.projectId,
@@ -880,22 +1198,31 @@ var CloudClient = class {
880
1198
  return body;
881
1199
  }
882
1200
  async fetchManifest(manifestUrl) {
883
- const url = manifestUrl || (this.avatarId ? contractApiUrl(this.getApiBaseUrl(), API_ROUTES.avatarManifest(this.projectId, this.avatarId)) : void 0);
884
- if (!url) {
1201
+ const rawUrl = manifestUrl || (this.avatarId ? contractApiUrl(this.getApiBaseUrl(), API_ROUTES.avatarManifest(this.projectId, this.avatarId)) : void 0);
1202
+ if (!rawUrl) {
885
1203
  throw new ConfigurationError("Manifest URL is required to fetch avatar manifest.");
886
1204
  }
1205
+ const url = this.withProjectQuery(rawUrl, { publicKey: this.publicKey || void 0 });
887
1206
  const response = await this.runtimeRequest({
888
1207
  path: url,
889
1208
  method: "GET",
890
1209
  headers: {
891
1210
  Accept: "application/json",
892
1211
  "X-Asiyst-Public-Key": this.publicKey,
1212
+ "X-Asiyst-Project-Key": this.publicKey,
893
1213
  "X-Asiyst-Project-Id": this.projectId
894
1214
  }
895
1215
  }, "assistant:config");
896
1216
  if (!response.ok || !response.data) {
897
1217
  throw new NetworkError(`Failed to fetch avatar manifest: HTTP ${response.status}`);
898
1218
  }
1219
+ const rawData = response.data;
1220
+ if (rawData.data && typeof rawData.data === "object" && !Array.isArray(rawData.data)) {
1221
+ return rawData.data;
1222
+ }
1223
+ if (rawData.manifest && typeof rawData.manifest === "object" && !Array.isArray(rawData.manifest)) {
1224
+ return rawData.manifest;
1225
+ }
899
1226
  return response.data;
900
1227
  }
901
1228
  async submitContext(request) {
@@ -1113,6 +1440,7 @@ var CloudClient = class {
1113
1440
  async runtimeRequest(request, capability = "assistant:config") {
1114
1441
  const fullRequest = {
1115
1442
  ...request,
1443
+ path: this.withProjectQuery(request.path),
1116
1444
  sessionId: request.sessionId ?? this.sessionId,
1117
1445
  conversationId: request.conversationId ?? this.conversationId
1118
1446
  };
@@ -1278,7 +1606,8 @@ var ConfigManager = class {
1278
1606
  new NamespacedStorage(credentials.projectId, browserLocalStorage())
1279
1607
  );
1280
1608
  const cached = this.cache.read(credentials.projectId);
1281
- this.current = cached ?? this.localFallback();
1609
+ const canUseCached = cached && (!credentials.avatarId || cached.avatarId === credentials.avatarId);
1610
+ this.current = canUseCached ? cached : this.localFallback();
1282
1611
  }
1283
1612
  get() {
1284
1613
  return this.current;
@@ -1294,11 +1623,14 @@ var ConfigManager = class {
1294
1623
  this.inFlightRefresh = null;
1295
1624
  }
1296
1625
  }
1297
- async executeRefresh(_options) {
1626
+ async executeRefresh(options) {
1298
1627
  const prev = this.current;
1299
1628
  try {
1300
1629
  const cached = this.cache.getEnvelope(this.options.projectId);
1301
- const normalized = normalizeProjectConfig(await this.cloud.fetchConfig(cached?.etag, cached?.config));
1630
+ const validCachedConfig = cached?.config && (!this.options.avatarId || cached.config.avatarId === this.options.avatarId) ? cached.config : void 0;
1631
+ const normalized = normalizeProjectConfig(
1632
+ await this.cloud.fetchConfig(validCachedConfig ? cached?.etag : void 0, validCachedConfig)
1633
+ );
1302
1634
  const receivedMetadata = this.cloud.getConfigMetadata?.() ?? {};
1303
1635
  const metadata = {
1304
1636
  ...receivedMetadata,
@@ -1313,16 +1645,20 @@ var ConfigManager = class {
1313
1645
  }
1314
1646
  return this.current;
1315
1647
  } catch (error) {
1316
- const cached = this.cache.getEnvelope(this.options.projectId);
1317
- const staleIfErrorMs = cached?.staleIfErrorMs ?? API_LIMITS.configStaleIfErrorMs;
1318
- if (cached && staleIfErrorMs > 0 && Date.now() - cached.fetchedAt <= staleIfErrorMs) {
1319
- this.current = normalizeProjectConfig(cached.config);
1320
- }
1648
+ const errCode = error && typeof error === "object" && "code" in error ? String(error.code) : "config_refresh_failed";
1321
1649
  this.events.emit("asiyst:error", {
1322
- code: "config_refresh_failed",
1650
+ code: errCode,
1323
1651
  message: error instanceof Error ? error.message : "Failed to refresh configuration"
1324
1652
  });
1325
- return this.current;
1653
+ if (options?.silent) {
1654
+ const cached = this.cache.getEnvelope(this.options.projectId);
1655
+ const staleIfErrorMs = cached?.staleIfErrorMs ?? API_LIMITS.configStaleIfErrorMs;
1656
+ if (cached && staleIfErrorMs > 0 && Date.now() - cached.fetchedAt <= staleIfErrorMs && (!this.options.avatarId || cached.config.avatarId === this.options.avatarId)) {
1657
+ this.current = normalizeProjectConfig(cached.config);
1658
+ }
1659
+ return this.current;
1660
+ }
1661
+ throw error;
1326
1662
  }
1327
1663
  }
1328
1664
  applyLocalUpdate(partial) {
@@ -2371,8 +2707,9 @@ var AssetLoader = class {
2371
2707
  continue;
2372
2708
  }
2373
2709
  throw new AsiystError({
2374
- code: "NETWORK_ERROR",
2710
+ code: "CORS_OR_NETWORK_FAILURE",
2375
2711
  message: `CORS or network policy blocked avatar asset retrieval from ${sanitizedUrl}`,
2712
+ hint: "Check that the asset server allows cross-origin requests from your website origin and that the URL is reachable.",
2376
2713
  cause: err
2377
2714
  });
2378
2715
  } finally {
@@ -2387,24 +2724,32 @@ var AssetLoader = class {
2387
2724
  break;
2388
2725
  }
2389
2726
  if (!response.ok) {
2727
+ if (response.status === 401) {
2728
+ throw new AsiystError({
2729
+ code: "UNAUTHORIZED",
2730
+ status: 401,
2731
+ message: `Unauthorized access (HTTP 401) when retrieving avatar asset from ${sanitizedUrl}`,
2732
+ hint: "Verify your publicKey and project authentication settings."
2733
+ });
2734
+ }
2390
2735
  if (response.status === 403) {
2391
2736
  throw new AsiystError({
2392
2737
  code: "DOMAIN_NOT_APPROVED",
2393
2738
  status: 403,
2394
2739
  message: `Avatar asset request forbidden (HTTP 403) from ${sanitizedUrl}`,
2395
- hint: "Check that the current website domain or origin is approved in the project settings."
2740
+ hint: "Check that the current website domain or origin is approved in the project settings, or refresh an expired signed asset URL."
2396
2741
  });
2397
2742
  }
2398
2743
  if (response.status === 404) {
2399
2744
  throw new AsiystError({
2400
- code: "AVATAR_NOT_FOUND",
2745
+ code: options?.isAnimation ? "MISSING_ANIMATION_FILE" : "MISSING_CHARACTER_FILE",
2401
2746
  status: 404,
2402
- message: `Avatar asset not found (HTTP 404) at ${sanitizedUrl}`,
2403
- hint: "Verify the avatarId and ensure a 3D model asset is published for this avatar."
2747
+ message: options?.isAnimation ? `Animation FBX/GLB file not found (HTTP 404) at ${sanitizedUrl}` : `Character FBX/GLB file not found (HTTP 404) at ${sanitizedUrl}`,
2748
+ hint: options?.isAnimation ? "Verify that the separate animation FBX/GLB file is uploaded and published for this avatar." : "Verify the avatarId and ensure a character 3D model asset is uploaded and published for this avatar."
2404
2749
  });
2405
2750
  }
2406
2751
  throw new AsiystError({
2407
- code: "NETWORK_ERROR",
2752
+ code: "INVALID_ASSET_RESPONSE",
2408
2753
  status: response.status,
2409
2754
  message: `Avatar asset download failed: HTTP ${response.status} from ${sanitizedUrl}`
2410
2755
  });
@@ -2412,7 +2757,7 @@ var AssetLoader = class {
2412
2757
  const contentType = (response.headers.get("content-type") || "").toLowerCase();
2413
2758
  if (contentType.includes("text/html")) {
2414
2759
  throw new AsiystError({
2415
- code: "ASSET_PARSE_FAILED",
2760
+ code: "INVALID_ASSET_RESPONSE",
2416
2761
  message: `Avatar asset request returned HTML instead of 3D asset from ${sanitizedUrl}`,
2417
2762
  hint: "The server returned a web page instead of 3D asset bytes. Check authentication or routing."
2418
2763
  });
@@ -2424,16 +2769,22 @@ var AssetLoader = class {
2424
2769
  manifest = JSON.parse(text);
2425
2770
  } catch {
2426
2771
  throw new AsiystError({
2427
- code: "ASSET_PARSE_FAILED",
2772
+ code: "INVALID_ASSET_RESPONSE",
2428
2773
  message: "Invalid avatar manifest: JSON decoding failed"
2429
2774
  });
2430
2775
  }
2431
2776
  if (typeof manifest !== "object" || manifest === null || Array.isArray(manifest)) {
2432
2777
  throw new AsiystError({
2433
- code: "ASSET_PARSE_FAILED",
2778
+ code: "INVALID_ASSET_RESPONSE",
2434
2779
  message: "Invalid avatar manifest schema"
2435
2780
  });
2436
2781
  }
2782
+ if (options?.expectedFormat === "fbx" || options?.expectedFormat === "glb") {
2783
+ throw new AsiystError({
2784
+ code: "INVALID_ASSET_RESPONSE",
2785
+ message: `Avatar asset request returned JSON instead of ${options.expectedFormat.toUpperCase()} binary from ${sanitizedUrl}`
2786
+ });
2787
+ }
2437
2788
  return {
2438
2789
  format: "manifest",
2439
2790
  url: sanitizedUrl,
@@ -2547,7 +2898,7 @@ var AssetLoader = class {
2547
2898
  }
2548
2899
  if (arrayBuffer.byteLength < 12) {
2549
2900
  throw new AsiystError({
2550
- code: "ASSET_PARSE_FAILED",
2901
+ code: "INVALID_ASSET_RESPONSE",
2551
2902
  message: "Avatar asset payload is too small to be a valid 3D container"
2552
2903
  });
2553
2904
  }
@@ -2558,7 +2909,7 @@ var AssetLoader = class {
2558
2909
  const headerStr = new TextDecoder("utf-8", { fatal: false }).decode(headerBytes).trim();
2559
2910
  if (/^<!DOCTYPE\s+html/i.test(headerStr) || /^<html/i.test(headerStr)) {
2560
2911
  throw new AsiystError({
2561
- code: "ASSET_PARSE_FAILED",
2912
+ code: "INVALID_ASSET_RESPONSE",
2562
2913
  message: `Avatar asset payload contains HTML error page instead of binary 3D container from ${sanitizedUrl}`
2563
2914
  });
2564
2915
  }
@@ -2568,14 +2919,14 @@ var AssetLoader = class {
2568
2919
  const isGlb = hasGlbSignature || !hasFbxSignature && isGlbExtension;
2569
2920
  if (isFbx && isGlb) {
2570
2921
  throw new AsiystError({
2571
- code: "ASSET_PARSE_FAILED",
2922
+ code: "INVALID_ASSET_RESPONSE",
2572
2923
  message: "Avatar asset format is ambiguous"
2573
2924
  });
2574
2925
  }
2575
2926
  if (isFbx) {
2576
2927
  if (options?.expectedFormat && options.expectedFormat !== "fbx") {
2577
2928
  throw new AsiystError({
2578
- code: "ASSET_PARSE_FAILED",
2929
+ code: "INVALID_ASSET_RESPONSE",
2579
2930
  message: `Avatar asset format mismatch: expected ${options.expectedFormat}, received fbx`
2580
2931
  });
2581
2932
  }
@@ -2585,7 +2936,16 @@ var AssetLoader = class {
2585
2936
  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).`);
2586
2937
  }
2587
2938
  }
2588
- const fbxHeader = this.parseFbxHeader(arrayBuffer);
2939
+ let fbxHeader;
2940
+ try {
2941
+ fbxHeader = this.parseFbxHeader(arrayBuffer);
2942
+ } catch (fbxErr) {
2943
+ throw new AsiystError({
2944
+ code: "INCOMPATIBLE_FBX",
2945
+ message: fbxErr instanceof Error ? fbxErr.message : "Unsupported or incompatible FBX header",
2946
+ cause: fbxErr
2947
+ });
2948
+ }
2589
2949
  const resourcePath = sanitizedUrl.includes("/") ? sanitizedUrl.substring(0, sanitizedUrl.lastIndexOf("/") + 1) : "";
2590
2950
  return {
2591
2951
  format: "fbx",
@@ -2599,13 +2959,13 @@ var AssetLoader = class {
2599
2959
  }
2600
2960
  if (!isGlb) {
2601
2961
  throw new AsiystError({
2602
- code: "ASSET_PARSE_FAILED",
2603
- message: "Avatar asset format is unsupported; expected FBX or GLB"
2962
+ code: "INCOMPATIBLE_FBX",
2963
+ message: "Avatar asset format is unsupported or incompatible; expected valid FBX or GLB container"
2604
2964
  });
2605
2965
  }
2606
2966
  if (options?.expectedFormat && options.expectedFormat !== "glb") {
2607
2967
  throw new AsiystError({
2608
- code: "ASSET_PARSE_FAILED",
2968
+ code: "INVALID_ASSET_RESPONSE",
2609
2969
  message: `Avatar asset format mismatch: expected ${options.expectedFormat}, received glb`
2610
2970
  });
2611
2971
  }
@@ -2964,27 +3324,57 @@ var RigDetector = class {
2964
3324
  return rawName.trim().replace(/^.*[:|/]/, "").replace(/^(mixamorig\d*|bip01|armature|root)[:_ ]?/i, "").replace(/[^a-zA-Z0-9._-]/g, "").toLowerCase();
2965
3325
  }
2966
3326
  /**
2967
- * Analyzes an imported 3D model root, identifies all bones, maps them to canonical AUBR,
2968
- * validates hierarchy, and reports capability profile.
3327
+ * Analyzes an imported 3D model root, identifies all bones and skinned meshes,
3328
+ * maps them to canonical AUBR, validates hierarchy, and reports capability profile.
2969
3329
  */
2970
- static detect(modelRoot) {
3330
+ static detect(modelRoot, options) {
2971
3331
  const allBones = [];
3332
+ const seenBones = /* @__PURE__ */ new Set();
3333
+ const skinnedMeshes = [];
2972
3334
  modelRoot.traverse((node) => {
2973
- if (node.isBone) {
3335
+ if (node.isSkinnedMesh) {
3336
+ const sm = node;
3337
+ skinnedMeshes.push(sm);
3338
+ if (sm.skeleton?.bones) {
3339
+ for (const b of sm.skeleton.bones) {
3340
+ if (b && !seenBones.has(b)) {
3341
+ seenBones.add(b);
3342
+ allBones.push(b);
3343
+ }
3344
+ }
3345
+ }
3346
+ }
3347
+ if (node.isBone && !seenBones.has(node)) {
3348
+ seenBones.add(node);
2974
3349
  allBones.push(node);
2975
3350
  }
2976
3351
  });
2977
3352
  if (allBones.length === 0) {
2978
3353
  modelRoot.traverse((node) => {
3354
+ if (node.isMesh) return;
2979
3355
  if (node.name && (node.type === "Bone" || /bone|joint|limb|hips|spine|arm|leg|head/i.test(node.name))) {
2980
- if (!allBones.includes(node)) {
3356
+ if (!seenBones.has(node)) {
3357
+ seenBones.add(node);
2981
3358
  allBones.push(node);
2982
3359
  }
2983
3360
  }
2984
3361
  });
2985
3362
  }
3363
+ const embeddedAnimationCount = typeof options?.embeddedAnimationCount === "number" && Number.isFinite(options.embeddedAnimationCount) ? Math.max(0, Math.floor(options.embeddedAnimationCount)) : Array.isArray(modelRoot.animations) ? modelRoot.animations.length : 0;
3364
+ const hasEmbeddedAnimations = embeddedAnimationCount > 0;
3365
+ const skinnedMeshCount = skinnedMeshes.length;
3366
+ const hasSkinnedMesh = skinnedMeshCount > 0;
3367
+ const boneCount = allBones.length;
3368
+ const hasSkeleton = boneCount > 0;
2986
3369
  if (allBones.length === 0) {
2987
- const caps = this.createUnsupportedCapabilities("unsupported", ["hips", "spine", "head"]);
3370
+ const caps = this.createUnsupportedCapabilities("unsupported", ["hips", "spine", "head"], {
3371
+ hasSkeleton,
3372
+ hasSkinnedMesh,
3373
+ boneCount,
3374
+ skinnedMeshCount,
3375
+ embeddedAnimationCount,
3376
+ hasEmbeddedAnimations
3377
+ });
2988
3378
  return {
2989
3379
  rigType: "unsupported",
2990
3380
  capabilities: caps,
@@ -3025,26 +3415,43 @@ var RigDetector = class {
3025
3415
  const hasArms = matchedBones.has("leftUpperArm") && matchedBones.has("leftLowerArm") && matchedBones.has("rightUpperArm") && matchedBones.has("rightLowerArm");
3026
3416
  const isHumanoid = hasHipsAndSpine && (hasLegs || hasArms);
3027
3417
  let finalRigType = rigFlavor;
3418
+ const detectedRigFlavor = isHumanoid ? rigFlavor : "unsupported";
3028
3419
  if (!isHumanoid) {
3029
3420
  finalRigType = "unsupported";
3030
3421
  } else if (missingRequired.length > 0) {
3031
3422
  finalRigType = "partial_humanoid";
3032
3423
  }
3424
+ const proceduralIdle = isHumanoid && hasHipsAndSpine && hasHead;
3425
+ const proceduralLocomotion = isHumanoid && hasLegs;
3426
+ const proceduralRunning = isHumanoid && hasLegs;
3427
+ const upperBodyGestures = isHumanoid && hasArms && hasHipsAndSpine;
3428
+ const proceduralAnimationAvailable = proceduralIdle || proceduralLocomotion || upperBodyGestures;
3429
+ const clipPlayback = hasSkeleton && allBones.length > 5 || hasEmbeddedAnimations;
3430
+ const animationSourceMode = proceduralAnimationAvailable && hasEmbeddedAnimations ? "embedded_and_procedural" : proceduralAnimationAvailable ? "procedural_only" : hasEmbeddedAnimations ? "embedded_only" : "static";
3033
3431
  const capabilities = {
3034
3432
  rigType: finalRigType,
3433
+ detectedRigFlavor,
3035
3434
  isHumanoid,
3435
+ hasSkeleton,
3436
+ hasSkinnedMesh,
3437
+ boneCount,
3438
+ skinnedMeshCount,
3036
3439
  confidence: Math.round(confidence * 100) / 100,
3037
- proceduralIdle: hasHipsAndSpine && hasHead,
3038
- proceduralLocomotion: isHumanoid && hasLegs,
3039
- proceduralRunning: isHumanoid && hasLegs,
3440
+ proceduralAnimationAvailable,
3441
+ proceduralIdle,
3442
+ proceduralLocomotion,
3443
+ proceduralRunning,
3040
3444
  turning: isHumanoid,
3041
- legIK: hasLegs,
3042
- armIK: hasArms,
3043
- footPlacement: hasLegs,
3044
- headLookAt: hasHead,
3045
- upperBodyGestures: hasArms && hasHipsAndSpine,
3445
+ legIK: isHumanoid && hasLegs,
3446
+ armIK: isHumanoid && hasArms,
3447
+ footPlacement: isHumanoid && hasLegs,
3448
+ headLookAt: isHumanoid && hasHead,
3449
+ upperBodyGestures,
3046
3450
  facialAnimation: this.detectFacialCapabilities(modelRoot),
3047
- clipPlayback: allBones.length > 5,
3451
+ hasEmbeddedAnimations,
3452
+ embeddedAnimationCount,
3453
+ clipPlayback,
3454
+ animationSourceMode,
3048
3455
  missingRequiredBones: missingRequired,
3049
3456
  missingOptionalBones: missingOptional
3050
3457
  };
@@ -3059,15 +3466,15 @@ var RigDetector = class {
3059
3466
  /**
3060
3467
  * Alias for detect()
3061
3468
  */
3062
- static detectRig(modelRoot) {
3063
- return this.detect(modelRoot);
3469
+ static detectRig(modelRoot, options) {
3470
+ return this.detect(modelRoot, options);
3064
3471
  }
3065
3472
  /**
3066
3473
  * Assesses avatar rig capabilities from detection result or model.
3067
3474
  */
3068
- static assessCapabilities(detection, modelRoot) {
3475
+ static assessCapabilities(detection, modelRoot, options) {
3069
3476
  if (modelRoot) {
3070
- return this.detect(modelRoot).capabilities;
3477
+ return this.detect(modelRoot, options).capabilities;
3071
3478
  }
3072
3479
  return detection.capabilities;
3073
3480
  }
@@ -3132,6 +3539,24 @@ var RigDetector = class {
3132
3539
  if (rightLow && rightFoot && !this.isDescendantOf(rightFoot, rightLow)) {
3133
3540
  matched.delete("rightFoot");
3134
3541
  }
3542
+ const leftUpArm = matched.get("leftUpperArm");
3543
+ const leftLowArm = matched.get("leftLowerArm");
3544
+ const leftHand = matched.get("leftHand");
3545
+ if (leftUpArm && leftLowArm && !this.isDescendantOf(leftLowArm, leftUpArm)) {
3546
+ matched.delete("leftLowerArm");
3547
+ }
3548
+ if (leftLowArm && leftHand && !this.isDescendantOf(leftHand, leftLowArm)) {
3549
+ matched.delete("leftHand");
3550
+ }
3551
+ const rightUpArm = matched.get("rightUpperArm");
3552
+ const rightLowArm = matched.get("rightLowerArm");
3553
+ const rightHand = matched.get("rightHand");
3554
+ if (rightUpArm && rightLowArm && !this.isDescendantOf(rightLowArm, rightUpArm)) {
3555
+ matched.delete("rightLowerArm");
3556
+ }
3557
+ if (rightLowArm && rightHand && !this.isDescendantOf(rightHand, rightLowArm)) {
3558
+ matched.delete("rightHand");
3559
+ }
3135
3560
  const hips = matched.get("hips");
3136
3561
  const spine = matched.get("spine");
3137
3562
  const head = matched.get("head");
@@ -3160,11 +3585,19 @@ var RigDetector = class {
3160
3585
  });
3161
3586
  return hasMorphTargets;
3162
3587
  }
3163
- static createUnsupportedCapabilities(rigType, missingReq) {
3588
+ static createUnsupportedCapabilities(rigType, missingReq, meta) {
3589
+ const hasEmbeddedAnimations = meta?.hasEmbeddedAnimations ?? false;
3590
+ const embeddedAnimationCount = meta?.embeddedAnimationCount ?? 0;
3164
3591
  return {
3165
3592
  rigType,
3593
+ detectedRigFlavor: rigType,
3166
3594
  isHumanoid: false,
3595
+ hasSkeleton: meta?.hasSkeleton ?? false,
3596
+ hasSkinnedMesh: meta?.hasSkinnedMesh ?? false,
3597
+ boneCount: meta?.boneCount ?? 0,
3598
+ skinnedMeshCount: meta?.skinnedMeshCount ?? 0,
3167
3599
  confidence: 0,
3600
+ proceduralAnimationAvailable: false,
3168
3601
  proceduralIdle: false,
3169
3602
  proceduralLocomotion: false,
3170
3603
  proceduralRunning: false,
@@ -3175,7 +3608,10 @@ var RigDetector = class {
3175
3608
  headLookAt: false,
3176
3609
  upperBodyGestures: false,
3177
3610
  facialAnimation: false,
3178
- clipPlayback: false,
3611
+ hasEmbeddedAnimations,
3612
+ embeddedAnimationCount,
3613
+ clipPlayback: hasEmbeddedAnimations,
3614
+ animationSourceMode: hasEmbeddedAnimations ? "embedded_only" : "static",
3179
3615
  missingRequiredBones: missingReq,
3180
3616
  missingOptionalBones: [...OPTIONAL_CANONICAL_BONES]
3181
3617
  };
@@ -3236,12 +3672,16 @@ ScratchMath.v4 = new THREE.Vector3();
3236
3672
  ScratchMath.v5 = new THREE.Vector3();
3237
3673
  ScratchMath.v6 = new THREE.Vector3();
3238
3674
  ScratchMath.v7 = new THREE.Vector3();
3675
+ ScratchMath.v8 = new THREE.Vector3();
3676
+ ScratchMath.v9 = new THREE.Vector3();
3239
3677
  // Quaternion scratch pool
3240
3678
  ScratchMath.q0 = new THREE.Quaternion();
3241
3679
  ScratchMath.q1 = new THREE.Quaternion();
3242
3680
  ScratchMath.q2 = new THREE.Quaternion();
3243
3681
  ScratchMath.q3 = new THREE.Quaternion();
3244
3682
  ScratchMath.q4 = new THREE.Quaternion();
3683
+ ScratchMath.q5 = new THREE.Quaternion();
3684
+ ScratchMath.q6 = new THREE.Quaternion();
3245
3685
  // Matrix4 scratch pool
3246
3686
  ScratchMath.m0 = new THREE.Matrix4();
3247
3687
  ScratchMath.m1 = new THREE.Matrix4();
@@ -3258,16 +3698,29 @@ ScratchMath.LEFT = new THREE.Vector3(-1, 0, 0);
3258
3698
 
3259
3699
  // src/avatar/procedural/AUBRSkeleton.ts
3260
3700
  var AUBRSkeleton = class {
3261
- constructor(modelRoot) {
3701
+ constructor(modelRoot, options) {
3262
3702
  this.joints = /* @__PURE__ */ new Map();
3703
+ /** Rest foot positions in modelRoot local space */
3704
+ this.restLeftFootModelPos = new THREE.Vector3();
3705
+ this.restRightFootModelPos = new THREE.Vector3();
3263
3706
  this.boneToCanonical = /* @__PURE__ */ new Map();
3707
+ this.restModelQuat = /* @__PURE__ */ new Map();
3708
+ this.restModelQuatInv = /* @__PURE__ */ new Map();
3264
3709
  this.modelRoot = modelRoot;
3265
- const detection = RigDetector.detect(modelRoot);
3710
+ this.modelRoot.updateMatrixWorld(true);
3711
+ const detection = RigDetector.detect(modelRoot, options);
3266
3712
  this.capabilities = detection.capabilities;
3713
+ const rootWorldQuatInv = new THREE.Quaternion();
3714
+ this.modelRoot.getWorldQuaternion(rootWorldQuatInv).invert();
3267
3715
  for (const [canonicalName, bone] of detection.matchedBones.entries()) {
3268
3716
  const restPos = bone.position.clone();
3269
3717
  const restQuat = bone.quaternion.clone();
3270
3718
  const restScale = bone.scale.clone();
3719
+ const boneWorldQuat = new THREE.Quaternion();
3720
+ bone.getWorldQuaternion(boneWorldQuat);
3721
+ const boneModelQuat = rootWorldQuatInv.clone().multiply(boneWorldQuat).normalize();
3722
+ this.restModelQuat.set(canonicalName, boneModelQuat);
3723
+ this.restModelQuatInv.set(canonicalName, boneModelQuat.clone().invert());
3271
3724
  let restDir = new THREE.Vector3(0, 1, 0);
3272
3725
  let boneLen = 0.2;
3273
3726
  if (bone.children.length > 0) {
@@ -3296,6 +3749,79 @@ var AUBRSkeleton = class {
3296
3749
  this.boneToCanonical.set(bone, canonicalName);
3297
3750
  }
3298
3751
  this.proportions = this.calculateProportions(detection.matchedBones);
3752
+ this.worldUnitsPerMeter = this.proportions.totalHeight / 1.8;
3753
+ const hipsBone = detection.matchedBones.get("hips");
3754
+ let hipsParentScale = 1;
3755
+ if (hipsBone?.parent) {
3756
+ const parentScaleVec = new THREE.Vector3();
3757
+ hipsBone.parent.getWorldScale(parentScaleVec);
3758
+ const avg = (Math.abs(parentScaleVec.x) + Math.abs(parentScaleVec.y) + Math.abs(parentScaleVec.z)) / 3;
3759
+ if (Number.isFinite(avg) && avg > 1e-5) {
3760
+ hipsParentScale = avg;
3761
+ }
3762
+ }
3763
+ this.hipsLocalPerMeter = this.worldUnitsPerMeter / hipsParentScale;
3764
+ const leftArmRest = this.measureArmRest("leftUpperArm", "leftLowerArm", 1);
3765
+ const rightArmRest = this.measureArmRest("rightUpperArm", "rightLowerArm", -1);
3766
+ this.leftArmRestAngleFromDown = leftArmRest.angleFromDown;
3767
+ this.leftArmLowerSign = leftArmRest.lowerSign;
3768
+ this.rightArmRestAngleFromDown = rightArmRest.angleFromDown;
3769
+ this.rightArmLowerSign = rightArmRest.lowerSign;
3770
+ const leftFoot = detection.matchedBones.get("leftFoot");
3771
+ const rightFoot = detection.matchedBones.get("rightFoot");
3772
+ if (leftFoot && rightFoot) {
3773
+ leftFoot.getWorldPosition(this.restLeftFootModelPos);
3774
+ this.modelRoot.worldToLocal(this.restLeftFootModelPos);
3775
+ rightFoot.getWorldPosition(this.restRightFootModelPos);
3776
+ this.modelRoot.worldToLocal(this.restRightFootModelPos);
3777
+ this.hasRestFootPositions = true;
3778
+ } else {
3779
+ this.hasRestFootPositions = false;
3780
+ }
3781
+ }
3782
+ measureArmRest(upperName, lowerName, defaultLateralX) {
3783
+ const upper = this.joints.get(upperName)?.bone;
3784
+ const lower = this.joints.get(lowerName)?.bone;
3785
+ if (!upper || !lower) {
3786
+ return { angleFromDown: 0, lowerSign: defaultLateralX >= 0 ? -1 : 1 };
3787
+ }
3788
+ upper.getWorldPosition(ScratchMath.v0);
3789
+ lower.getWorldPosition(ScratchMath.v1);
3790
+ this.modelRoot.worldToLocal(ScratchMath.v0);
3791
+ this.modelRoot.worldToLocal(ScratchMath.v1);
3792
+ const dir = ScratchMath.v2.subVectors(ScratchMath.v1, ScratchMath.v0);
3793
+ if (dir.lengthSq() < 1e-8) {
3794
+ return { angleFromDown: 0, lowerSign: defaultLateralX >= 0 ? -1 : 1 };
3795
+ }
3796
+ dir.normalize();
3797
+ const dotDown = Math.max(-1, Math.min(1, dir.dot(ScratchMath.DOWN)));
3798
+ const lateralX = Math.abs(dir.x) > 0.05 ? dir.x : defaultLateralX;
3799
+ return {
3800
+ angleFromDown: Math.acos(dotDown),
3801
+ lowerSign: lateralX >= 0 ? -1 : 1
3802
+ };
3803
+ }
3804
+ /**
3805
+ * Applies a rotation delta defined in character model space (+Y up, +Z forward, +X right/left)
3806
+ * relative to the joint's rest pose, converted cleanly into the bone's local coordinate frame.
3807
+ * Allocation-free and rig-agnostic across Mixamo, Rigify, Unreal, VRM, and generic humanoids.
3808
+ */
3809
+ applyModelDeltaRotation(name, modelDeltaQuat, weight = 1, additive = false) {
3810
+ const joint = this.joints.get(name);
3811
+ const restModel = this.restModelQuat.get(name);
3812
+ const restModelInv = this.restModelQuatInv.get(name);
3813
+ if (!joint || !restModel || !restModelInv || weight <= 1e-3) return;
3814
+ ScratchMath.q5.copy(restModelInv).multiply(modelDeltaQuat).multiply(restModel);
3815
+ if (additive) {
3816
+ ScratchMath.q6.copy(joint.targetQuaternion).multiply(ScratchMath.q5);
3817
+ } else {
3818
+ ScratchMath.q6.copy(joint.restQuaternion).multiply(ScratchMath.q5);
3819
+ }
3820
+ if (weight >= 0.999) {
3821
+ joint.targetQuaternion.copy(ScratchMath.q6);
3822
+ } else {
3823
+ joint.targetQuaternion.slerp(ScratchMath.q6, Math.max(0, Math.min(1, weight)));
3824
+ }
3299
3825
  }
3300
3826
  getJoint(name) {
3301
3827
  return this.joints.get(name);
@@ -3362,67 +3888,102 @@ var AUBRSkeleton = class {
3362
3888
  }
3363
3889
  }
3364
3890
  calculateProportions(bones) {
3365
- const box = new THREE.Box3().setFromObject(this.modelRoot);
3366
- const size = box.getSize(new THREE.Vector3());
3367
- const totalHeight = size.y > 0 ? size.y : 1.78;
3891
+ const box = new THREE.Box3();
3892
+ try {
3893
+ box.setFromObject(this.modelRoot);
3894
+ } catch {
3895
+ box.makeEmpty();
3896
+ }
3897
+ const size = box.isEmpty() ? new THREE.Vector3(0, 0, 0) : box.getSize(new THREE.Vector3());
3898
+ let totalHeight = size.y > 0.01 ? size.y : 0;
3899
+ const head = bones.get("head");
3900
+ const leftFoot = bones.get("leftFoot");
3901
+ const rightFoot = bones.get("rightFoot");
3902
+ const hips = bones.get("hips");
3903
+ if (totalHeight <= 0.01 && head && (leftFoot || rightFoot)) {
3904
+ head.getWorldPosition(ScratchMath.v0);
3905
+ (leftFoot || rightFoot).getWorldPosition(ScratchMath.v1);
3906
+ const headToFoot = Math.abs(ScratchMath.v0.y - ScratchMath.v1.y);
3907
+ if (headToFoot > 0.01) {
3908
+ totalHeight = headToFoot * 1.15;
3909
+ }
3910
+ }
3911
+ if (totalHeight <= 0.01 && head && hips) {
3912
+ head.getWorldPosition(ScratchMath.v0);
3913
+ hips.getWorldPosition(ScratchMath.v1);
3914
+ const headToHips = ScratchMath.v0.distanceTo(ScratchMath.v1);
3915
+ if (headToHips > 0.01) {
3916
+ totalHeight = headToHips * 2.2;
3917
+ }
3918
+ }
3919
+ if (totalHeight <= 0.01) {
3920
+ totalHeight = 1.78;
3921
+ }
3368
3922
  const leftUp = bones.get("leftUpperLeg");
3369
3923
  const leftLow = bones.get("leftLowerLeg");
3370
- const leftFoot = bones.get("leftFoot");
3371
- let thighLength = 0.45;
3372
- let shinLength = 0.43;
3373
- let footHeight = 0.08;
3924
+ let thighLength = totalHeight * 0.25;
3925
+ let shinLength = totalHeight * 0.24;
3926
+ let footHeight = totalHeight * 0.045;
3374
3927
  if (leftUp && leftLow) {
3375
3928
  leftUp.getWorldPosition(ScratchMath.v0);
3376
3929
  leftLow.getWorldPosition(ScratchMath.v1);
3377
- thighLength = ScratchMath.v0.distanceTo(ScratchMath.v1);
3930
+ const d = ScratchMath.v0.distanceTo(ScratchMath.v1);
3931
+ if (d > 1e-4) thighLength = d;
3378
3932
  }
3379
3933
  if (leftLow && leftFoot) {
3380
3934
  leftLow.getWorldPosition(ScratchMath.v0);
3381
3935
  leftFoot.getWorldPosition(ScratchMath.v1);
3382
- shinLength = ScratchMath.v0.distanceTo(ScratchMath.v1);
3383
- footHeight = Math.max(leftFoot.position.y, 0.08);
3936
+ const d = ScratchMath.v0.distanceTo(ScratchMath.v1);
3937
+ if (d > 1e-4) shinLength = d;
3938
+ if (!box.isEmpty()) {
3939
+ const rawFootY = ScratchMath.v1.y - box.min.y;
3940
+ footHeight = Math.max(totalHeight * 0.03, Math.min(totalHeight * 0.12, rawFootY));
3941
+ }
3384
3942
  }
3385
3943
  const legLength = thighLength + shinLength + footHeight;
3386
3944
  const spine = bones.get("spine");
3387
- const head = bones.get("head");
3388
- let spineLength = 0.52;
3945
+ let spineLength = totalHeight * 0.29;
3389
3946
  if (spine && head) {
3390
3947
  spine.getWorldPosition(ScratchMath.v0);
3391
3948
  head.getWorldPosition(ScratchMath.v1);
3392
- spineLength = ScratchMath.v0.distanceTo(ScratchMath.v1);
3949
+ const d = ScratchMath.v0.distanceTo(ScratchMath.v1);
3950
+ if (d > 1e-4) spineLength = d;
3393
3951
  }
3394
3952
  const leftArm = bones.get("leftUpperArm");
3395
3953
  const rightArm = bones.get("rightUpperArm");
3396
- let shoulderWidth = 0.42;
3954
+ let shoulderWidth = totalHeight * 0.23;
3397
3955
  if (leftArm && rightArm) {
3398
3956
  leftArm.getWorldPosition(ScratchMath.v0);
3399
3957
  rightArm.getWorldPosition(ScratchMath.v1);
3400
- shoulderWidth = ScratchMath.v0.distanceTo(ScratchMath.v1);
3958
+ const d = ScratchMath.v0.distanceTo(ScratchMath.v1);
3959
+ if (d > 1e-4) shoulderWidth = d;
3401
3960
  }
3402
3961
  const rightUp = bones.get("rightUpperLeg");
3403
- let hipWidth = 0.28;
3962
+ let hipWidth = totalHeight * 0.15;
3404
3963
  if (leftUp && rightUp) {
3405
3964
  leftUp.getWorldPosition(ScratchMath.v0);
3406
3965
  rightUp.getWorldPosition(ScratchMath.v1);
3407
- hipWidth = ScratchMath.v0.distanceTo(ScratchMath.v1);
3966
+ const d = ScratchMath.v0.distanceTo(ScratchMath.v1);
3967
+ if (d > 1e-4) hipWidth = d;
3408
3968
  }
3409
3969
  const leftHand = bones.get("leftHand");
3410
- let armLength = 0.65;
3970
+ let armLength = totalHeight * 0.36;
3411
3971
  if (leftArm && leftHand) {
3412
3972
  leftArm.getWorldPosition(ScratchMath.v0);
3413
3973
  leftHand.getWorldPosition(ScratchMath.v1);
3414
- armLength = ScratchMath.v0.distanceTo(ScratchMath.v1);
3974
+ const d = ScratchMath.v0.distanceTo(ScratchMath.v1);
3975
+ if (d > 1e-4) armLength = d;
3415
3976
  }
3416
3977
  return {
3417
3978
  totalHeight,
3418
- legLength: Math.max(legLength, 0.4),
3419
- thighLength: Math.max(thighLength, 0.2),
3420
- shinLength: Math.max(shinLength, 0.2),
3421
- footHeight: Math.max(footHeight, 0.05),
3422
- spineLength: Math.max(spineLength, 0.3),
3423
- shoulderWidth: Math.max(shoulderWidth, 0.25),
3424
- hipWidth: Math.max(hipWidth, 0.15),
3425
- armLength: Math.max(armLength, 0.35)
3979
+ legLength: Math.max(legLength, totalHeight * 0.25),
3980
+ thighLength: Math.max(thighLength, totalHeight * 0.12),
3981
+ shinLength: Math.max(shinLength, totalHeight * 0.12),
3982
+ footHeight: Math.max(footHeight, totalHeight * 0.025),
3983
+ spineLength: Math.max(spineLength, totalHeight * 0.15),
3984
+ shoulderWidth: Math.max(shoulderWidth, totalHeight * 0.12),
3985
+ hipWidth: Math.max(hipWidth, totalHeight * 0.08),
3986
+ armLength: Math.max(armLength, totalHeight * 0.2)
3426
3987
  };
3427
3988
  }
3428
3989
  };
@@ -3516,35 +4077,91 @@ var TwoBoneIK = class {
3516
4077
  };
3517
4078
  }
3518
4079
  /**
3519
- * Applies solved two-bone IK rotations to the target AUBR joints in-place.
4080
+ * Applies solved two-bone IK rotations to the target AUBR leg joints in-place
4081
+ * using rest-pose-preserving world-space delta rotations so Mixamo, Rigify, Unreal,
4082
+ * VRM, and generic humanoid bone orientations are never distorted.
4083
+ *
4084
+ * `targetFootPosWorld` and `poleDirWorld` are in world space (or model space when
4085
+ * `modelRoot` is omitted and bones are evaluated in local space).
3520
4086
  */
3521
- static applyLegIK(thighBone, shinBone, footBone, thighLength, shinLength, targetFootPosModel, poleVector, weight = 1, modelRoot) {
4087
+ static applyLegIK(thighBone, shinBone, footBone, thighLength, shinLength, targetFootPosWorld, poleDirWorld, weight = 1, _modelRoot) {
3522
4088
  if (weight <= 1e-3) return;
3523
- const rootPos = ScratchMath.v3;
3524
- thighBone.getWorldPosition(rootPos);
3525
- if (modelRoot) {
3526
- modelRoot.worldToLocal(rootPos);
3527
- } else if (thighBone.parent) {
3528
- thighBone.parent.worldToLocal(rootPos);
3529
- }
3530
- const chain = {
3531
- rootBone: thighBone,
3532
- midBone: shinBone,
3533
- endBone: footBone,
3534
- poleVector,
3535
- length1: thighLength,
3536
- length2: shinLength
3537
- };
3538
- const result = this.solveAnalytical(chain, targetFootPosModel, rootPos, poleVector);
3539
- if (weight >= 0.999) {
3540
- thighBone.quaternion.copy(result.rootRotation);
3541
- shinBone.quaternion.copy(result.midRotation);
4089
+ const clampedWeight = Math.max(0, Math.min(1, weight));
4090
+ const hipPos = ScratchMath.v0;
4091
+ const kneePos = ScratchMath.v1;
4092
+ const anklePos = ScratchMath.v2;
4093
+ thighBone.getWorldPosition(hipPos);
4094
+ shinBone.getWorldPosition(kneePos);
4095
+ footBone.getWorldPosition(anklePos);
4096
+ let l1 = hipPos.distanceTo(kneePos);
4097
+ let l2 = kneePos.distanceTo(anklePos);
4098
+ if (l1 < 1e-5) l1 = Math.max(thighLength, 0.05);
4099
+ if (l2 < 1e-5) l2 = Math.max(shinLength, 0.05);
4100
+ const maxReach = l1 + l2;
4101
+ const minReach = Math.abs(l1 - l2);
4102
+ const toTarget = ScratchMath.v3.subVectors(targetFootPosWorld, hipPos);
4103
+ const dist = toTarget.length();
4104
+ const clampedDist = Math.max(minReach + 1e-4, Math.min(dist, maxReach * 0.99999));
4105
+ if (dist < 1e-6) {
4106
+ toTarget.copy(ScratchMath.DOWN);
3542
4107
  } else {
3543
- thighBone.quaternion.slerp(result.rootRotation, weight);
3544
- shinBone.quaternion.slerp(result.midRotation, weight);
4108
+ toTarget.divideScalar(dist);
4109
+ }
4110
+ const bendDir = ScratchMath.v4.copy(poleDirWorld);
4111
+ const poleProj = bendDir.dot(toTarget);
4112
+ bendDir.addScaledVector(toTarget, -poleProj);
4113
+ if (bendDir.lengthSq() < 1e-6) {
4114
+ bendDir.crossVectors(toTarget, ScratchMath.RIGHT);
4115
+ if (bendDir.lengthSq() < 1e-6) {
4116
+ bendDir.crossVectors(toTarget, ScratchMath.FORWARD);
4117
+ }
4118
+ }
4119
+ bendDir.normalize();
4120
+ const cosAlpha = Math.max(
4121
+ -1,
4122
+ Math.min(1, (l1 * l1 + clampedDist * clampedDist - l2 * l2) / (2 * l1 * clampedDist))
4123
+ );
4124
+ const sinAlpha = Math.sqrt(Math.max(0, 1 - cosAlpha * cosAlpha));
4125
+ const desiredThighDir = ScratchMath.v5.copy(toTarget).multiplyScalar(cosAlpha).addScaledVector(bendDir, sinAlpha).normalize();
4126
+ const desiredKneePos = ScratchMath.v6.copy(hipPos).addScaledVector(desiredThighDir, l1);
4127
+ const desiredShinDir = ScratchMath.v7.subVectors(targetFootPosWorld, desiredKneePos);
4128
+ if (desiredShinDir.lengthSq() < 1e-8) {
4129
+ desiredShinDir.copy(toTarget);
4130
+ } else {
4131
+ desiredShinDir.normalize();
4132
+ }
4133
+ const currentThighDir = ScratchMath.v8.subVectors(kneePos, hipPos);
4134
+ if (currentThighDir.lengthSq() > 1e-10) {
4135
+ currentThighDir.normalize();
4136
+ ScratchMath.q0.setFromUnitVectors(currentThighDir, desiredThighDir);
4137
+ thighBone.getWorldQuaternion(ScratchMath.q1);
4138
+ ScratchMath.q2.copy(ScratchMath.q1).invert();
4139
+ ScratchMath.q3.copy(ScratchMath.q2).multiply(ScratchMath.q0).multiply(ScratchMath.q1);
4140
+ ScratchMath.q4.copy(thighBone.quaternion).multiply(ScratchMath.q3);
4141
+ if (clampedWeight >= 0.999) {
4142
+ thighBone.quaternion.copy(ScratchMath.q4);
4143
+ } else {
4144
+ thighBone.quaternion.slerp(ScratchMath.q4, clampedWeight);
4145
+ }
4146
+ thighBone.updateMatrixWorld(true);
4147
+ }
4148
+ shinBone.getWorldPosition(kneePos);
4149
+ footBone.getWorldPosition(anklePos);
4150
+ const currentShinDir = ScratchMath.v8.subVectors(anklePos, kneePos);
4151
+ if (currentShinDir.lengthSq() > 1e-10) {
4152
+ currentShinDir.normalize();
4153
+ ScratchMath.q0.setFromUnitVectors(currentShinDir, desiredShinDir);
4154
+ shinBone.getWorldQuaternion(ScratchMath.q1);
4155
+ ScratchMath.q2.copy(ScratchMath.q1).invert();
4156
+ ScratchMath.q3.copy(ScratchMath.q2).multiply(ScratchMath.q0).multiply(ScratchMath.q1);
4157
+ ScratchMath.q4.copy(shinBone.quaternion).multiply(ScratchMath.q3);
4158
+ if (clampedWeight >= 0.999) {
4159
+ shinBone.quaternion.copy(ScratchMath.q4);
4160
+ } else {
4161
+ shinBone.quaternion.slerp(ScratchMath.q4, clampedWeight);
4162
+ }
4163
+ shinBone.updateMatrixWorld(true);
3545
4164
  }
3546
- ScratchMath.q2.setFromAxisAngle(ScratchMath.RIGHT, 0);
3547
- footBone.quaternion.slerp(ScratchMath.q2, weight * 0.85);
3548
4165
  }
3549
4166
  };
3550
4167
  var _FABRIKSolver = class _FABRIKSolver {
@@ -3697,43 +4314,52 @@ var _FABRIKSolver = class _FABRIKSolver {
3697
4314
  };
3698
4315
  }
3699
4316
  /**
3700
- * Projects middle hinge joint onto plane defined by pole vector.
4317
+ * Projects middle hinge joint onto the half-plane defined by the pole direction vector.
3701
4318
  */
3702
4319
  static applyPoleVector(root, hinge, end, pole) {
3703
- const line = ScratchMath.v1.subVectors(end, root).normalize();
4320
+ const line = ScratchMath.v1.subVectors(end, root);
4321
+ if (line.lengthSq() < 1e-10) return;
4322
+ line.normalize();
3704
4323
  const toHinge = ScratchMath.v2.subVectors(hinge, root);
3705
4324
  const projDist = toHinge.dot(line);
3706
4325
  const projPoint = ScratchMath.v3.copy(root).addScaledVector(line, projDist);
3707
- const currentNormal = ScratchMath.v4.subVectors(hinge, projPoint).normalize();
3708
- const desiredNormal = ScratchMath.v5.subVectors(pole, projPoint).normalize();
3709
- if (currentNormal.lengthSq() > 1e-3 && desiredNormal.lengthSq() > 1e-3) {
4326
+ const desiredNormal = ScratchMath.v5.copy(pole).addScaledVector(line, -pole.dot(line));
4327
+ if (desiredNormal.lengthSq() > 1e-6) {
4328
+ desiredNormal.normalize();
3710
4329
  const hingeDist = hinge.distanceTo(projPoint);
3711
- hinge.copy(projPoint).addScaledVector(desiredNormal, Math.max(hingeDist, 0.05));
4330
+ hinge.copy(projPoint).addScaledVector(desiredNormal, Math.max(hingeDist, 0.02));
3712
4331
  }
3713
4332
  }
3714
4333
  /**
3715
4334
  * Converts solved world positions back into local bone rotations for the Three.js hierarchy.
4335
+ * Calculates delta rotation in world space from current bone direction to solved target direction,
4336
+ * transforming into local bone space to guarantee zero deformation when positions match rest pose.
3716
4337
  */
3717
4338
  static applyPositionsToBones(chain, solvedPositions, weight = 1) {
3718
4339
  if (solvedPositions.length < 2 || weight <= 1e-3) return;
3719
4340
  for (let i = 0; i < chain.bones.length - 1; i++) {
3720
4341
  const bone = chain.bones[i];
4342
+ const nextBone = chain.bones[i + 1];
3721
4343
  const nextPos = solvedPositions[i + 1];
3722
- if (!bone || !nextPos) continue;
4344
+ if (!bone || !nextBone || !nextPos) continue;
3723
4345
  bone.getWorldPosition(ScratchMath.v0);
4346
+ nextBone.getWorldPosition(ScratchMath.v2);
4347
+ const currentDirWorld = ScratchMath.v3.subVectors(ScratchMath.v2, ScratchMath.v0);
4348
+ if (currentDirWorld.lengthSq() < 1e-10) continue;
4349
+ currentDirWorld.normalize();
3724
4350
  const targetDirWorld = ScratchMath.v1.subVectors(nextPos, ScratchMath.v0);
3725
4351
  if (targetDirWorld.lengthSq() < 1e-10) continue;
3726
4352
  targetDirWorld.normalize();
3727
- if (bone.parent) {
3728
- ScratchMath.m0.copy(bone.parent.matrixWorld).invert();
3729
- targetDirWorld.transformDirection(ScratchMath.m0).normalize();
3730
- }
3731
- const restDir = ScratchMath.RIGHT;
3732
- ScratchMath.q0.setFromUnitVectors(restDir, targetDirWorld);
4353
+ ScratchMath.q0.setFromUnitVectors(currentDirWorld, targetDirWorld);
4354
+ bone.getWorldQuaternion(ScratchMath.q1);
4355
+ ScratchMath.q2.copy(ScratchMath.q1).invert();
4356
+ ScratchMath.q3.copy(ScratchMath.q2).multiply(ScratchMath.q0).multiply(ScratchMath.q1);
4357
+ const currentLocalQuat = ScratchMath.q4.copy(bone.quaternion);
4358
+ const targetLocalQuat = ScratchMath.q3.premultiply(currentLocalQuat);
3733
4359
  if (weight >= 0.999) {
3734
- bone.quaternion.copy(ScratchMath.q0);
4360
+ bone.quaternion.copy(targetLocalQuat);
3735
4361
  } else {
3736
- bone.quaternion.slerp(ScratchMath.q0, weight);
4362
+ bone.quaternion.copy(currentLocalQuat).slerp(targetLocalQuat, weight);
3737
4363
  }
3738
4364
  bone.updateMatrixWorld(true);
3739
4365
  }
@@ -3765,21 +4391,25 @@ var IKCoordinator = class {
3765
4391
  }
3766
4392
  /**
3767
4393
  * Solves and applies left leg Two-Bone IK.
4394
+ * `targetFootPosModel` is in `skeleton.modelRoot` local space.
3768
4395
  */
3769
4396
  solveLeftLeg(targetFootPosModel, weight = 1) {
3770
4397
  const thigh = this.skeleton.getJoint("leftUpperLeg");
3771
4398
  const shin = this.skeleton.getJoint("leftLowerLeg");
3772
4399
  const foot = this.skeleton.getJoint("leftFoot");
3773
- if (!thigh || !shin || !foot) return;
3774
- const pole = ScratchMath.v6.copy(ScratchMath.FORWARD);
4400
+ if (!thigh || !shin || !foot || weight <= 1e-3) return;
4401
+ const targetWorld = ScratchMath.v9.copy(targetFootPosModel);
4402
+ this.skeleton.modelRoot.localToWorld(targetWorld);
4403
+ this.skeleton.modelRoot.getWorldQuaternion(ScratchMath.q5);
4404
+ const poleWorld = ScratchMath.v8.copy(ScratchMath.FORWARD).applyQuaternion(ScratchMath.q5).normalize();
3775
4405
  TwoBoneIK.applyLegIK(
3776
4406
  thigh.bone,
3777
4407
  shin.bone,
3778
4408
  foot.bone,
3779
4409
  this.skeleton.proportions.thighLength,
3780
4410
  this.skeleton.proportions.shinLength,
3781
- targetFootPosModel,
3782
- pole,
4411
+ targetWorld,
4412
+ poleWorld,
3783
4413
  weight,
3784
4414
  this.skeleton.modelRoot
3785
4415
  );
@@ -3789,21 +4419,25 @@ var IKCoordinator = class {
3789
4419
  }
3790
4420
  /**
3791
4421
  * Solves and applies right leg Two-Bone IK.
4422
+ * `targetFootPosModel` is in `skeleton.modelRoot` local space.
3792
4423
  */
3793
4424
  solveRightLeg(targetFootPosModel, weight = 1) {
3794
4425
  const thigh = this.skeleton.getJoint("rightUpperLeg");
3795
4426
  const shin = this.skeleton.getJoint("rightLowerLeg");
3796
4427
  const foot = this.skeleton.getJoint("rightFoot");
3797
- if (!thigh || !shin || !foot) return;
3798
- const pole = ScratchMath.v6.copy(ScratchMath.FORWARD);
4428
+ if (!thigh || !shin || !foot || weight <= 1e-3) return;
4429
+ const targetWorld = ScratchMath.v9.copy(targetFootPosModel);
4430
+ this.skeleton.modelRoot.localToWorld(targetWorld);
4431
+ this.skeleton.modelRoot.getWorldQuaternion(ScratchMath.q5);
4432
+ const poleWorld = ScratchMath.v8.copy(ScratchMath.FORWARD).applyQuaternion(ScratchMath.q5).normalize();
3799
4433
  TwoBoneIK.applyLegIK(
3800
4434
  thigh.bone,
3801
4435
  shin.bone,
3802
4436
  foot.bone,
3803
4437
  this.skeleton.proportions.thighLength,
3804
4438
  this.skeleton.proportions.shinLength,
3805
- targetFootPosModel,
3806
- pole,
4439
+ targetWorld,
4440
+ poleWorld,
3807
4441
  weight,
3808
4442
  this.skeleton.modelRoot
3809
4443
  );
@@ -3817,7 +4451,8 @@ var IKCoordinator = class {
3817
4451
  solveArmReach(side, targetPosWorld, weight = 1) {
3818
4452
  const chain = side === "left" ? this.leftArmChain : this.rightArmChain;
3819
4453
  if (!chain || weight <= 1e-3) return;
3820
- const pole = side === "left" ? ScratchMath.v7.set(-0.5, 0, -1).normalize() : ScratchMath.v7.set(0.5, 0, -1).normalize();
4454
+ this.skeleton.modelRoot.getWorldQuaternion(ScratchMath.q5);
4455
+ const pole = (side === "left" ? ScratchMath.v7.set(-0.5, 0, -1).normalize() : ScratchMath.v7.set(0.5, 0, -1).normalize()).applyQuaternion(ScratchMath.q5);
3821
4456
  const result = FABRIKSolver.solve(chain, targetPosWorld, pole);
3822
4457
  FABRIKSolver.applyPositionsToBones(chain, result.solvedPositions, weight);
3823
4458
  const upper = this.skeleton.getJoint(side === "left" ? "leftUpperArm" : "rightUpperArm");
@@ -3841,63 +4476,86 @@ var IdleEngine = class {
3841
4476
  this.targetWeightShift = 0;
3842
4477
  this.nextWeightShiftTime = 3.5;
3843
4478
  }
4479
+ reset() {
4480
+ this.clock = 0;
4481
+ this.breathPhase = 0;
4482
+ this.swayPhase = 0;
4483
+ this.weightShift = 0;
4484
+ this.targetWeightShift = 0;
4485
+ this.nextWeightShiftTime = 3.5;
4486
+ }
3844
4487
  update(delta, weight = 1) {
3845
4488
  if (weight <= 1e-3) return;
4489
+ const w = Math.max(0, Math.min(1, weight));
3846
4490
  this.clock += delta;
3847
4491
  this.breathPhase += delta * 0.28;
3848
- this.swayPhase += delta * 0.12;
4492
+ this.swayPhase += delta * 0.14;
3849
4493
  if (this.clock > this.nextWeightShiftTime) {
3850
- this.targetWeightShift = (Math.random() - 0.5) * 1.6;
4494
+ this.targetWeightShift = (Math.random() - 0.5) * 1.4;
3851
4495
  this.nextWeightShiftTime = this.clock + 4 + Math.random() * 4;
3852
4496
  }
3853
- this.weightShift = ScratchMath.damp(this.weightShift, this.targetWeightShift, 1.2, delta);
4497
+ this.weightShift = ScratchMath.damp(this.weightShift, this.targetWeightShift, 1.4, delta);
4498
+ const localScale = this.skeleton.hipsLocalPerMeter;
3854
4499
  const breathSin = Math.sin(this.breathPhase * Math.PI * 2);
3855
- const spinePitch = breathSin * 0.015;
3856
- const chestPitch = breathSin * 0.022;
4500
+ const spinePitch = breathSin * 0.022 * w;
4501
+ const chestPitch = breathSin * 0.028 * w;
3857
4502
  const swaySin = Math.sin(this.swayPhase * Math.PI * 2);
3858
- const pelvicX = (swaySin * 6e-3 + this.weightShift * 0.012) * weight;
3859
- const pelvicY = breathSin * 4e-3 * weight;
3860
- const pelvicRoll = -this.weightShift * 0.018 * weight;
4503
+ const pelvicX = (swaySin * 8e-3 + this.weightShift * 0.014) * localScale * w;
4504
+ const pelvicY = breathSin * 5e-3 * localScale * w;
4505
+ const pelvicRoll = -this.weightShift * 0.022 * w;
3861
4506
  const hips = this.skeleton.getJoint("hips");
3862
4507
  if (hips) {
3863
4508
  hips.targetPosition.x = hips.restPosition.x + pelvicX;
3864
4509
  hips.targetPosition.y = hips.restPosition.y + pelvicY;
3865
4510
  ScratchMath.e0.set(0, 0, pelvicRoll, "YXZ");
3866
4511
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
3867
- hips.targetQuaternion.copy(hips.restQuaternion).multiply(ScratchMath.q0);
4512
+ this.skeleton.applyModelDeltaRotation("hips", ScratchMath.q0, w);
3868
4513
  }
3869
- const spine = this.skeleton.getJoint("spine");
3870
- if (spine) {
3871
- ScratchMath.e0.set(spinePitch * weight, 0, 0, "YXZ");
4514
+ if (this.skeleton.hasJoint("spine")) {
4515
+ ScratchMath.e0.set(spinePitch, swaySin * 0.012 * w, -pelvicRoll * 0.4, "YXZ");
3872
4516
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
3873
- spine.targetQuaternion.copy(spine.restQuaternion).multiply(ScratchMath.q0);
4517
+ this.skeleton.applyModelDeltaRotation("spine", ScratchMath.q0, w);
3874
4518
  }
3875
- const chest = this.skeleton.getJoint("chest") || this.skeleton.getJoint("upperChest");
3876
- if (chest) {
3877
- ScratchMath.e0.set(chestPitch * weight, 0, 0, "YXZ");
4519
+ const chestName = this.skeleton.hasJoint("chest") ? "chest" : this.skeleton.hasJoint("upperChest") ? "upperChest" : null;
4520
+ if (chestName) {
4521
+ ScratchMath.e0.set(chestPitch, 0, 0, "YXZ");
3878
4522
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
3879
- chest.targetQuaternion.copy(chest.restQuaternion).multiply(ScratchMath.q0);
4523
+ this.skeleton.applyModelDeltaRotation(chestName, ScratchMath.q0, w);
3880
4524
  }
3881
- const head = this.skeleton.getJoint("head");
3882
- if (head) {
3883
- const headCounterRoll = -pelvicRoll * 0.6;
3884
- const headCounterPitch = -spinePitch * 0.5;
4525
+ if (this.skeleton.hasJoint("head")) {
4526
+ const headCounterRoll = -pelvicRoll * 0.5;
4527
+ const headCounterPitch = -spinePitch * 0.45;
3885
4528
  ScratchMath.e0.set(headCounterPitch, 0, headCounterRoll, "YXZ");
3886
4529
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
3887
- head.targetQuaternion.copy(head.restQuaternion).multiply(ScratchMath.q0);
3888
- }
3889
- const lArm = this.skeleton.getJoint("leftUpperArm");
3890
- const rArm = this.skeleton.getJoint("rightUpperArm");
3891
- const armSway = breathSin * 0.012 * weight;
3892
- if (lArm) {
3893
- ScratchMath.e0.set(armSway, 0, armSway * 0.5, "YXZ");
3894
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
3895
- lArm.targetQuaternion.copy(lArm.restQuaternion).multiply(ScratchMath.q0);
3896
- }
3897
- if (rArm) {
3898
- ScratchMath.e0.set(armSway, 0, -armSway * 0.5, "YXZ");
3899
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
3900
- rArm.targetQuaternion.copy(rArm.restQuaternion).multiply(ScratchMath.q0);
4530
+ this.skeleton.applyModelDeltaRotation("head", ScratchMath.q0, w);
4531
+ }
4532
+ const targetStandingArmAngle = 0.28;
4533
+ const armBreathSway = breathSin * 0.025;
4534
+ const armOutSway = breathSin * 0.018;
4535
+ if (this.skeleton.hasJoint("leftUpperArm")) {
4536
+ const relaxAngle = Math.max(0, this.skeleton.leftArmRestAngleFromDown - targetStandingArmAngle);
4537
+ const lowerZ = this.skeleton.leftArmLowerSign * (relaxAngle - armOutSway);
4538
+ ScratchMath.q1.setFromAxisAngle(ScratchMath.FORWARD, lowerZ);
4539
+ ScratchMath.q2.setFromAxisAngle(ScratchMath.RIGHT, -armBreathSway);
4540
+ ScratchMath.q0.copy(ScratchMath.q2).multiply(ScratchMath.q1);
4541
+ this.skeleton.applyModelDeltaRotation("leftUpperArm", ScratchMath.q0, w);
4542
+ }
4543
+ if (this.skeleton.hasJoint("rightUpperArm")) {
4544
+ const relaxAngle = Math.max(0, this.skeleton.rightArmRestAngleFromDown - targetStandingArmAngle);
4545
+ const lowerZ = this.skeleton.rightArmLowerSign * (relaxAngle - armOutSway);
4546
+ ScratchMath.q1.setFromAxisAngle(ScratchMath.FORWARD, lowerZ);
4547
+ ScratchMath.q2.setFromAxisAngle(ScratchMath.RIGHT, -armBreathSway);
4548
+ ScratchMath.q0.copy(ScratchMath.q2).multiply(ScratchMath.q1);
4549
+ this.skeleton.applyModelDeltaRotation("rightUpperArm", ScratchMath.q0, w);
4550
+ }
4551
+ const elbowRelaxFlex = 0.16 + breathSin * 0.015;
4552
+ if (this.skeleton.hasJoint("leftLowerArm")) {
4553
+ ScratchMath.q0.setFromAxisAngle(ScratchMath.RIGHT, -elbowRelaxFlex);
4554
+ this.skeleton.applyModelDeltaRotation("leftLowerArm", ScratchMath.q0, w);
4555
+ }
4556
+ if (this.skeleton.hasJoint("rightLowerArm")) {
4557
+ ScratchMath.q0.setFromAxisAngle(ScratchMath.RIGHT, -elbowRelaxFlex);
4558
+ this.skeleton.applyModelDeltaRotation("rightLowerArm", ScratchMath.q0, w);
3901
4559
  }
3902
4560
  }
3903
4561
  };
@@ -3940,9 +4598,10 @@ var LocomotionEngine = class {
3940
4598
  return this.phase;
3941
4599
  }
3942
4600
  calibrateStride() {
3943
- const legLen = this.skeleton.proportions.legLength;
3944
- this.strideLength = Math.max(0.35, legLen * 0.78);
3945
- this.stepHeight = Math.max(0.04, legLen * 0.095);
4601
+ const unitScale = this.skeleton.hipsLocalPerMeter;
4602
+ const legLenLocal = Math.max(0.4 * unitScale, this.skeleton.proportions.legLength / Math.max(this.skeleton.worldUnitsPerMeter, 1e-4) * unitScale);
4603
+ this.strideLength = Math.max(0.35 * unitScale, legLenLocal * 0.72);
4604
+ this.stepHeight = Math.max(0.04 * unitScale, legLenLocal * 0.11);
3946
4605
  }
3947
4606
  setMotion(params) {
3948
4607
  this.targetSpeed = Math.max(0, params.speed);
@@ -3952,113 +4611,128 @@ var LocomotionEngine = class {
3952
4611
  const stridesPerSecond = params.screenVelocityPx / 180;
3953
4612
  this.baseFrequency = Math.max(0.8, Math.min(3.2, stridesPerSecond * 2));
3954
4613
  } else {
3955
- this.baseFrequency = this.isRunning ? 2.6 : 1.5;
4614
+ this.baseFrequency = this.isRunning ? 2.4 : 1.35;
3956
4615
  }
3957
4616
  }
3958
4617
  stop() {
3959
4618
  this.targetSpeed = 0;
3960
4619
  this.moving = false;
3961
4620
  }
4621
+ cancel() {
4622
+ this.targetSpeed = 0;
4623
+ this.currentSpeed = 0;
4624
+ this.moving = false;
4625
+ this.isRunning = false;
4626
+ }
3962
4627
  update(delta, weight = 1) {
3963
- this.currentSpeed = ScratchMath.damp(this.currentSpeed, this.targetSpeed, 4, delta);
4628
+ const speedDamp = this.moving ? 6.5 : 8;
4629
+ this.currentSpeed = ScratchMath.damp(this.currentSpeed, this.targetSpeed, speedDamp, delta);
3964
4630
  if (this.currentSpeed <= 0.01 && weight <= 1e-3) return;
3965
- const effectiveFreq = this.baseFrequency * Math.max(0.3, this.currentSpeed);
4631
+ const w = Math.max(0, Math.min(1, weight));
4632
+ const speedRatio = Math.min(this.currentSpeed, 2.2);
4633
+ const activeAmplitude = Math.min(1, this.currentSpeed / 0.35) * w;
4634
+ if (activeAmplitude <= 1e-3) return;
4635
+ const effectiveFreq = this.baseFrequency * Math.max(0.35, Math.min(1.6, this.currentSpeed));
3966
4636
  this.phase = (this.phase + effectiveFreq * delta) % 1;
3967
4637
  const phi = this.phase;
3968
4638
  const twoPiPhi = phi * Math.PI * 2;
3969
- const speedRatio = Math.min(this.currentSpeed, 2);
3970
- const bobAmplitude = (this.isRunning ? 0.045 : 0.024) * speedRatio;
4639
+ const localScale = this.skeleton.hipsLocalPerMeter;
4640
+ const bobAmplitude = (this.isRunning ? 0.05 : 0.028) * speedRatio * localScale;
3971
4641
  const pelvicY = -bobAmplitude * Math.abs(Math.sin(twoPiPhi));
3972
- const swayAmplitude = (this.isRunning ? 0.018 : 0.028) * speedRatio;
4642
+ const swayAmplitude = (this.isRunning ? 0.02 : 0.03) * speedRatio * localScale;
3973
4643
  const pelvicX = swayAmplitude * Math.sin(twoPiPhi);
3974
4644
  const yawAmplitude = (this.isRunning ? 0.14 : 0.09) * speedRatio;
3975
4645
  const pelvicYaw = yawAmplitude * Math.cos(twoPiPhi);
3976
- const rollAmplitude = 0.035 * speedRatio;
4646
+ const rollAmplitude = 0.04 * speedRatio;
3977
4647
  const pelvicRoll = -rollAmplitude * Math.sin(twoPiPhi);
3978
4648
  const hips = this.skeleton.getJoint("hips");
3979
4649
  if (hips) {
3980
- hips.targetPosition.x = hips.restPosition.x + pelvicX * weight;
3981
- hips.targetPosition.y = hips.restPosition.y + pelvicY * weight;
3982
- ScratchMath.e0.set(0.04 * speedRatio, pelvicYaw * weight, pelvicRoll * weight, "YXZ");
4650
+ hips.targetPosition.x = hips.restPosition.x + pelvicX * w;
4651
+ hips.targetPosition.y = hips.restPosition.y + pelvicY * w;
4652
+ ScratchMath.e0.set((this.isRunning ? 0.08 : 0.04) * speedRatio, pelvicYaw, pelvicRoll, "YXZ");
3983
4653
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
3984
- hips.targetQuaternion.copy(hips.restQuaternion).multiply(ScratchMath.q0);
4654
+ this.skeleton.applyModelDeltaRotation("hips", ScratchMath.q0, activeAmplitude);
3985
4655
  }
3986
- const spine = this.skeleton.getJoint("spine");
3987
- if (spine) {
3988
- const spineCounterYaw = -pelvicYaw * 0.65 * weight;
3989
- ScratchMath.e0.set(-0.02 * speedRatio, spineCounterYaw, 0, "YXZ");
4656
+ if (this.skeleton.hasJoint("spine")) {
4657
+ const spineCounterYaw = -pelvicYaw * 0.65;
4658
+ ScratchMath.e0.set((this.isRunning ? 0.08 : 0.03) * speedRatio, spineCounterYaw, -pelvicRoll * 0.35, "YXZ");
3990
4659
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
3991
- spine.targetQuaternion.copy(spine.restQuaternion).multiply(ScratchMath.q0);
4660
+ this.skeleton.applyModelDeltaRotation("spine", ScratchMath.q0, activeAmplitude);
3992
4661
  }
3993
- const chest = this.skeleton.getJoint("chest") || this.skeleton.getJoint("upperChest");
3994
- if (chest) {
3995
- const chestCounterYaw = -pelvicYaw * 0.35 * weight;
3996
- ScratchMath.e0.set(0.01, chestCounterYaw, 0, "YXZ");
4662
+ const chestName = this.skeleton.hasJoint("chest") ? "chest" : this.skeleton.hasJoint("upperChest") ? "upperChest" : null;
4663
+ if (chestName) {
4664
+ const chestCounterYaw = -pelvicYaw * 0.35;
4665
+ ScratchMath.e0.set(0.02 * speedRatio, chestCounterYaw, 0, "YXZ");
3997
4666
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
3998
- chest.targetQuaternion.copy(chest.restQuaternion).multiply(ScratchMath.q0);
3999
- }
4000
- const hipWidthHalf = this.skeleton.proportions.hipWidth * 0.5;
4001
- const groundY = 0;
4002
- const halfStride = this.strideLength * 0.5 * speedRatio;
4003
- let leftX = -hipWidthHalf;
4004
- let leftY = groundY;
4005
- let leftZ = 0;
4667
+ this.skeleton.applyModelDeltaRotation(chestName, ScratchMath.q0, activeAmplitude);
4668
+ }
4669
+ const halfStride = this.strideLength * 0.5 * Math.min(speedRatio, 1.45);
4670
+ const liftHeight = this.stepHeight * Math.min(speedRatio, 1.5);
4671
+ const baseLeftX = this.skeleton.hasRestFootPositions ? this.skeleton.restLeftFootModelPos.x : -this.skeleton.proportions.hipWidth * 0.5;
4672
+ const baseLeftY = this.skeleton.hasRestFootPositions ? this.skeleton.restLeftFootModelPos.y : 0;
4673
+ const baseLeftZ = this.skeleton.hasRestFootPositions ? this.skeleton.restLeftFootModelPos.z : 0;
4674
+ const baseRightX = this.skeleton.hasRestFootPositions ? this.skeleton.restRightFootModelPos.x : this.skeleton.proportions.hipWidth * 0.5;
4675
+ const baseRightY = this.skeleton.hasRestFootPositions ? this.skeleton.restRightFootModelPos.y : 0;
4676
+ const baseRightZ = this.skeleton.hasRestFootPositions ? this.skeleton.restRightFootModelPos.z : 0;
4677
+ let leftY = baseLeftY;
4678
+ let leftZ = baseLeftZ;
4006
4679
  if (phi < 0.5) {
4007
4680
  const s = phi / 0.5;
4008
- leftZ = halfStride * (1 - 2 * s);
4009
- leftY = groundY;
4681
+ leftZ = baseLeftZ + halfStride * (1 - 2 * s);
4010
4682
  } else {
4011
4683
  const s = (phi - 0.5) / 0.5;
4012
- leftZ = halfStride * (2 * s - 1);
4013
- leftY = groundY + this.stepHeight * speedRatio * (4 * s * (1 - s));
4684
+ leftZ = baseLeftZ + halfStride * (2 * s - 1);
4685
+ leftY = baseLeftY + liftHeight * (4 * s * (1 - s));
4014
4686
  }
4015
- let rightX = hipWidthHalf;
4016
- let rightY = groundY;
4017
- let rightZ = 0;
4687
+ let rightY = baseRightY;
4688
+ let rightZ = baseRightZ;
4018
4689
  if (phi < 0.5) {
4019
4690
  const s = phi / 0.5;
4020
- rightZ = halfStride * (2 * s - 1);
4021
- rightY = groundY + this.stepHeight * speedRatio * (4 * s * (1 - s));
4691
+ rightZ = baseRightZ + halfStride * (2 * s - 1);
4692
+ rightY = baseRightY + liftHeight * (4 * s * (1 - s));
4022
4693
  } else {
4023
4694
  const s = (phi - 0.5) / 0.5;
4024
- rightZ = halfStride * (1 - 2 * s);
4025
- rightY = groundY;
4695
+ rightZ = baseRightZ + halfStride * (1 - 2 * s);
4026
4696
  }
4027
- this.leftFootTarget.set(leftX, leftY, leftZ);
4028
- this.rightFootTarget.set(rightX, rightY, rightZ);
4697
+ this.leftFootTarget.set(baseLeftX, leftY, leftZ);
4698
+ this.rightFootTarget.set(baseRightX, rightY, rightZ);
4029
4699
  if (this.ik) {
4030
- this.ik.solveLeftLeg(this.leftFootTarget, weight);
4031
- this.ik.solveRightLeg(this.rightFootTarget, weight);
4032
- }
4033
- const armSwingAngle = (this.isRunning ? 0.65 : 0.38) * speedRatio * weight;
4034
- const lArmAngle = -Math.sin(twoPiPhi) * armSwingAngle;
4035
- const rArmAngle = Math.sin(twoPiPhi) * armSwingAngle;
4036
- const lArm = this.skeleton.getJoint("leftUpperArm");
4037
- const rArm = this.skeleton.getJoint("rightUpperArm");
4038
- const lForeArm = this.skeleton.getJoint("leftLowerArm");
4039
- const rForeArm = this.skeleton.getJoint("rightLowerArm");
4040
- if (lArm) {
4041
- ScratchMath.e0.set(lArmAngle, 0, 0.05, "YXZ");
4042
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4043
- lArm.targetQuaternion.copy(lArm.restQuaternion).multiply(ScratchMath.q0);
4044
- }
4045
- if (rArm) {
4046
- ScratchMath.e0.set(rArmAngle, 0, -0.05, "YXZ");
4047
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4048
- rArm.targetQuaternion.copy(rArm.restQuaternion).multiply(ScratchMath.q0);
4049
- }
4050
- const elbowFlexBase = this.isRunning ? 0.55 : 0.25;
4051
- if (lForeArm) {
4052
- const flex = elbowFlexBase + Math.max(0, -Math.sin(twoPiPhi)) * 0.35;
4053
- ScratchMath.e0.set(flex * weight, 0, 0, "YXZ");
4054
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4055
- lForeArm.targetQuaternion.copy(lForeArm.restQuaternion).multiply(ScratchMath.q0);
4056
- }
4057
- if (rForeArm) {
4058
- const flex = elbowFlexBase + Math.max(0, Math.sin(twoPiPhi)) * 0.35;
4059
- ScratchMath.e0.set(flex * weight, 0, 0, "YXZ");
4060
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4061
- rForeArm.targetQuaternion.copy(rForeArm.restQuaternion).multiply(ScratchMath.q0);
4700
+ if (hips) {
4701
+ hips.bone.position.copy(hips.targetPosition);
4702
+ hips.bone.quaternion.copy(hips.targetQuaternion);
4703
+ hips.bone.updateMatrixWorld(true);
4704
+ }
4705
+ this.ik.solveLeftLeg(this.leftFootTarget, activeAmplitude);
4706
+ this.ik.solveRightLeg(this.rightFootTarget, activeAmplitude);
4707
+ }
4708
+ const targetStandingArmAngle = 0.25;
4709
+ const armSwingAngle = (this.isRunning ? 0.72 : 0.42) * Math.min(speedRatio, 1.5);
4710
+ const lArmForward = -Math.sin(twoPiPhi) * armSwingAngle;
4711
+ const rArmForward = Math.sin(twoPiPhi) * armSwingAngle;
4712
+ if (this.skeleton.hasJoint("leftUpperArm")) {
4713
+ const relaxAngle = Math.max(0, this.skeleton.leftArmRestAngleFromDown - targetStandingArmAngle);
4714
+ ScratchMath.q1.setFromAxisAngle(ScratchMath.FORWARD, this.skeleton.leftArmLowerSign * relaxAngle);
4715
+ ScratchMath.q2.setFromAxisAngle(ScratchMath.RIGHT, -lArmForward);
4716
+ ScratchMath.q0.copy(ScratchMath.q2).multiply(ScratchMath.q1);
4717
+ this.skeleton.applyModelDeltaRotation("leftUpperArm", ScratchMath.q0, activeAmplitude);
4718
+ }
4719
+ if (this.skeleton.hasJoint("rightUpperArm")) {
4720
+ const relaxAngle = Math.max(0, this.skeleton.rightArmRestAngleFromDown - targetStandingArmAngle);
4721
+ ScratchMath.q1.setFromAxisAngle(ScratchMath.FORWARD, this.skeleton.rightArmLowerSign * relaxAngle);
4722
+ ScratchMath.q2.setFromAxisAngle(ScratchMath.RIGHT, -rArmForward);
4723
+ ScratchMath.q0.copy(ScratchMath.q2).multiply(ScratchMath.q1);
4724
+ this.skeleton.applyModelDeltaRotation("rightUpperArm", ScratchMath.q0, activeAmplitude);
4725
+ }
4726
+ const elbowFlexBase = this.isRunning ? 0.85 : 0.28;
4727
+ if (this.skeleton.hasJoint("leftLowerArm")) {
4728
+ const flex = elbowFlexBase + Math.max(0, lArmForward) * 0.45;
4729
+ ScratchMath.q0.setFromAxisAngle(ScratchMath.RIGHT, -flex);
4730
+ this.skeleton.applyModelDeltaRotation("leftLowerArm", ScratchMath.q0, activeAmplitude);
4731
+ }
4732
+ if (this.skeleton.hasJoint("rightLowerArm")) {
4733
+ const flex = elbowFlexBase + Math.max(0, rArmForward) * 0.45;
4734
+ ScratchMath.q0.setFromAxisAngle(ScratchMath.RIGHT, -flex);
4735
+ this.skeleton.applyModelDeltaRotation("rightLowerArm", ScratchMath.q0, activeAmplitude);
4062
4736
  }
4063
4737
  }
4064
4738
  getPhase() {
@@ -4071,18 +4745,26 @@ var LocomotionEngine = class {
4071
4745
 
4072
4746
  // src/avatar/procedural/TurnEngine.ts
4073
4747
  var TurnEngine = class {
4074
- constructor(skeleton) {
4748
+ constructor(skeleton, turnTarget) {
4075
4749
  this.skeleton = skeleton;
4076
4750
  this.currentYaw = 0;
4077
- // Current character yaw in radians
4751
+ // Current character yaw offset in radians
4078
4752
  this.targetYaw = 0;
4079
- // Target desired yaw in radians
4753
+ // Target desired yaw offset in radians
4080
4754
  this.isTurning = false;
4081
4755
  this.turnAngularVelocity = 0;
4756
+ this.turnTarget = turnTarget ?? skeleton.modelRoot;
4757
+ this.baseYaw = this.turnTarget.rotation.y;
4082
4758
  }
4083
4759
  setTargetHeading(targetYawRad) {
4084
4760
  this.targetYaw = targetYawRad;
4085
4761
  }
4762
+ turnLeft(stepRad = Math.PI / 4) {
4763
+ this.targetYaw -= Math.abs(stepRad);
4764
+ }
4765
+ turnRight(stepRad = Math.PI / 4) {
4766
+ this.targetYaw += Math.abs(stepRad);
4767
+ }
4086
4768
  setFacingDirection(direction) {
4087
4769
  switch (direction) {
4088
4770
  case "left":
@@ -4093,32 +4775,45 @@ var TurnEngine = class {
4093
4775
  break;
4094
4776
  case "center":
4095
4777
  case "forward":
4778
+ case "front":
4096
4779
  default:
4097
4780
  this.targetYaw = 0;
4098
4781
  break;
4099
4782
  }
4100
4783
  }
4784
+ reset() {
4785
+ this.currentYaw = 0;
4786
+ this.targetYaw = 0;
4787
+ this.isTurning = false;
4788
+ this.turnAngularVelocity = 0;
4789
+ this.turnTarget.rotation.y = this.baseYaw;
4790
+ }
4101
4791
  update(delta, isLocomoting = false) {
4102
4792
  const diff = ((this.targetYaw - this.currentYaw) % (Math.PI * 2) + Math.PI * 3) % (Math.PI * 2) - Math.PI;
4103
4793
  this.isTurning = Math.abs(diff) > 0.02;
4104
- const damping = isLocomoting ? 6.5 : 4;
4794
+ const damping = isLocomoting ? 6.5 : 5;
4105
4795
  const prevYaw = this.currentYaw;
4106
4796
  this.currentYaw = ScratchMath.dampAngle(this.currentYaw, this.targetYaw, damping, delta);
4107
4797
  this.turnAngularVelocity = (this.currentYaw - prevYaw) / Math.max(delta, 1e-3);
4108
- this.skeleton.modelRoot.rotation.y = this.currentYaw;
4109
- if (isLocomoting && Math.abs(this.turnAngularVelocity) > 0.2) {
4110
- const bankRoll = -Math.max(-0.06, Math.min(0.06, this.turnAngularVelocity * 0.04));
4111
- const hips = this.skeleton.getJoint("hips");
4112
- if (hips) {
4798
+ this.turnTarget.rotation.y = this.baseYaw + this.currentYaw;
4799
+ if (Math.abs(this.turnAngularVelocity) > 0.15) {
4800
+ const bankRoll = -Math.max(-0.06, Math.min(0.06, this.turnAngularVelocity * (isLocomoting ? 0.04 : 0.02)));
4801
+ if (this.skeleton.hasJoint("hips")) {
4113
4802
  ScratchMath.e0.set(0, 0, bankRoll, "YXZ");
4114
4803
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4115
- hips.targetQuaternion.multiply(ScratchMath.q0);
4804
+ this.skeleton.applyModelDeltaRotation("hips", ScratchMath.q0, 1, true);
4116
4805
  }
4117
4806
  }
4118
4807
  }
4119
4808
  getYaw() {
4120
4809
  return this.currentYaw;
4121
4810
  }
4811
+ getTargetYaw() {
4812
+ return this.targetYaw;
4813
+ }
4814
+ getAngularVelocity() {
4815
+ return this.turnAngularVelocity;
4816
+ }
4122
4817
  isTurnActive() {
4123
4818
  return this.isTurning;
4124
4819
  }
@@ -4134,23 +4829,24 @@ var BalanceEngine = class {
4134
4829
  */
4135
4830
  applyCompensation(reachOffset, weight = 1) {
4136
4831
  if (weight <= 1e-3) return;
4832
+ const localScale = this.skeleton.hipsLocalPerMeter;
4137
4833
  this.targetOffset.set(
4138
- -reachOffset.x * 0.22,
4139
- -Math.abs(reachOffset.z) * 0.05,
4140
- -reachOffset.z * 0.25
4834
+ -reachOffset.x * 0.18 * localScale,
4835
+ -Math.abs(reachOffset.z) * 0.03 * localScale,
4836
+ -reachOffset.z * 0.18 * localScale
4141
4837
  );
4142
4838
  this.centerOfMassOffset.lerp(this.targetOffset, Math.min(1, weight));
4143
4839
  const hips = this.skeleton.getJoint("hips");
4144
4840
  if (hips) {
4145
4841
  hips.targetPosition.add(this.centerOfMassOffset);
4146
4842
  }
4147
- const spine = this.skeleton.getJoint("spine");
4148
- if (spine && this.centerOfMassOffset.lengthSq() > 1e-4) {
4149
- const counterPitch = this.centerOfMassOffset.z * 0.35;
4150
- const counterRoll = -this.centerOfMassOffset.x * 0.35;
4843
+ if (this.skeleton.hasJoint("spine") && this.centerOfMassOffset.lengthSq() > 1e-6) {
4844
+ const invScale = localScale > 1e-4 ? 1 / localScale : 1;
4845
+ const counterPitch = Math.max(-0.12, Math.min(0.12, this.centerOfMassOffset.z * invScale * 0.35));
4846
+ const counterRoll = Math.max(-0.12, Math.min(0.12, -this.centerOfMassOffset.x * invScale * 0.35));
4151
4847
  ScratchMath.e0.set(counterPitch, 0, counterRoll, "YXZ");
4152
4848
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4153
- spine.targetQuaternion.multiply(ScratchMath.q0);
4849
+ this.skeleton.applyModelDeltaRotation("spine", ScratchMath.q0, 1, true);
4154
4850
  }
4155
4851
  }
4156
4852
  reset() {
@@ -4370,177 +5066,146 @@ var GestureEngine = class {
4370
5066
  return "right";
4371
5067
  }
4372
5068
  }
5069
+ /**
5070
+ * Helper: rotates an upper arm from its rest orientation to a target standing-relative Euler pose in model space.
5071
+ */
5072
+ applyStandingArmDelta(side, pitchForwardRad, yawRad, abductOutRad, weight) {
5073
+ const boneName = side === "left" ? "leftUpperArm" : "rightUpperArm";
5074
+ if (!this.skeleton.hasJoint(boneName)) return;
5075
+ const restAngle = side === "left" ? this.skeleton.leftArmRestAngleFromDown : this.skeleton.rightArmRestAngleFromDown;
5076
+ const lowerSign = side === "left" ? this.skeleton.leftArmLowerSign : this.skeleton.rightArmLowerSign;
5077
+ const relaxToDown = Math.max(0, restAngle - abductOutRad);
5078
+ ScratchMath.q1.setFromAxisAngle(ScratchMath.FORWARD, lowerSign * relaxToDown);
5079
+ ScratchMath.e0.set(-pitchForwardRad, yawRad, 0, "YXZ");
5080
+ ScratchMath.q2.setFromEuler(ScratchMath.e0);
5081
+ ScratchMath.q0.copy(ScratchMath.q2).multiply(ScratchMath.q1);
5082
+ this.skeleton.applyModelDeltaRotation(boneName, ScratchMath.q0, weight);
5083
+ }
4373
5084
  // 1. Wave (right hand oscillates back and forth at shoulder height)
4374
5085
  synthesizeWave(progress, weight) {
4375
- const rUpper = this.skeleton.getJoint("rightUpperArm");
4376
- const rLower = this.skeleton.getJoint("rightLowerArm");
4377
- const rHand = this.skeleton.getJoint("rightHand");
4378
- if (rUpper && rLower) {
4379
- ScratchMath.e0.set(-0.6, 0.4, -1.35 * weight, "YXZ");
5086
+ this.applyStandingArmDelta("right", 0.35, -0.25, 1.35, weight);
5087
+ if (this.skeleton.hasJoint("rightLowerArm")) {
5088
+ const waveOsc = Math.sin(progress * Math.PI * 8) * 0.35;
5089
+ ScratchMath.e0.set(-1.35, 0, waveOsc, "YXZ");
4380
5090
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4381
- rUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
4382
- ScratchMath.e0.set(1.4 * weight, 0, 0, "YXZ");
5091
+ this.skeleton.applyModelDeltaRotation("rightLowerArm", ScratchMath.q0, weight);
5092
+ }
5093
+ if (this.skeleton.hasJoint("rightHand")) {
5094
+ const handWave = Math.sin(progress * Math.PI * 8) * 0.3;
5095
+ ScratchMath.e0.set(0, 0, handWave, "YXZ");
4383
5096
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4384
- rLower.targetQuaternion.slerp(ScratchMath.q0, weight);
4385
- if (rHand) {
4386
- const waveAngle = Math.sin(progress * Math.PI * 8) * 0.45 * weight;
4387
- ScratchMath.e0.set(0, 0, waveAngle, "YXZ");
4388
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4389
- rHand.targetQuaternion.slerp(ScratchMath.q0, weight);
4390
- }
5097
+ this.skeleton.applyModelDeltaRotation("rightHand", ScratchMath.q0, weight);
4391
5098
  }
4392
5099
  }
4393
5100
  // 2. Pointing (arm extends toward target using IK or forward angle)
4394
5101
  synthesizePoint(_progress, weight, targetPos) {
4395
5102
  const isLeft = this.activeGesture?.type === "point_left";
4396
- const armName = isLeft ? "leftUpperArm" : "rightUpperArm";
4397
- const foreName = isLeft ? "leftLowerArm" : "rightLowerArm";
5103
+ const side = isLeft ? "left" : "right";
4398
5104
  if (targetPos && this.ik) {
4399
- this.ik.solveArmReach(isLeft ? "left" : "right", targetPos, weight);
5105
+ this.ik.solveArmReach(side, targetPos, weight);
4400
5106
  } else {
4401
- const upper = this.skeleton.getJoint(armName);
4402
- const fore = this.skeleton.getJoint(foreName);
4403
5107
  const sign = isLeft ? 1 : -1;
4404
- if (upper && fore) {
4405
- ScratchMath.e0.set(-1.45 * weight, sign * 0.25 * weight, sign * 0.15 * weight, "YXZ");
4406
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4407
- upper.targetQuaternion.slerp(ScratchMath.q0, weight);
4408
- ScratchMath.e0.set(0.15 * weight, 0, 0, "YXZ");
4409
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4410
- fore.targetQuaternion.slerp(ScratchMath.q0, weight);
5108
+ this.applyStandingArmDelta(side, 1.35, sign * 0.2, 0.25, weight);
5109
+ const foreName = isLeft ? "leftLowerArm" : "rightLowerArm";
5110
+ if (this.skeleton.hasJoint(foreName)) {
5111
+ ScratchMath.q0.setFromAxisAngle(ScratchMath.RIGHT, -0.15);
5112
+ this.skeleton.applyModelDeltaRotation(foreName, ScratchMath.q0, weight);
4411
5113
  }
4412
5114
  }
4413
5115
  }
4414
5116
  // 3. Agree (nod head twice)
4415
5117
  synthesizeAgree(progress, weight) {
4416
- const head = this.skeleton.getJoint("head");
4417
- if (head) {
5118
+ if (this.skeleton.hasJoint("head")) {
4418
5119
  const nodPitch = Math.sin(progress * Math.PI * 4) * 0.24 * weight;
4419
5120
  ScratchMath.e0.set(nodPitch, 0, 0, "YXZ");
4420
5121
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4421
- head.targetQuaternion.copy(head.restQuaternion).multiply(ScratchMath.q0);
5122
+ this.skeleton.applyModelDeltaRotation("head", ScratchMath.q0, weight);
4422
5123
  }
4423
5124
  }
4424
5125
  // 4. Disagree (shake head side to side)
4425
5126
  synthesizeDisagree(progress, weight) {
4426
- const head = this.skeleton.getJoint("head");
4427
- if (head) {
5127
+ if (this.skeleton.hasJoint("head")) {
4428
5128
  const shakeYaw = Math.sin(progress * Math.PI * 4) * 0.32 * weight;
4429
5129
  ScratchMath.e0.set(0, shakeYaw, 0, "YXZ");
4430
5130
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4431
- head.targetQuaternion.copy(head.restQuaternion).multiply(ScratchMath.q0);
5131
+ this.skeleton.applyModelDeltaRotation("head", ScratchMath.q0, weight);
4432
5132
  }
4433
5133
  }
4434
5134
  // 5. Shrug (raise shoulders, turn palms up, tilt head)
4435
5135
  synthesizeShrug(_progress, weight) {
4436
- const lUpper = this.skeleton.getJoint("leftUpperArm");
4437
- const rUpper = this.skeleton.getJoint("rightUpperArm");
4438
- const lFore = this.skeleton.getJoint("leftLowerArm");
4439
- const rFore = this.skeleton.getJoint("rightLowerArm");
4440
- const head = this.skeleton.getJoint("head");
4441
- const lift = 0.28 * weight;
4442
- if (lUpper && rUpper) {
4443
- ScratchMath.e0.set(-0.25 * weight, 0, lift, "YXZ");
4444
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4445
- lUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
4446
- ScratchMath.e0.set(-0.25 * weight, 0, -lift, "YXZ");
5136
+ this.applyStandingArmDelta("left", 0.2, 0, 0.48, weight);
5137
+ this.applyStandingArmDelta("right", 0.2, 0, 0.48, weight);
5138
+ if (this.skeleton.hasJoint("leftLowerArm")) {
5139
+ ScratchMath.e0.set(-0.95, 0.35, 0, "YXZ");
4447
5140
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4448
- rUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
5141
+ this.skeleton.applyModelDeltaRotation("leftLowerArm", ScratchMath.q0, weight);
4449
5142
  }
4450
- if (lFore && rFore) {
4451
- ScratchMath.e0.set(0.85 * weight, 0.4 * weight, 0, "YXZ");
5143
+ if (this.skeleton.hasJoint("rightLowerArm")) {
5144
+ ScratchMath.e0.set(-0.95, -0.35, 0, "YXZ");
4452
5145
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4453
- lFore.targetQuaternion.slerp(ScratchMath.q0, weight);
4454
- ScratchMath.e0.set(0.85 * weight, -0.4 * weight, 0, "YXZ");
4455
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4456
- rFore.targetQuaternion.slerp(ScratchMath.q0, weight);
5146
+ this.skeleton.applyModelDeltaRotation("rightLowerArm", ScratchMath.q0, weight);
4457
5147
  }
4458
- if (head) {
5148
+ if (this.skeleton.hasJoint("head")) {
4459
5149
  ScratchMath.e0.set(0.08 * weight, 0, 0.12 * weight, "YXZ");
4460
5150
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4461
- head.targetQuaternion.copy(head.restQuaternion).multiply(ScratchMath.q0);
5151
+ this.skeleton.applyModelDeltaRotation("head", ScratchMath.q0, weight);
4462
5152
  }
4463
5153
  }
4464
5154
  // 6. Think (hand to chin / temple, look upward slightly)
4465
5155
  synthesizeThink(_progress, weight) {
4466
- const rUpper = this.skeleton.getJoint("rightUpperArm");
4467
- const rFore = this.skeleton.getJoint("rightLowerArm");
4468
- const head = this.skeleton.getJoint("head");
4469
- if (rUpper && rFore) {
4470
- ScratchMath.e0.set(-1.1 * weight, -0.4 * weight, -0.5 * weight, "YXZ");
4471
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4472
- rUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
4473
- ScratchMath.e0.set(1.6 * weight, 0, 0, "YXZ");
5156
+ this.applyStandingArmDelta("right", 0.95, 0.35, 0.35, weight);
5157
+ if (this.skeleton.hasJoint("rightLowerArm")) {
5158
+ ScratchMath.e0.set(-1.55, 0, 0, "YXZ");
4474
5159
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4475
- rFore.targetQuaternion.slerp(ScratchMath.q0, weight);
5160
+ this.skeleton.applyModelDeltaRotation("rightLowerArm", ScratchMath.q0, weight);
4476
5161
  }
4477
- if (head) {
5162
+ if (this.skeleton.hasJoint("head")) {
4478
5163
  ScratchMath.e0.set(-0.15 * weight, 0.18 * weight, 0.08 * weight, "YXZ");
4479
5164
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4480
- head.targetQuaternion.copy(head.restQuaternion).multiply(ScratchMath.q0);
5165
+ this.skeleton.applyModelDeltaRotation("head", ScratchMath.q0, weight);
4481
5166
  }
4482
5167
  }
4483
5168
  // 7. Explain / Conversational gestures (gentle rhythmic hand gesturing)
4484
5169
  synthesizeExplain(progress, weight) {
4485
- const lUpper = this.skeleton.getJoint("leftUpperArm");
4486
- const rUpper = this.skeleton.getJoint("rightUpperArm");
4487
- const lFore = this.skeleton.getJoint("leftLowerArm");
4488
- const rFore = this.skeleton.getJoint("rightLowerArm");
4489
- const osc = Math.sin(progress * Math.PI * 3) * 0.15 * weight;
4490
- if (lUpper && rUpper) {
4491
- ScratchMath.e0.set(-0.35 * weight + osc, 0.25 * weight, 0.2 * weight, "YXZ");
4492
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4493
- lUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
4494
- ScratchMath.e0.set(-0.35 * weight - osc, -0.25 * weight, -0.2 * weight, "YXZ");
4495
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4496
- rUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
5170
+ const osc = Math.sin(progress * Math.PI * 3) * 0.18;
5171
+ this.applyStandingArmDelta("left", 0.35 + osc, 0.2, 0.35, weight);
5172
+ this.applyStandingArmDelta("right", 0.35 - osc, -0.2, 0.35, weight);
5173
+ if (this.skeleton.hasJoint("leftLowerArm")) {
5174
+ ScratchMath.q0.setFromAxisAngle(ScratchMath.RIGHT, -0.9);
5175
+ this.skeleton.applyModelDeltaRotation("leftLowerArm", ScratchMath.q0, weight);
4497
5176
  }
4498
- if (lFore && rFore) {
4499
- ScratchMath.e0.set(0.9 * weight, 0, 0, "YXZ");
4500
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4501
- lFore.targetQuaternion.slerp(ScratchMath.q0, weight);
4502
- ScratchMath.e0.set(0.9 * weight, 0, 0, "YXZ");
4503
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4504
- rFore.targetQuaternion.slerp(ScratchMath.q0, weight);
5177
+ if (this.skeleton.hasJoint("rightLowerArm")) {
5178
+ ScratchMath.q0.setFromAxisAngle(ScratchMath.RIGHT, -0.9);
5179
+ this.skeleton.applyModelDeltaRotation("rightLowerArm", ScratchMath.q0, weight);
4505
5180
  }
4506
5181
  }
4507
5182
  // 8. Open Hands (Welcome / Present / Invite)
4508
5183
  synthesizeOpenHands(_progress, weight) {
4509
- const lUpper = this.skeleton.getJoint("leftUpperArm");
4510
- const rUpper = this.skeleton.getJoint("rightUpperArm");
4511
- const lFore = this.skeleton.getJoint("leftLowerArm");
4512
- const rFore = this.skeleton.getJoint("rightLowerArm");
4513
- if (lUpper && rUpper) {
4514
- ScratchMath.e0.set(-0.45 * weight, 0.35 * weight, 0.45 * weight, "YXZ");
4515
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4516
- lUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
4517
- ScratchMath.e0.set(-0.45 * weight, -0.35 * weight, -0.45 * weight, "YXZ");
5184
+ this.applyStandingArmDelta("left", 0.45, 0.35, 0.55, weight);
5185
+ this.applyStandingArmDelta("right", 0.45, -0.35, 0.55, weight);
5186
+ if (this.skeleton.hasJoint("leftLowerArm")) {
5187
+ ScratchMath.e0.set(-0.75, 0.35, 0, "YXZ");
4518
5188
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4519
- rUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
5189
+ this.skeleton.applyModelDeltaRotation("leftLowerArm", ScratchMath.q0, weight);
4520
5190
  }
4521
- if (lFore && rFore) {
4522
- ScratchMath.e0.set(0.75 * weight, 0.45 * weight, 0, "YXZ");
4523
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4524
- lFore.targetQuaternion.slerp(ScratchMath.q0, weight);
4525
- ScratchMath.e0.set(0.75 * weight, -0.45 * weight, 0, "YXZ");
5191
+ if (this.skeleton.hasJoint("rightLowerArm")) {
5192
+ ScratchMath.e0.set(-0.75, -0.35, 0, "YXZ");
4526
5193
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4527
- rFore.targetQuaternion.slerp(ScratchMath.q0, weight);
5194
+ this.skeleton.applyModelDeltaRotation("rightLowerArm", ScratchMath.q0, weight);
4528
5195
  }
4529
5196
  }
4530
5197
  // 9. Acknowledge (slight bow of head / chest)
4531
5198
  synthesizeAcknowledge(progress, weight) {
4532
- const spine = this.skeleton.getJoint("spine");
4533
- const head = this.skeleton.getJoint("head");
4534
5199
  const bow = Math.sin(progress * Math.PI) * 0.16 * weight;
4535
- if (spine) {
5200
+ if (this.skeleton.hasJoint("spine")) {
4536
5201
  ScratchMath.e0.set(bow, 0, 0, "YXZ");
4537
5202
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4538
- spine.targetQuaternion.copy(spine.restQuaternion).multiply(ScratchMath.q0);
5203
+ this.skeleton.applyModelDeltaRotation("spine", ScratchMath.q0, weight);
4539
5204
  }
4540
- if (head) {
5205
+ if (this.skeleton.hasJoint("head")) {
4541
5206
  ScratchMath.e0.set(bow * 0.5, 0, 0, "YXZ");
4542
5207
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4543
- head.targetQuaternion.copy(head.restQuaternion).multiply(ScratchMath.q0);
5208
+ this.skeleton.applyModelDeltaRotation("head", ScratchMath.q0, weight);
4544
5209
  }
4545
5210
  }
4546
5211
  // 10. Reach
@@ -4551,21 +5216,12 @@ var GestureEngine = class {
4551
5216
  }
4552
5217
  // 11. Celebrate (arms raised in victory, chest open)
4553
5218
  synthesizeCelebrate(_progress, weight) {
4554
- const lUpper = this.skeleton.getJoint("leftUpperArm");
4555
- const rUpper = this.skeleton.getJoint("rightUpperArm");
4556
- const spine = this.skeleton.getJoint("spine");
4557
- if (lUpper && rUpper) {
4558
- ScratchMath.e0.set(-1.8 * weight, 0, 1.2 * weight, "YXZ");
4559
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4560
- lUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
4561
- ScratchMath.e0.set(-1.8 * weight, 0, -1.2 * weight, "YXZ");
4562
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4563
- rUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
4564
- }
4565
- if (spine) {
5219
+ this.applyStandingArmDelta("left", 0.35, 0, 2.45, weight);
5220
+ this.applyStandingArmDelta("right", 0.35, 0, 2.45, weight);
5221
+ if (this.skeleton.hasJoint("spine")) {
4566
5222
  ScratchMath.e0.set(-0.12 * weight, 0, 0, "YXZ");
4567
5223
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4568
- spine.targetQuaternion.copy(spine.restQuaternion).multiply(ScratchMath.q0);
5224
+ this.skeleton.applyModelDeltaRotation("spine", ScratchMath.q0, weight);
4569
5225
  }
4570
5226
  }
4571
5227
  };
@@ -4863,13 +5519,17 @@ var MotionCoordinator = _MotionCoordinator;
4863
5519
 
4864
5520
  // src/avatar/procedural/ProceduralMovementEngine.ts
4865
5521
  var ProceduralMovementEngine = class {
4866
- constructor(modelRoot) {
5522
+ constructor(modelRoot, options) {
4867
5523
  this.isEnabled = true;
4868
- this.skeleton = new AUBRSkeleton(modelRoot);
5524
+ this.paused = false;
5525
+ this.locomotionBlendWeight = 0;
5526
+ this.startingTimer = 0;
5527
+ this.balanceReachScratch = new THREE.Vector3();
5528
+ this.skeleton = new AUBRSkeleton(modelRoot, options);
4869
5529
  this.ik = new IKCoordinator(this.skeleton);
4870
5530
  this.idle = new IdleEngine(this.skeleton);
4871
5531
  this.locomotion = new LocomotionEngine(this.skeleton, this.ik);
4872
- this.turn = new TurnEngine(this.skeleton);
5532
+ this.turn = new TurnEngine(this.skeleton, options?.turnTarget);
4873
5533
  this.balance = new BalanceEngine(this.skeleton);
4874
5534
  this.lookAtEngine = new LookAtEngine(this.skeleton);
4875
5535
  this.gesture = new GestureEngine(this.skeleton, this.ik);
@@ -4880,42 +5540,110 @@ var ProceduralMovementEngine = class {
4880
5540
  getCapabilities() {
4881
5541
  return this.skeleton.capabilities;
4882
5542
  }
5543
+ getState() {
5544
+ return this.stateMachine.getState();
5545
+ }
4883
5546
  setEnabled(enabled) {
4884
5547
  this.isEnabled = enabled;
4885
5548
  }
5549
+ pause() {
5550
+ this.paused = true;
5551
+ }
5552
+ resume() {
5553
+ this.paused = false;
5554
+ }
5555
+ isPaused() {
5556
+ return this.paused;
5557
+ }
5558
+ resetToRestPose() {
5559
+ this.startingTimer = 0;
5560
+ this.locomotionBlendWeight = 0;
5561
+ this.locomotion.cancel();
5562
+ this.gesture.stopGesture();
5563
+ this.idle.reset();
5564
+ this.turn.reset();
5565
+ this.balance.reset();
5566
+ this.lookAtEngine.clearTarget();
5567
+ this.facial.setSpeaking(false);
5568
+ this.facial.setExpression("neutral");
5569
+ this.stateMachine.transitionTo("idle", 0.05);
5570
+ this.coordinator.setWeights({ locomotionWeight: 0, idleWeight: 1, gestureWeight: 0 });
5571
+ this.skeleton.resetToRestPose();
5572
+ this.skeleton.updateWorldMatrices();
5573
+ }
4886
5574
  // --- High-Level Movement API ---
5575
+ startIdle() {
5576
+ const current = this.stateMachine.getState();
5577
+ if (current === "walking" || current === "running" || current === "starting") {
5578
+ this.stopLocomotion();
5579
+ return;
5580
+ }
5581
+ this.startingTimer = 0;
5582
+ this.gesture.stopGesture();
5583
+ this.stateMachine.transitionTo("idle", 0.2);
5584
+ this.coordinator.setWeights({ locomotionWeight: 0, idleWeight: 1, gestureWeight: 0 });
5585
+ }
5586
+ startWalking(speed = 1, screenVelocityPx) {
5587
+ if (!this.skeleton.capabilities.proceduralLocomotion) return;
5588
+ this.startingTimer = 0.18;
5589
+ this.stateMachine.transitionTo("starting", 0.18);
5590
+ this.locomotion.setMotion({ speed, isRunning: false, screenVelocityPx });
5591
+ }
4887
5592
  walk(speed = 1, screenVelocityPx) {
4888
- this.clearStopTimer();
4889
- this.stateMachine.transitionTo("walking");
5593
+ if (!this.skeleton.capabilities.proceduralLocomotion) return;
5594
+ this.startingTimer = 0;
5595
+ this.stateMachine.transitionTo("walking", 0.2);
4890
5596
  this.locomotion.setMotion({ speed, isRunning: false, screenVelocityPx });
4891
- this.coordinator.setWeights({ locomotionWeight: 1, idleWeight: 0 });
4892
5597
  }
4893
5598
  run(speed = 1.8, screenVelocityPx) {
4894
- this.clearStopTimer();
4895
- this.stateMachine.transitionTo("running");
5599
+ if (!this.skeleton.capabilities.proceduralRunning) return;
5600
+ this.startingTimer = 0;
5601
+ this.stateMachine.transitionTo("running", 0.2);
4896
5602
  this.locomotion.setMotion({ speed, isRunning: true, screenVelocityPx });
4897
- this.coordinator.setWeights({ locomotionWeight: 1, idleWeight: 0 });
5603
+ }
5604
+ stop() {
5605
+ this.stopLocomotion();
4898
5606
  }
4899
5607
  stopLocomotion() {
4900
- this.clearStopTimer();
5608
+ this.startingTimer = 0;
4901
5609
  this.locomotion.stop();
4902
- this.stateMachine.transitionTo("stopping", 0.2);
4903
- this.stopTimer = setTimeout(() => {
4904
- this.stopTimer = void 0;
4905
- if (this.stateMachine.getState() === "stopping") {
4906
- this.stateMachine.transitionTo("idle", 0.25);
4907
- this.coordinator.setWeights({ locomotionWeight: 0, idleWeight: 1 });
4908
- }
4909
- }, 200);
4910
- }
4911
- dispose() {
4912
- this.clearStopTimer();
4913
- this.isEnabled = false;
4914
- }
4915
- clearStopTimer() {
4916
- if (this.stopTimer) {
4917
- clearTimeout(this.stopTimer);
4918
- this.stopTimer = void 0;
5610
+ const state = this.stateMachine.getState();
5611
+ if (state === "walking" || state === "running" || state === "starting") {
5612
+ this.stateMachine.transitionTo("stopping", 0.22);
5613
+ } else if (state !== "stopping") {
5614
+ this.stateMachine.transitionTo("idle", 0.2);
5615
+ }
5616
+ }
5617
+ cancelLocomotion() {
5618
+ this.startingTimer = 0;
5619
+ this.locomotionBlendWeight = 0;
5620
+ this.locomotion.cancel();
5621
+ this.coordinator.setWeights({ locomotionWeight: 0, idleWeight: 1 });
5622
+ this.stateMachine.transitionTo("idle", 0.05);
5623
+ }
5624
+ turnLeft(stepRad = Math.PI / 4) {
5625
+ if (!this.skeleton.capabilities.turning) return;
5626
+ this.turn.turnLeft(stepRad);
5627
+ if (this.stateMachine.getState() === "idle") {
5628
+ this.stateMachine.transitionTo("turning", 0.15);
5629
+ }
5630
+ }
5631
+ turnRight(stepRad = Math.PI / 4) {
5632
+ if (!this.skeleton.capabilities.turning) return;
5633
+ this.turn.turnRight(stepRad);
5634
+ if (this.stateMachine.getState() === "idle") {
5635
+ this.stateMachine.transitionTo("turning", 0.15);
5636
+ }
5637
+ }
5638
+ turnTo(directionOrYaw) {
5639
+ if (!this.skeleton.capabilities.turning) return;
5640
+ if (typeof directionOrYaw === "number") {
5641
+ this.turn.setTargetHeading(directionOrYaw);
5642
+ } else {
5643
+ this.turn.setFacingDirection(directionOrYaw);
5644
+ }
5645
+ if (this.stateMachine.getState() === "idle") {
5646
+ this.stateMachine.transitionTo("turning", 0.15);
4919
5647
  }
4920
5648
  }
4921
5649
  setFacing(direction) {
@@ -4924,10 +5652,26 @@ var ProceduralMovementEngine = class {
4924
5652
  setTargetHeading(yawRad) {
4925
5653
  this.turn.setTargetHeading(yawRad);
4926
5654
  }
5655
+ dispose() {
5656
+ this.isEnabled = false;
5657
+ this.paused = false;
5658
+ this.startingTimer = 0;
5659
+ this.locomotionBlendWeight = 0;
5660
+ this.locomotion.cancel();
5661
+ this.gesture.stopGesture();
5662
+ this.balance.reset();
5663
+ this.lookAtEngine.clearTarget();
5664
+ }
4927
5665
  playGesture(type, options) {
5666
+ if (!this.skeleton.capabilities.upperBodyGestures && !this.skeleton.capabilities.headLookAt) {
5667
+ return false;
5668
+ }
4928
5669
  const success = this.gesture.playGesture(type, options);
4929
5670
  if (success) {
4930
- this.stateMachine.transitionTo("gesturing");
5671
+ const current = this.stateMachine.getState();
5672
+ if (current === "idle" || current === "speaking" || current === "listening" || current === "thinking") {
5673
+ this.stateMachine.transitionTo("gesturing");
5674
+ }
4931
5675
  this.coordinator.setWeights({ gestureWeight: 1 });
4932
5676
  }
4933
5677
  return success;
@@ -4965,41 +5709,83 @@ var ProceduralMovementEngine = class {
4965
5709
  * Restores bones to reference bind pose to prevent cumulative transform drift.
4966
5710
  */
4967
5711
  preMixerUpdate() {
4968
- if (!this.isEnabled) return;
5712
+ if (!this.isEnabled || this.paused) return;
4969
5713
  this.coordinator.preMixerRestore();
4970
5714
  }
4971
5715
  /**
4972
5716
  * Main procedural pipeline tick.
4973
- * Invoked in FbxRenderer.startLoop() after mixer.update(delta) and before renderer.render().
5717
+ * Invoked in FbxRenderer.startLoop() or Avatar Studio after mixer.update(delta) and before renderer.render().
4974
5718
  */
4975
- update(delta, hasActiveMixerClip) {
4976
- if (!this.isEnabled) return;
5719
+ update(delta, hasActiveMixerClip = false) {
5720
+ if (!this.isEnabled || this.paused) return;
5721
+ const dt = Math.min(Math.max(delta, 0), 0.1);
4977
5722
  if (hasActiveMixerClip) {
4978
5723
  this.coordinator.snapshotMixerOutput();
4979
5724
  this.coordinator.setWeights({ clipWeight: 1 });
4980
5725
  } else {
4981
5726
  this.coordinator.setWeights({ clipWeight: 0 });
4982
5727
  }
4983
- const currentState = this.stateMachine.getState();
5728
+ this.stateMachine.update(dt);
5729
+ let currentState = this.stateMachine.getState();
5730
+ if (currentState === "starting") {
5731
+ this.startingTimer -= dt;
5732
+ if (this.startingTimer <= 0) {
5733
+ this.stateMachine.transitionTo("walking", 0.2);
5734
+ currentState = this.stateMachine.getState();
5735
+ }
5736
+ }
4984
5737
  const isLocomoting = currentState === "walking" || currentState === "running" || currentState === "starting";
4985
- this.stateMachine.update(delta);
4986
- this.turn.update(delta, isLocomoting);
4987
- const locoWeight = isLocomoting ? 1 : this.coordinator.getWeights().locomotionWeight;
4988
- if (locoWeight > 0.01) {
4989
- this.locomotion.update(delta, locoWeight);
5738
+ const targetLocoWeight = isLocomoting ? 1 : 0;
5739
+ const blendRate = isLocomoting ? 7.5 : 8.5;
5740
+ this.locomotionBlendWeight = ScratchMath.damp(
5741
+ this.locomotionBlendWeight,
5742
+ targetLocoWeight,
5743
+ blendRate,
5744
+ dt
5745
+ );
5746
+ if (this.locomotionBlendWeight < 5e-3 && !isLocomoting) {
5747
+ this.locomotionBlendWeight = 0;
5748
+ }
5749
+ if (currentState === "stopping" && this.locomotionBlendWeight < 0.02 && this.locomotion.getSpeed() < 0.05) {
5750
+ this.locomotionBlendWeight = 0;
5751
+ this.stateMachine.transitionTo("idle", 0.15);
5752
+ currentState = "idle";
5753
+ }
5754
+ const locoWeight = this.locomotionBlendWeight;
5755
+ const idleWeight = Math.max(0, 1 - locoWeight);
5756
+ this.coordinator.setWeights({
5757
+ locomotionWeight: locoWeight,
5758
+ idleWeight
5759
+ });
5760
+ if (idleWeight > 5e-3 && this.skeleton.capabilities.proceduralIdle) {
5761
+ this.idle.update(dt, idleWeight);
4990
5762
  }
4991
- const idleWeight = !isLocomoting ? 1 : this.coordinator.getWeights().idleWeight;
4992
- if (idleWeight > 0.01) {
4993
- this.idle.update(delta, idleWeight);
5763
+ if (locoWeight > 5e-3 && this.skeleton.capabilities.proceduralLocomotion) {
5764
+ this.locomotion.update(dt, locoWeight);
5765
+ }
5766
+ if (this.skeleton.capabilities.turning) {
5767
+ this.turn.update(dt, isLocomoting);
5768
+ if (currentState === "turning" && !this.turn.isTurnActive()) {
5769
+ this.stateMachine.transitionTo("idle", 0.15);
5770
+ }
4994
5771
  }
4995
5772
  if (this.gesture.isGestureActive()) {
4996
- this.gesture.update(delta);
5773
+ this.gesture.update(dt);
4997
5774
  this.coordinator.setWeights({ gestureWeight: 1 });
5775
+ this.balanceReachScratch.set(0, 0, 0.15);
5776
+ this.balance.applyCompensation(this.balanceReachScratch, Math.min(1, dt * 6));
4998
5777
  } else {
4999
5778
  this.coordinator.setWeights({ gestureWeight: 0 });
5779
+ if (this.stateMachine.getState() === "gesturing") {
5780
+ this.stateMachine.transitionTo("idle", 0.2);
5781
+ }
5782
+ this.balanceReachScratch.set(0, 0, 0);
5783
+ this.balance.applyCompensation(this.balanceReachScratch, Math.min(1, dt * 6));
5000
5784
  }
5001
- this.lookAtEngine.update(delta, 1);
5002
- this.facial.update(delta);
5785
+ if (this.skeleton.capabilities.headLookAt) {
5786
+ this.lookAtEngine.update(dt, 1);
5787
+ }
5788
+ this.facial.update(dt);
5003
5789
  this.coordinator.blendLayers(hasActiveMixerClip);
5004
5790
  this.skeleton.apply();
5005
5791
  this.skeleton.updateWorldMatrices();
@@ -5037,16 +5823,21 @@ var FbxRenderer = class {
5037
5823
  if (!doc) {
5038
5824
  throw new Error("Unable to access document DOM for 3D avatar viewport");
5039
5825
  }
5826
+ const probeCanvas = doc.createElement("canvas");
5827
+ const glContext = probeCanvas.getContext("webgl2") || probeCanvas.getContext("webgl");
5828
+ if (!glContext) {
5829
+ throw new AsiystError({
5830
+ code: "WEBGL_UNAVAILABLE",
5831
+ message: "WebGLRenderingContext is not available or supported in this browser environment",
5832
+ hint: "Enable hardware acceleration in your browser or use a WebGL-capable device."
5833
+ });
5834
+ }
5040
5835
  this.canvas = doc.createElement("canvas");
5041
5836
  this.canvas.className = "asiyst-avatar-canvas";
5042
5837
  this.canvas.setAttribute("role", "presentation");
5043
5838
  this.canvas.style.opacity = "0";
5044
5839
  this.canvas.style.transition = "opacity 0.25s ease";
5045
5840
  this.canvas.style.background = "transparent";
5046
- const glContext = this.canvas.getContext("webgl2") || this.canvas.getContext("webgl");
5047
- if (!glContext) {
5048
- throw new Error("WebGLRenderingContext is not available or supported in this browser environment");
5049
- }
5050
5841
  const isMobile = typeof window !== "undefined" && window.innerWidth <= 640;
5051
5842
  const width = options?.width || (isMobile ? 140 : 190);
5052
5843
  const height = options?.height || (isMobile ? 280 : 360);
@@ -5131,7 +5922,12 @@ var FbxRenderer = class {
5131
5922
  modelAnimations = parsedGroup.animations || [];
5132
5923
  } catch (parseErr) {
5133
5924
  const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);
5134
- throw new Error(`FBX decoding and parsing failed: ${msg}`);
5925
+ throw new AsiystError({
5926
+ code: "INCOMPATIBLE_FBX",
5927
+ message: `FBX decoding and parsing failed: ${msg}`,
5928
+ hint: "Ensure the character FBX uses a supported binary (7.0+) or ASCII format and valid humanoid mesh data.",
5929
+ cause: parseErr
5930
+ });
5135
5931
  }
5136
5932
  } else {
5137
5933
  const loader = new GLTFLoader();
@@ -5144,13 +5940,21 @@ var FbxRenderer = class {
5144
5940
  modelAnimations = gltf.animations || [];
5145
5941
  } catch (parseErr) {
5146
5942
  const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);
5147
- throw new Error(`GLB decoding and parsing failed: ${msg}`);
5943
+ throw new AsiystError({
5944
+ code: "INVALID_ASSET_RESPONSE",
5945
+ message: `GLB decoding and parsing failed: ${msg}`,
5946
+ cause: parseErr
5947
+ });
5148
5948
  }
5149
5949
  }
5150
5950
  const { meshCount, vertexCount: totalVertices } = this.validateGeometry(rawObject);
5151
5951
  const rawBox = new THREE.Box3().setFromObject(rawObject);
5152
5952
  if (rawBox.isEmpty()) {
5153
- throw new Error("FBX asset geometry bounding box is empty");
5953
+ throw new AsiystError({
5954
+ code: "INCOMPATIBLE_FBX",
5955
+ message: "FBX asset geometry bounding box is empty",
5956
+ hint: "Export the character mesh along with the skeleton armature in your FBX file."
5957
+ });
5154
5958
  }
5155
5959
  const rawSize = rawBox.getSize(new THREE.Vector3());
5156
5960
  const rawCenter = rawBox.getCenter(new THREE.Vector3());
@@ -5186,7 +5990,10 @@ var FbxRenderer = class {
5186
5990
  });
5187
5991
  this.allAnimations = [...modelAnimations];
5188
5992
  try {
5189
- this.proceduralEngine = new ProceduralMovementEngine(rawObject);
5993
+ this.proceduralEngine = new ProceduralMovementEngine(rawObject, {
5994
+ embeddedAnimationCount: modelAnimations.length,
5995
+ turnTarget: this.modelRoot
5996
+ });
5190
5997
  } catch (procErr) {
5191
5998
  if (typeof console !== "undefined" && typeof console.warn === "function") {
5192
5999
  console.warn("[asiyst] Procedural movement engine initialization notice:", procErr);
@@ -5338,6 +6145,16 @@ var FbxRenderer = class {
5338
6145
  }
5339
6146
  async loadExternalAnimations(animations, targetAnimationName) {
5340
6147
  if (!this.rawObject || !this.mixer) return;
6148
+ for (const anim of animations) {
6149
+ const url = anim.assetUrl || anim.downloadUrl || anim.url;
6150
+ if (!url) {
6151
+ this.failedAnimations.set(anim.id || anim.name, {
6152
+ error: `Animation "${anim.name}" is missing an animation file URL`,
6153
+ code: "MISSING_ANIMATION_FILE",
6154
+ id: anim.id
6155
+ });
6156
+ }
6157
+ }
5341
6158
  const pending = animations.filter(
5342
6159
  (anim) => {
5343
6160
  const url = anim.assetUrl || anim.downloadUrl || anim.url;
@@ -5353,7 +6170,11 @@ var FbxRenderer = class {
5353
6170
  await Promise.allSettled(
5354
6171
  pending.map(async (anim) => {
5355
6172
  try {
5356
- const loaded = await this.assetLoader.load(anim.assetUrl, { integrity: anim.integrity });
6173
+ const loaded = await this.assetLoader.load(anim.assetUrl, {
6174
+ integrity: anim.integrity,
6175
+ isAnimation: true,
6176
+ assetName: anim.name
6177
+ });
5357
6178
  let extractedClips = [];
5358
6179
  if (loaded.format === "fbx") {
5359
6180
  const loader = new FBXLoader();
@@ -5391,18 +6212,25 @@ var FbxRenderer = class {
5391
6212
  clip: retargeted
5392
6213
  });
5393
6214
  }
5394
- if (!anyExtracted && extractedClips.length > 0) {
6215
+ if (extractedClips.length === 0) {
6216
+ this.failedAnimations.set(anim.id || anim.name, {
6217
+ error: `Animation file "${anim.name}" contains no animation clips`,
6218
+ code: "INCOMPATIBLE_FBX",
6219
+ id: anim.id
6220
+ });
6221
+ } else if (!anyExtracted) {
5395
6222
  this.failedAnimations.set(anim.id || anim.name, {
5396
6223
  error: `Animation "${anim.name}" contains no compatible skeleton bone tracks`,
5397
- code: "INCOMPATIBLE_SKELETON",
6224
+ code: "INCOMPATIBLE_FBX",
5398
6225
  id: anim.id
5399
6226
  });
5400
6227
  }
5401
6228
  } catch (err) {
5402
6229
  const msg = err instanceof Error ? err.message : String(err);
6230
+ const errCode = err instanceof AsiystError ? String(err.code) : "MISSING_ANIMATION_FILE";
5403
6231
  this.failedAnimations.set(anim.id || anim.name, {
5404
6232
  error: msg,
5405
- code: "LOAD_FAILED",
6233
+ code: errCode,
5406
6234
  id: anim.id
5407
6235
  });
5408
6236
  if (typeof console !== "undefined" && typeof console.warn === "function") {
@@ -5704,7 +6532,11 @@ var FbxRenderer = class {
5704
6532
  }
5705
6533
  });
5706
6534
  if (meshCount === 0 || totalVertices === 0) {
5707
- throw new Error("FBX asset contains no drawable 3D geometry");
6535
+ throw new AsiystError({
6536
+ code: "INCOMPATIBLE_FBX",
6537
+ message: "FBX asset contains no drawable 3D geometry",
6538
+ hint: "Ensure the FBX file exports the character mesh geometry, not just animation bones."
6539
+ });
5708
6540
  }
5709
6541
  return { meshCount, vertexCount: totalVertices };
5710
6542
  }
@@ -5752,6 +6584,34 @@ var FbxRenderer = class {
5752
6584
  this.mixer = null;
5753
6585
  }
5754
6586
  if (this.scene) {
6587
+ const disposedTextures = /* @__PURE__ */ new Set();
6588
+ const TEXTURE_SLOTS = [
6589
+ "map",
6590
+ "normalMap",
6591
+ "roughnessMap",
6592
+ "metalnessMap",
6593
+ "aoMap",
6594
+ "emissiveMap",
6595
+ "alphaMap",
6596
+ "bumpMap",
6597
+ "displacementMap",
6598
+ "lightMap",
6599
+ "envMap"
6600
+ ];
6601
+ const disposeMat = (m) => {
6602
+ const matRecord = m;
6603
+ for (const slot of TEXTURE_SLOTS) {
6604
+ const texCandidate = matRecord[slot];
6605
+ if (texCandidate && typeof texCandidate === "object" && texCandidate.isTexture) {
6606
+ const tex = texCandidate;
6607
+ if (!disposedTextures.has(tex)) {
6608
+ disposedTextures.add(tex);
6609
+ tex.dispose();
6610
+ }
6611
+ }
6612
+ }
6613
+ m.dispose();
6614
+ };
5755
6615
  this.scene.traverse((obj) => {
5756
6616
  const mesh = obj;
5757
6617
  if (mesh.isMesh) {
@@ -5761,14 +6621,12 @@ var FbxRenderer = class {
5761
6621
  if (mesh.material) {
5762
6622
  if (Array.isArray(mesh.material)) {
5763
6623
  mesh.material.forEach((m) => {
5764
- const mat = m;
5765
- mat.map?.dispose();
5766
- mat.dispose();
6624
+ if (m && typeof m.dispose === "function") {
6625
+ disposeMat(m);
6626
+ }
5767
6627
  });
5768
- } else {
5769
- const mat = mesh.material;
5770
- mat.map?.dispose();
5771
- mat.dispose();
6628
+ } else if (mesh.material && typeof mesh.material.dispose === "function") {
6629
+ disposeMat(mesh.material);
5772
6630
  }
5773
6631
  }
5774
6632
  }
@@ -6401,6 +7259,7 @@ var CssAvatarRenderer = class {
6401
7259
  } catch (err) {
6402
7260
  const errorObj = err instanceof Error ? err : new Error(String(err));
6403
7261
  this.lastErrorMessage = errorObj.message;
7262
+ this.lastErrorObj = errorObj;
6404
7263
  this.renderState = "error";
6405
7264
  this.isAssetLoadedFlag = false;
6406
7265
  this.isFallbackFlag = true;
@@ -6763,6 +7622,12 @@ var CssAvatarRenderer = class {
6763
7622
  getLastError() {
6764
7623
  return this.lastErrorMessage;
6765
7624
  }
7625
+ getLastErrorObject() {
7626
+ return this.lastErrorObj;
7627
+ }
7628
+ getFailedAnimations() {
7629
+ return this.fbxRenderer?.getFailedAnimations() ?? [];
7630
+ }
6766
7631
  getMetrics() {
6767
7632
  return this.renderMetrics;
6768
7633
  }
@@ -7077,6 +7942,8 @@ var MovementEngine = class {
7077
7942
  faceDirection(direction) {
7078
7943
  if (direction === "left" || direction === "right") {
7079
7944
  this.renderer.setFacing(direction);
7945
+ } else if (typeof this.renderer.setFacing === "function") {
7946
+ this.renderer.setFacing(direction);
7080
7947
  }
7081
7948
  }
7082
7949
  viewport() {
@@ -7852,13 +8719,6 @@ var ConversationPanel = class {
7852
8719
  };
7853
8720
 
7854
8721
  // src/core/isolate.ts
7855
- async function isolateAsync(fn, fallback) {
7856
- try {
7857
- return await fn();
7858
- } catch {
7859
- return fallback;
7860
- }
7861
- }
7862
8722
  function withIsolation(fn) {
7863
8723
  try {
7864
8724
  fn();
@@ -7949,6 +8809,13 @@ var RuntimeAuth = class {
7949
8809
  let response;
7950
8810
  try {
7951
8811
  const baseUrl = this.options.apiBaseUrl.replace(/\/$/, "");
8812
+ const tokenUrl = new URL(contractApiUrl(baseUrl, API_ROUTES.runtimeToken));
8813
+ if (this.options.projectId) {
8814
+ tokenUrl.searchParams.set("projectId", this.options.projectId);
8815
+ }
8816
+ if (this.options.publicKey) {
8817
+ tokenUrl.searchParams.set("publicKey", this.options.publicKey);
8818
+ }
7952
8819
  const payload = JSON.stringify({
7953
8820
  projectId: this.options.projectId,
7954
8821
  publicKey: this.options.publicKey,
@@ -7965,11 +8832,14 @@ var RuntimeAuth = class {
7965
8832
  "assistant:events"
7966
8833
  ]
7967
8834
  });
7968
- response = await fetch(contractApiUrl(baseUrl, API_ROUTES.runtimeToken), {
8835
+ response = await fetch(tokenUrl.toString(), {
7969
8836
  method: "POST",
7970
8837
  headers: {
7971
8838
  Accept: "application/json",
7972
- "Content-Type": "application/json"
8839
+ "Content-Type": "application/json",
8840
+ "X-Asiyst-Project-Id": this.options.projectId,
8841
+ "X-Asiyst-Public-Key": this.options.publicKey,
8842
+ "X-Asiyst-Project-Key": this.options.publicKey
7973
8843
  },
7974
8844
  body: payload,
7975
8845
  signal: controller.signal
@@ -9690,12 +10560,20 @@ var ActionScheduler = class {
9690
10560
  ctx.events.emit("action_started", { actionId: action.id, actionType: action.type });
9691
10561
  try {
9692
10562
  const timeoutMs = typeof action.expirationMs === "number" && action.expirationMs > 0 ? action.expirationMs : 15e3;
9693
- const result = await Promise.race([
9694
- handler(ctx),
9695
- new Promise(
9696
- (_, reject) => setTimeout(() => reject(new Error(`Action ${action.type} timed out after ${timeoutMs}ms`)), timeoutMs)
9697
- )
9698
- ]);
10563
+ let timerId;
10564
+ const timeoutPromise = new Promise((_, reject) => {
10565
+ timerId = setTimeout(() => {
10566
+ reject(new Error(`Action ${action.type} timed out after ${timeoutMs}ms`));
10567
+ }, timeoutMs);
10568
+ });
10569
+ let result;
10570
+ try {
10571
+ result = await Promise.race([handler(ctx), timeoutPromise]);
10572
+ } finally {
10573
+ if (timerId !== void 0) {
10574
+ clearTimeout(timerId);
10575
+ }
10576
+ }
9699
10577
  const durationMs = Date.now() - startTime;
9700
10578
  const ackResult = {
9701
10579
  executionDurationMs: durationMs,
@@ -10343,7 +11221,7 @@ var AsiystRuntime = class {
10343
11221
  apiBaseUrl: options.apiBaseUrl ?? DEFAULT_API_BASE_URL,
10344
11222
  projectId: options.projectId,
10345
11223
  publicKey: options.publicKey,
10346
- installationId: void 0,
11224
+ installationId: this.installationId,
10347
11225
  origin: win.location.origin,
10348
11226
  environment: this.environment
10349
11227
  }) : void 0;
@@ -10425,36 +11303,47 @@ var AsiystRuntime = class {
10425
11303
  (event) => this.cloud.sendRuntimeEvent(event),
10426
11304
  this.events
10427
11305
  );
10428
- this.tourEngine = new TourEngine(
10429
- async (route) => {
11306
+ this.tourEngine = new TourEngine({
11307
+ navigateToRoute: async (route) => {
10430
11308
  const nav = resolveNavigationAdapter(win);
10431
11309
  await nav.navigateToRoute(route);
10432
11310
  },
10433
- async (elId) => {
11311
+ moveToElement: async (elId) => {
10434
11312
  await this.movement.moveTo(elId, "developer");
10435
11313
  },
10436
- async (elId) => {
11314
+ pointAtElement: async (elId) => {
10437
11315
  await this.movement.pointAt(elId, "developer");
10438
11316
  },
10439
- async (elId, style) => {
10440
- const el = this.targetRegistry.get(elId);
10441
- if (el) {
10442
- this.highlights.show(el, style || "spotlight");
11317
+ highlightElement: async (elId, style) => {
11318
+ const resolved = this.resolver.tryResolve(elId, "developer");
11319
+ if (resolved) {
11320
+ this.highlights.show(resolved.element, style || "spotlight");
11321
+ } else {
11322
+ const el = this.targetRegistry.get(elId);
11323
+ if (el) {
11324
+ this.highlights.show(el, style || "spotlight");
11325
+ }
10443
11326
  }
10444
11327
  },
10445
- async (text) => {
11328
+ clearHighlight: () => {
11329
+ this.highlights.hide();
11330
+ },
11331
+ speak: async (text) => {
10446
11332
  await this.speechPlayer.speak(text);
10447
11333
  },
10448
- (event) => {
11334
+ playGesture: (gesture) => {
11335
+ return this.avatar.playGesture(gesture);
11336
+ },
11337
+ onStepChanged: (event) => {
10449
11338
  this.events.emit("asiyst:tour:step_changed", event);
10450
11339
  },
10451
- (tourId) => {
11340
+ onTourCompleted: (tourId) => {
10452
11341
  this.events.emit("asiyst:tour:completed", { tourId });
10453
11342
  },
10454
- (tourId, error) => {
11343
+ onTourError: (tourId, error) => {
10455
11344
  this.events.emit("asiyst:tour:error", { tourId, error });
10456
11345
  }
10457
- );
11346
+ });
10458
11347
  this.actionScheduler = new ActionScheduler(
10459
11348
  (action) => this.createActionContext(action, doc, win)
10460
11349
  );
@@ -10590,19 +11479,48 @@ var AsiystRuntime = class {
10590
11479
  }
10591
11480
  this.setState("fetching-config");
10592
11481
  let cfg;
11482
+ let configFailedWithError;
10593
11483
  try {
10594
- cfg = await isolateAsync(() => this.config.refresh(), this.config.get());
11484
+ cfg = await this.config.refresh();
10595
11485
  this.metricsTracker.record("configRetrieved");
10596
11486
  } catch (configErr) {
10597
- const asiystErr = new AsiystError({
10598
- code: "CONFIG_INVALID",
11487
+ const preservedCode = configErr instanceof AsiystError && configErr.code && configErr.code !== "configuration_error" && configErr.code !== "network_error" && configErr.code !== "authentication_error" ? configErr.code : configErr instanceof AuthenticationError ? "UNAUTHORIZED" : "CONFIG_INVALID";
11488
+ const asiystErr = configErr instanceof AsiystError && preservedCode === configErr.code ? configErr : new AsiystError({
11489
+ code: preservedCode,
10599
11490
  message: configErr instanceof Error ? configErr.message : "Failed to load project configuration.",
11491
+ hint: configErr instanceof AsiystError ? configErr.hint : void 0,
11492
+ status: configErr instanceof AsiystError ? configErr.status : void 0,
10600
11493
  cause: configErr
10601
11494
  });
11495
+ configFailedWithError = asiystErr;
10602
11496
  this.recordError(asiystErr);
11497
+ this.events.emit("asiyst:avatar:error", {
11498
+ avatarId: this.options.avatarId,
11499
+ error: asiystErr.message,
11500
+ stage: "metadata_retrieval"
11501
+ });
10603
11502
  this.events.emit("error", asiystErr);
10604
11503
  cfg = this.config.get();
10605
11504
  }
11505
+ if (configFailedWithError) {
11506
+ const fatalConfigCodes = /* @__PURE__ */ new Set([
11507
+ "AVATAR_NOT_FOUND",
11508
+ "AVATAR_NOT_IMPORTED",
11509
+ "PROJECT_MISMATCH",
11510
+ "UNAUTHORIZED",
11511
+ "DOMAIN_NOT_APPROVED",
11512
+ "ORIGIN_NOT_APPROVED",
11513
+ "MISSING_CHARACTER_FILE"
11514
+ ]);
11515
+ if (this.options.avatarId || fatalConfigCodes.has(String(configFailedWithError.code))) {
11516
+ this.renderer.renderErrorState(configFailedWithError, this.options.fallback);
11517
+ this.avatar.show();
11518
+ this.movement.goToAnchor();
11519
+ this.setAvatarLifecycleState("error");
11520
+ this.setState("error", { reason: "avatar_config_failed", code: configFailedWithError.code });
11521
+ return;
11522
+ }
11523
+ }
10606
11524
  const domainCheck = validateWebsiteDomain(cfg, window.location.href);
10607
11525
  if (!domainCheck.allowed) {
10608
11526
  this.connectionStatus = "disconnected";
@@ -10641,6 +11559,23 @@ var AsiystRuntime = class {
10641
11559
  this.avatar.show();
10642
11560
  this.movement.goToAnchor();
10643
11561
  }
11562
+ } else if (this.options.avatarId || cfg.avatarId) {
11563
+ const missingCharErr = new AsiystError({
11564
+ code: "MISSING_CHARACTER_FILE",
11565
+ message: `Avatar "${this.options.avatarId ?? cfg.avatarId}" is missing a character 3D model file (FBX/GLB).`,
11566
+ hint: "Upload and publish a valid character FBX or GLB in Avatar Studio."
11567
+ });
11568
+ this.recordError(missingCharErr);
11569
+ this.renderer.renderErrorState(missingCharErr, this.options.fallback);
11570
+ this.avatar.show();
11571
+ this.movement.goToAnchor();
11572
+ this.events.emit("asiyst:avatar:error", {
11573
+ avatarId: this.options.avatarId ?? cfg.avatarId,
11574
+ error: missingCharErr.message,
11575
+ stage: "asset_url_resolution"
11576
+ });
11577
+ this.events.emit("error", missingCharErr);
11578
+ avatarLoadedSuccessfully = false;
10644
11579
  } else {
10645
11580
  this.avatar.show();
10646
11581
  this.movement.goToAnchor();
@@ -10695,6 +11630,17 @@ var AsiystRuntime = class {
10695
11630
  const format = this.renderer.getLoadedFormat();
10696
11631
  const assetUrl = this.renderer.getAssetUrl();
10697
11632
  const isRendered = this.renderer.isRendered();
11633
+ const failedAnims = this.renderer.getFailedAnimations();
11634
+ for (const failedAnim of failedAnims) {
11635
+ this.recordError({
11636
+ code: failedAnim.code ?? "MISSING_ANIMATION_FILE",
11637
+ message: failedAnim.error
11638
+ });
11639
+ this.events.emit("asiyst:animation:error", {
11640
+ name: failedAnim.name,
11641
+ error: failedAnim.error
11642
+ });
11643
+ }
10698
11644
  this.events.emit("asiyst:avatar:loaded", {
10699
11645
  avatarId: this.options.avatarId ?? cfg.avatarId,
10700
11646
  assetUrl,
@@ -10711,16 +11657,25 @@ var AsiystRuntime = class {
10711
11657
  }
10712
11658
  return true;
10713
11659
  } else {
11660
+ const lastErrObj = this.renderer.getLastErrorObject();
10714
11661
  const err = this.renderer.getLastError() ?? "Avatar asset loading failed";
11662
+ const errCode = lastErrObj instanceof AsiystError && lastErrObj.code ? String(lastErrObj.code) : "AVATAR_LOAD_FAILED";
11663
+ const errHint = lastErrObj instanceof AsiystError ? lastErrObj.hint : void 0;
10715
11664
  this.recordError({
10716
- code: "AVATAR_LOAD_FAILED",
10717
- message: err
11665
+ code: errCode,
11666
+ message: err,
11667
+ hint: errHint
10718
11668
  });
10719
11669
  this.events.emit("asiyst:avatar:error", {
10720
11670
  avatarId: this.options.avatarId ?? cfg.avatarId,
10721
11671
  error: err,
10722
11672
  stage: "renderer_init"
10723
11673
  });
11674
+ this.events.emit("error", {
11675
+ code: errCode,
11676
+ message: err,
11677
+ hint: errHint
11678
+ });
10724
11679
  return false;
10725
11680
  }
10726
11681
  } catch (error) {
@@ -10740,7 +11695,7 @@ var AsiystRuntime = class {
10740
11695
  }
10741
11696
  this.configRevalidationTimer = setInterval(() => {
10742
11697
  if (!this.destroyed) {
10743
- void this.config.refresh();
11698
+ void this.config.refresh({ silent: true });
10744
11699
  }
10745
11700
  }, CONFIG_REVALIDATION_INTERVAL_MS);
10746
11701
  }
@@ -10874,12 +11829,28 @@ var AsiystRuntime = class {
10874
11829
  };
10875
11830
  }
10876
11831
  const cfg = this.config.get();
10877
- const runtimeConfig = {
11832
+ const configError = this.errorsObserved.find(
11833
+ (e) => [
11834
+ "CONFIG_INVALID",
11835
+ "AVATAR_NOT_FOUND",
11836
+ "AVATAR_NOT_IMPORTED",
11837
+ "PROJECT_MISMATCH",
11838
+ "CORS_OR_NETWORK_FAILURE"
11839
+ ].includes(e.code)
11840
+ );
11841
+ const runtimeConfig = configError ? {
11842
+ ok: false,
11843
+ code: configError.code,
11844
+ message: configError.message
11845
+ } : {
10878
11846
  ok: Boolean(cfg && cfg.version !== void 0),
10879
11847
  status: cfg ? 200 : void 0,
10880
11848
  message: cfg ? "Runtime configuration loaded" : "Runtime configuration unavailable"
10881
11849
  };
10882
11850
  const avatarId = this.options.avatarId ?? cfg.avatarId ?? "default";
11851
+ const failedAnimSet = new Set(
11852
+ this.renderer.getFailedAnimations().map((f) => (f.id || f.name).toLowerCase())
11853
+ );
10883
11854
  const assets = [];
10884
11855
  if (cfg.assetUrl) {
10885
11856
  assets.push({
@@ -10890,10 +11861,12 @@ var AsiystRuntime = class {
10890
11861
  }
10891
11862
  if (cfg.animations && Array.isArray(cfg.animations)) {
10892
11863
  for (const anim of cfg.animations) {
11864
+ const animKey = (anim.id || anim.name || "").toLowerCase();
11865
+ const animFailed = failedAnimSet.has(animKey) || !(anim.assetUrl || anim.downloadUrl);
10893
11866
  assets.push({
10894
11867
  name: anim.name || anim.assetUrl || "animation",
10895
- format: "fbx",
10896
- loaded: this.renderer.isAssetLoaded()
11868
+ format: anim.format || "fbx",
11869
+ loaded: this.renderer.isAssetLoaded() && !animFailed
10897
11870
  });
10898
11871
  }
10899
11872
  }
@@ -11146,8 +12119,8 @@ var AsiystRuntime = class {
11146
12119
  origin
11147
12120
  });
11148
12121
  if (reg?.runtimeSessionId) {
11149
- this.installationId = reg.runtimeSessionId;
11150
- this.runtimeAuth?.setInstallationId(reg.runtimeSessionId);
12122
+ this.visitorSessionId = reg.runtimeSessionId;
12123
+ this.cloud.setSessionId(reg.runtimeSessionId);
11151
12124
  this.registrationSucceeded = true;
11152
12125
  this.connectionStatus = "connected";
11153
12126
  this.verificationStatus = "connected";
@@ -11331,17 +12304,11 @@ var AsiystRuntime = class {
11331
12304
  async avatarSubmitContext() {
11332
12305
  await this.submitWebsiteContext();
11333
12306
  }
11334
- async avatarHighlight(targetId, style) {
11335
- const el = this.targetRegistry.get(targetId);
11336
- if (el) {
11337
- this.highlights.show(el, style ?? "outline");
11338
- }
12307
+ async avatarHighlight(target, style) {
12308
+ await this.avatar.highlight(target, style ?? "outline", "developer");
11339
12309
  }
11340
- async avatarPointAt(targetId) {
11341
- const el = this.targetRegistry.get(targetId);
11342
- if (el) {
11343
- await this.avatar.pointAt(targetId, "developer");
11344
- }
12310
+ async avatarPointAt(target) {
12311
+ await this.avatar.pointAt(target, "developer");
11345
12312
  }
11346
12313
  async avatarNavigateTo(route) {
11347
12314
  const win = this.host?.chrome?.ownerDocument?.defaultView || (typeof window !== "undefined" ? window : void 0);
@@ -11478,15 +12445,10 @@ var AsiystInstanceImpl = class {
11478
12445
  interact: {
11479
12446
  highlight: async (targetId, options) => {
11480
12447
  const style = typeof options === "string" ? options : options?.style;
11481
- await this.requireInstanceRuntime().avatarHighlight(
11482
- typeof targetId === "string" ? targetId : targetId.id || "",
11483
- style
11484
- );
12448
+ await this.requireInstanceRuntime().avatarHighlight(targetId, style);
11485
12449
  },
11486
12450
  pointAt: async (targetId) => {
11487
- await this.requireInstanceRuntime().avatarPointAt(
11488
- typeof targetId === "string" ? targetId : targetId.id || ""
11489
- );
12451
+ await this.requireInstanceRuntime().avatarPointAt(targetId);
11490
12452
  }
11491
12453
  },
11492
12454
  navigation: {
@@ -11792,10 +12754,10 @@ var Asiyst = {
11792
12754
  interact: {
11793
12755
  async highlight(targetId, options) {
11794
12756
  const style = typeof options === "string" ? options : options?.style;
11795
- await requireRuntime().avatarHighlight(typeof targetId === "string" ? targetId : targetId.id || "", style);
12757
+ await requireRuntime().avatarHighlight(targetId, style);
11796
12758
  },
11797
12759
  async pointAt(targetId) {
11798
- await requireRuntime().avatarPointAt(typeof targetId === "string" ? targetId : targetId.id || "");
12760
+ await requireRuntime().avatarPointAt(targetId);
11799
12761
  }
11800
12762
  },
11801
12763
  navigation: {
@@ -11929,6 +12891,6 @@ async function createAsiystInstance(options) {
11929
12891
  return instance;
11930
12892
  }
11931
12893
 
11932
- export { ACTION_RISK_MAP, ACTION_STATUSES, AUBRSkeleton, AVATAR_ACTION_PROTOCOL_VERSION, AVATAR_ACTION_TYPES, ActionNotAllowedError, ActionScheduler, Asiyst, AsiystError, AssetLoader, AuthenticationError, AvatarController, AvatarMetricsTracker, CANONICAL_BONE_NAMES, ConfigurationError, ConfirmationManager, CssAvatarRenderer, CustomHostNavigationAdapter, DefaultBrowserNavigationAdapter, FABRIKSolver, FacialAnimationEngine, FbxRenderer, GestureEngine, GreetingManager, IdleEngine, InitializationError, LocomotionEngine, LookAtEngine, MotionCoordinator, MotionStateMachine, MovementEngine, NetworkError, NextJsAppRouterNavigationAdapter, NextJsPagesNavigationAdapter, ProceduralMovementEngine, RigDetector, RuntimeEventReporter, SDK_VERSION, SpeechPlayer, TargetNotFoundError, TargetRegistry, TaskExecutionError, TaskStatus, TourEngine, TwoBoneIK, anchorToViewport, asiystInit, canNavigateTo, canTransition, computeAvatarDestination, createAsiystInstance, createNextAppRouterAdapter, evaluateActionPermission, fallbackConfig, isActionAllowed, isSafeSelector, isSensitiveTarget, normalizeProjectConfig, sanitizeText, setGlobalNavigationAdapter, validateActionDependencies, validateActionItem, validateActionPlan, validateInitOptions, validateWebsiteDomain };
12894
+ export { ACTION_RISK_MAP, ACTION_STATUSES, AUBRSkeleton, AVATAR_ACTION_PROTOCOL_VERSION, AVATAR_ACTION_TYPES, ActionNotAllowedError, ActionScheduler, Asiyst, AsiystError, AssetLoader, AuthenticationError, AvatarController, AvatarMetricsTracker, BalanceEngine, CANONICAL_BONE_NAMES, ConfigurationError, ConfirmationManager, CssAvatarRenderer, CustomHostNavigationAdapter, DefaultBrowserNavigationAdapter, FABRIKSolver, FacialAnimationEngine, FbxRenderer, GestureEngine, GreetingManager, IdleEngine, InitializationError, LocomotionEngine, LookAtEngine, MotionCoordinator, MotionStateMachine, MovementEngine, NetworkError, NextJsAppRouterNavigationAdapter, NextJsPagesNavigationAdapter, ProceduralMovementEngine, RigDetector, RuntimeEventReporter, SDK_VERSION, SpeechPlayer, TargetNotFoundError, TargetRegistry, TaskExecutionError, TaskStatus, TourEngine, TurnEngine, TwoBoneIK, anchorToViewport, asiystInit, canNavigateTo, canTransition, computeAvatarDestination, createAsiystInstance, createNextAppRouterAdapter, evaluateActionPermission, fallbackConfig, isActionAllowed, isSafeSelector, isSensitiveTarget, normalizeProjectConfig, sanitizeText, setGlobalNavigationAdapter, validateActionDependencies, validateActionItem, validateActionPlan, validateInitOptions, validateWebsiteDomain };
11933
12895
  //# sourceMappingURL=index.js.map
11934
12896
  //# sourceMappingURL=index.js.map