@asiyst/sdk 0.1.16 → 0.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -73,7 +73,7 @@ var ALL_ACTION_KINDS = [
73
73
  // src/core/constants.ts
74
74
  function resolveSdkVersion() {
75
75
  {
76
- return "0.1.15";
76
+ return "0.1.18";
77
77
  }
78
78
  }
79
79
  var SDK_VERSION = resolveSdkVersion();
@@ -423,72 +423,177 @@ var EventBus = class {
423
423
  };
424
424
 
425
425
  // src/communication/HttpTransport.ts
426
+ var DEFAULT_TIMEOUT_MS = 1e4;
427
+ function generateRequestId() {
428
+ return `req_${Math.random().toString(36).slice(2, 10)}_${Date.now().toString(36)}`;
429
+ }
426
430
  var HttpTransport = class {
427
431
  constructor(options) {
428
432
  this.options = options;
429
433
  }
430
434
  async request(req) {
431
435
  const url = `${this.options.apiBaseUrl.replace(/\/$/, "")}${req.path}`;
432
- let response;
433
- try {
434
- response = await fetch(url, {
435
- method: req.method,
436
- headers: {
437
- Accept: "application/json",
438
- "Content-Type": "application/json",
439
- "X-Asiyst-Project-Id": this.options.projectId,
440
- "X-Asiyst-Public-Key": this.options.publicKey,
441
- ...this.options.avatarId ? { "X-Asiyst-Avatar-Id": this.options.avatarId } : {},
442
- "X-Asiyst-SDK-Version": SDK_VERSION,
443
- ...req.authorizationToken ? { Authorization: `Bearer ${req.authorizationToken}` } : {}
444
- },
445
- body: req.body === void 0 ? void 0 : JSON.stringify(req.body),
446
- signal: req.signal
447
- });
448
- } catch {
449
- throw new NetworkError("Asiyst Cloud is unreachable");
450
- }
451
- let data = null;
452
- const contentType = response.headers.get("content-type") ?? "";
453
- if (contentType.includes("application/json")) {
436
+ const requestId = req.requestId || generateRequestId();
437
+ const timeoutMs = req.timeoutMs ?? this.options.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS;
438
+ const isSafeOrIdempotent = req.method === "GET" || Boolean(req.idempotent);
439
+ const maxRetries = isSafeOrIdempotent ? req.retries ?? 2 : 0;
440
+ let lastError;
441
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
442
+ if (attempt > 0) {
443
+ const delay = Math.min(50 * Math.pow(2, attempt - 1), 500);
444
+ await new Promise((resolve) => setTimeout(resolve, delay));
445
+ }
446
+ const controller = new AbortController();
447
+ let timedOut = false;
448
+ const timeoutId = setTimeout(() => {
449
+ timedOut = true;
450
+ controller.abort();
451
+ }, timeoutMs);
452
+ const onExternalAbort = () => controller.abort();
453
+ if (req.signal) {
454
+ if (req.signal.aborted) {
455
+ clearTimeout(timeoutId);
456
+ controller.abort();
457
+ } else {
458
+ req.signal.addEventListener("abort", onExternalAbort, { once: true });
459
+ }
460
+ }
454
461
  try {
455
- data = await response.json();
456
- } catch {
457
- data = null;
462
+ let response;
463
+ try {
464
+ response = await fetch(url, {
465
+ method: req.method,
466
+ headers: {
467
+ Accept: "application/json",
468
+ "Content-Type": "application/json",
469
+ "X-Asiyst-Project-Id": this.options.projectId,
470
+ "X-Asiyst-Public-Key": this.options.publicKey,
471
+ ...this.options.avatarId ? { "X-Asiyst-Avatar-Id": this.options.avatarId } : {},
472
+ "X-Asiyst-SDK-Version": SDK_VERSION,
473
+ "X-Asiyst-Request-Id": requestId,
474
+ ...req.sessionId ? { "X-Asiyst-Session-Id": req.sessionId } : {},
475
+ ...req.conversationId ? { "X-Asiyst-Conversation-Id": req.conversationId } : {},
476
+ ...req.authorizationToken ? { Authorization: `Bearer ${req.authorizationToken}` } : {}
477
+ },
478
+ body: req.body === void 0 ? void 0 : JSON.stringify(req.body),
479
+ signal: controller.signal
480
+ });
481
+ } finally {
482
+ clearTimeout(timeoutId);
483
+ if (req.signal) {
484
+ req.signal.removeEventListener("abort", onExternalAbort);
485
+ }
486
+ }
487
+ if (isSafeOrIdempotent && attempt < maxRetries && [502, 503, 504].includes(response.status)) {
488
+ continue;
489
+ }
490
+ if (response.status === 429 && isSafeOrIdempotent && attempt < maxRetries) {
491
+ const retryAfterHeader = response.headers.get("retry-after");
492
+ const retryAfterMs = retryAfterHeader ? Math.min(Number(retryAfterHeader) * 1e3 || 200, 1e3) : 100;
493
+ await new Promise((resolve) => setTimeout(resolve, retryAfterMs));
494
+ continue;
495
+ }
496
+ let data = null;
497
+ const contentType = response.headers.get("content-type") ?? "";
498
+ if (contentType.includes("application/json")) {
499
+ try {
500
+ data = await response.json();
501
+ } catch {
502
+ data = null;
503
+ }
504
+ }
505
+ if (!response.ok) {
506
+ return { ok: false, status: response.status, data };
507
+ }
508
+ return { ok: true, status: response.status, data };
509
+ } catch (err) {
510
+ clearTimeout(timeoutId);
511
+ if (req.signal) {
512
+ req.signal.removeEventListener("abort", onExternalAbort);
513
+ }
514
+ if (timedOut) {
515
+ throw new NetworkError("Asiyst Cloud request timed out");
516
+ }
517
+ lastError = err;
518
+ if (isSafeOrIdempotent && attempt < maxRetries) {
519
+ continue;
520
+ }
521
+ throw new NetworkError("Asiyst Cloud is unreachable");
458
522
  }
459
523
  }
460
- if (!response.ok) {
461
- return { ok: false, status: response.status, data };
462
- }
463
- return { ok: true, status: response.status, data };
524
+ throw lastError instanceof Error ? lastError : new NetworkError("Asiyst Cloud is unreachable");
464
525
  }
465
526
  };
466
527
 
467
528
  // src/communication/CloudClient.ts
468
529
  var CloudClient = class {
469
- constructor(transport, projectId, publicKey = "", runtimeAuth) {
530
+ constructor(transport, projectId, publicKey = "", runtimeAuth, sessionId) {
470
531
  this.transport = transport;
471
532
  this.projectId = projectId;
472
533
  this.publicKey = publicKey;
473
534
  this.runtimeAuth = runtimeAuth;
535
+ this.inFlightConversations = /* @__PURE__ */ new Map();
536
+ this.sessionId = sessionId;
537
+ }
538
+ setSessionId(sessionId) {
539
+ this.sessionId = sessionId;
540
+ }
541
+ getSessionId() {
542
+ return this.sessionId;
543
+ }
544
+ setConversationId(conversationId) {
545
+ this.conversationId = conversationId;
546
+ }
547
+ getConversationId() {
548
+ return this.conversationId;
549
+ }
550
+ async getAuthToken(capability) {
551
+ if (!this.runtimeAuth) return void 0;
552
+ if (this.tokenRefreshPromise) return this.tokenRefreshPromise;
553
+ if (!this.inFlightToken) {
554
+ this.inFlightToken = this.runtimeAuth.getToken(capability).then((token) => {
555
+ this.activeToken = token;
556
+ return token;
557
+ }).finally(() => {
558
+ this.inFlightToken = void 0;
559
+ });
560
+ }
561
+ return this.inFlightToken;
474
562
  }
475
563
  async fetchConfig() {
476
- const response = await this.runtimeRequest({
477
- path: `/projects/${encodeURIComponent(this.projectId)}/avatar`,
478
- method: "GET"
479
- });
480
- if (response.status === 401 || response.status === 403) {
481
- throw new AuthenticationError("Project credentials were rejected");
564
+ try {
565
+ const response = await this.runtimeRequest({
566
+ path: `/projects/${encodeURIComponent(this.projectId)}/avatar`,
567
+ method: "GET",
568
+ idempotent: true
569
+ });
570
+ if (response.ok && response.data) {
571
+ return normalizeProjectConfig(response.data.config ?? response.data);
572
+ }
573
+ } catch {
482
574
  }
483
- if (!response.ok || !response.data) {
484
- throw new NetworkError("Project configuration could not be loaded");
575
+ try {
576
+ const res = await fetch(`https://asiyst.com/api/v1/runtime/avatar?projectId=${encodeURIComponent(this.projectId)}&publicKey=${encodeURIComponent(this.publicKey)}`, {
577
+ headers: { Accept: "application/json" }
578
+ });
579
+ if (res.ok) {
580
+ const body = await res.json();
581
+ if (body?.avatar) {
582
+ return normalizeProjectConfig({
583
+ avatarName: body.avatar.name,
584
+ avatarId: body.avatar.avatarId
585
+ });
586
+ }
587
+ }
588
+ } catch {
485
589
  }
486
- return normalizeProjectConfig(response.data.config ?? response.data);
590
+ return normalizeProjectConfig({});
487
591
  }
488
592
  async heartbeat(metadata) {
489
593
  const response = await this.runtimeRequest({
490
594
  path: "/sdk/heartbeat",
491
595
  method: "POST",
596
+ idempotent: true,
492
597
  body: {
493
598
  project_id: this.projectId,
494
599
  public_key: this.publicKey,
@@ -513,7 +618,9 @@ var CloudClient = class {
513
618
  const response = await this.transport.request({
514
619
  path: "/sdk/installations/register",
515
620
  method: "POST",
516
- body: registration
621
+ body: registration,
622
+ idempotent: true,
623
+ sessionId: this.sessionId
517
624
  });
518
625
  if (!response.ok) {
519
626
  throw new NetworkError(`SDK installation registration failed (${response.status}).`);
@@ -538,7 +645,8 @@ var CloudClient = class {
538
645
  async fetchWorkflow(workflowId) {
539
646
  const response = await this.runtimeRequest({
540
647
  path: `/workflows/${encodeURIComponent(workflowId)}`,
541
- method: "GET"
648
+ method: "GET",
649
+ idempotent: true
542
650
  }, "assistant:conversation");
543
651
  if (!response.ok || !response.data?.workflow?.id || !Array.isArray(response.data.workflow.steps)) {
544
652
  throw new NetworkError("Workflow is unavailable");
@@ -546,15 +654,30 @@ var CloudClient = class {
546
654
  return response.data.workflow;
547
655
  }
548
656
  async sendConversationMessage(text, pageUrl) {
549
- const response = await this.runtimeRequest({
550
- path: "/conversations/messages",
551
- method: "POST",
552
- body: { projectId: this.projectId, text, pageUrl }
553
- }, "assistant:conversation");
554
- if (!response.ok || !response.data?.message?.text) {
555
- throw new NetworkError("Conversation service is unavailable");
657
+ const trimmed = text.trim();
658
+ const dedupeKey2 = `${this.conversationId ?? ""}:${trimmed}:${pageUrl}`;
659
+ const existing = this.inFlightConversations.get(dedupeKey2);
660
+ if (existing) {
661
+ return existing;
556
662
  }
557
- return response.data;
663
+ const conversationPromise = (async () => {
664
+ try {
665
+ const response = await this.runtimeRequest({
666
+ path: "/conversations/messages",
667
+ method: "POST",
668
+ body: { projectId: this.projectId, text: trimmed, pageUrl },
669
+ conversationId: this.conversationId
670
+ }, "assistant:conversation");
671
+ if (!response.ok || !response.data?.message?.text) {
672
+ throw new NetworkError("Conversation service is unavailable");
673
+ }
674
+ return response.data;
675
+ } finally {
676
+ this.inFlightConversations.delete(dedupeKey2);
677
+ }
678
+ })();
679
+ this.inFlightConversations.set(dedupeKey2, conversationPromise);
680
+ return conversationPromise;
558
681
  }
559
682
  async sendWebsiteMap(snapshot) {
560
683
  await this.safePost("/website-maps", snapshot);
@@ -562,6 +685,33 @@ var CloudClient = class {
562
685
  async sendAnalytics(events) {
563
686
  await this.safePost("/analytics", { events });
564
687
  }
688
+ async sendTelemetryEvent(eventType, metadata = {}) {
689
+ try {
690
+ const origin = typeof window !== "undefined" ? window.location.origin : void 0;
691
+ const installationId = this.runtimeAuth ? this.runtimeAuth.options?.installationId : void 0;
692
+ const payload = {
693
+ projectId: this.projectId,
694
+ publicKey: this.publicKey,
695
+ eventType,
696
+ installationId,
697
+ origin,
698
+ metadata: {
699
+ ...metadata,
700
+ sdkVersion: SDK_VERSION
701
+ }
702
+ };
703
+ await fetch("https://asiyst.com/api/v1/events", {
704
+ method: "POST",
705
+ headers: {
706
+ "Content-Type": "application/json",
707
+ Accept: "application/json",
708
+ "x-asiyst-public-key": this.publicKey
709
+ },
710
+ body: JSON.stringify(payload)
711
+ });
712
+ } catch {
713
+ }
714
+ }
565
715
  async sendTaskUpdate(taskId, status, stepId) {
566
716
  await this.safePost(`/tasks/${encodeURIComponent(taskId)}/events`, {
567
717
  status,
@@ -570,20 +720,35 @@ var CloudClient = class {
570
720
  }
571
721
  async safePost(path, body) {
572
722
  try {
573
- await this.runtimeRequest({ path, method: "POST", body }, "assistant:telemetry");
723
+ await this.runtimeRequest({ path, method: "POST", body, idempotent: true }, "assistant:telemetry");
574
724
  } catch {
575
725
  }
576
726
  }
577
727
  async runtimeRequest(request, capability = "assistant:config") {
728
+ const fullRequest = {
729
+ ...request,
730
+ sessionId: request.sessionId ?? this.sessionId,
731
+ conversationId: request.conversationId ?? this.conversationId
732
+ };
578
733
  if (!this.runtimeAuth) {
579
- return this.transport.request(request);
734
+ return this.transport.request(fullRequest);
580
735
  }
581
- let token = await this.runtimeAuth.getToken(capability);
582
- let response = await this.transport.request({ ...request, authorizationToken: token });
736
+ let token = await this.getAuthToken(capability);
737
+ let response = await this.transport.request({ ...fullRequest, authorizationToken: token });
583
738
  if (response.status === 401) {
584
- this.runtimeAuth.invalidate();
585
- token = await this.runtimeAuth.getToken(capability);
586
- response = await this.transport.request({ ...request, authorizationToken: token });
739
+ if (!this.tokenRefreshPromise) {
740
+ this.runtimeAuth.invalidate();
741
+ this.tokenRefreshPromise = this.runtimeAuth.getToken(capability).then((newToken) => {
742
+ this.activeToken = newToken;
743
+ return newToken;
744
+ }).finally(() => {
745
+ setTimeout(() => {
746
+ this.tokenRefreshPromise = void 0;
747
+ }, 50);
748
+ });
749
+ }
750
+ token = await this.tokenRefreshPromise ?? this.activeToken;
751
+ response = await this.transport.request({ ...fullRequest, authorizationToken: token });
587
752
  }
588
753
  return response;
589
754
  }
@@ -2273,8 +2438,8 @@ var ConversationPanel = class {
2273
2438
  this.conversationId = "";
2274
2439
  this.openState = false;
2275
2440
  const doc = root.ownerDocument;
2276
- const style = doc.createElement("style");
2277
- style.textContent = `
2441
+ this.style = doc.createElement("style");
2442
+ this.style.textContent = `
2278
2443
  .asiyst-panel {
2279
2444
  position: fixed;
2280
2445
  right: 16px;
@@ -2310,7 +2475,7 @@ var ConversationPanel = class {
2310
2475
  }
2311
2476
  .asiyst-close { background: transparent; color: #f8fafc; }
2312
2477
  `;
2313
- root.appendChild(style);
2478
+ root.appendChild(this.style);
2314
2479
  this.panel = doc.createElement("section");
2315
2480
  this.panel.className = "asiyst-panel";
2316
2481
  this.panel.hidden = true;
@@ -2344,11 +2509,12 @@ var ConversationPanel = class {
2344
2509
  });
2345
2510
  this.panel.append(header, this.log, this.form);
2346
2511
  root.appendChild(this.panel);
2347
- doc.addEventListener("keydown", (event) => {
2512
+ this.keydownListener = (event) => {
2348
2513
  if (event.key === "Escape" && this.openState) {
2349
2514
  this.close();
2350
2515
  }
2351
- });
2516
+ };
2517
+ doc.addEventListener("keydown", this.keydownListener);
2352
2518
  }
2353
2519
  isOpen() {
2354
2520
  return this.openState;
@@ -2387,6 +2553,14 @@ var ConversationPanel = class {
2387
2553
  this.append("user", text);
2388
2554
  await this.onSubmit(text);
2389
2555
  }
2556
+ destroy() {
2557
+ if (this.keydownListener) {
2558
+ this.panel.ownerDocument.removeEventListener("keydown", this.keydownListener);
2559
+ this.keydownListener = void 0;
2560
+ }
2561
+ this.panel.remove();
2562
+ this.style.remove();
2563
+ }
2390
2564
  };
2391
2565
 
2392
2566
  // src/core/isolate.ts
@@ -2645,6 +2819,7 @@ var AsiystRuntime = class {
2645
2819
  }
2646
2820
  this.options = options;
2647
2821
  this.installationId = loadOrCreateInstallationId(options.projectId);
2822
+ this.visitorSessionId = options.visitorSessionId || `vsess_${Math.random().toString(36).slice(2, 10)}_${Date.now().toString(36)}`;
2648
2823
  const isLocalOrigin = /^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i.test(win.location.hostname);
2649
2824
  this.environment = options.apiBaseUrl || isLocalOrigin ? "development" : "production";
2650
2825
  const transport = new HttpTransport({
@@ -2661,7 +2836,7 @@ var AsiystRuntime = class {
2661
2836
  origin: win.location.origin,
2662
2837
  environment: this.environment
2663
2838
  }) : void 0;
2664
- this.cloud = new CloudClient(transport, options.projectId, options.publicKey, runtimeAuth);
2839
+ this.cloud = new CloudClient(transport, options.projectId, options.publicKey, runtimeAuth, this.visitorSessionId);
2665
2840
  this.config = new ConfigManager(options, this.cloud, this.events);
2666
2841
  this.analytics = new Analytics(options.projectId, this.cloud);
2667
2842
  this.host = new HostRoot(doc);
@@ -2691,12 +2866,14 @@ var AsiystRuntime = class {
2691
2866
  this.host.chrome,
2692
2867
  (text) => this.handleUserMessage(text, doc),
2693
2868
  (open) => {
2869
+ const convId = this.panel.getConversationId();
2870
+ this.cloud.setConversationId(convId);
2694
2871
  if (open) {
2695
2872
  this.analytics.track("assistant_opened");
2696
- this.events.emit("asiyst:conversation:started", { conversationId: this.panel.getConversationId() });
2873
+ this.events.emit("asiyst:conversation:started", { conversationId: convId });
2697
2874
  } else {
2698
2875
  this.analytics.track("assistant_closed");
2699
- this.events.emit("asiyst:conversation:closed", { conversationId: this.panel.getConversationId() });
2876
+ this.events.emit("asiyst:conversation:closed", { conversationId: convId });
2700
2877
  }
2701
2878
  }
2702
2879
  );
@@ -2708,10 +2885,15 @@ var AsiystRuntime = class {
2708
2885
  this.analytics.start();
2709
2886
  this.rescan();
2710
2887
  this.avatar.show();
2711
- this.renderer.getFigure()?.addEventListener("click", () => this.open());
2712
- win.addEventListener("pagehide", () => {
2888
+ const figure = this.renderer.getFigure();
2889
+ if (figure) {
2890
+ this.figureClickListener = () => this.open();
2891
+ figure.addEventListener("click", this.figureClickListener);
2892
+ }
2893
+ this.pagehideListener = () => {
2713
2894
  void this.analytics.flush();
2714
- });
2895
+ };
2896
+ win.addEventListener("pagehide", this.pagehideListener);
2715
2897
  }
2716
2898
  async start() {
2717
2899
  this.events.emit("asiyst:initialized", { projectId: this.options.projectId });
@@ -2813,6 +2995,14 @@ var AsiystRuntime = class {
2813
2995
  }
2814
2996
  }
2815
2997
  this.events.emit("asiyst:ready", { projectId: this.options.projectId, configVersion: cfg.version });
2998
+ void this.cloud.sendTelemetryEvent("avatar_runtime_initialized", {
2999
+ avatarId: this.options.avatarId ?? cfg.avatarName,
3000
+ avatarName: cfg.avatarName
3001
+ });
3002
+ void this.cloud.sendTelemetryEvent("avatar_asset_loaded", {
3003
+ avatarId: this.options.avatarId ?? cfg.avatarName,
3004
+ avatarName: cfg.avatarName
3005
+ });
2816
3006
  }
2817
3007
  getConnectionStatus() {
2818
3008
  return this.connectionStatus;
@@ -2864,6 +3054,14 @@ var AsiystRuntime = class {
2864
3054
  return;
2865
3055
  }
2866
3056
  this.destroyed = true;
3057
+ if (this.pagehideListener) {
3058
+ win.removeEventListener("pagehide", this.pagehideListener);
3059
+ }
3060
+ const figure = this.renderer.getFigure();
3061
+ if (figure && this.figureClickListener) {
3062
+ figure.removeEventListener("click", this.figureClickListener);
3063
+ }
3064
+ this.panel.destroy();
2867
3065
  this.observer.stop();
2868
3066
  this.history.stop(win);
2869
3067
  this.movement.stop();