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