@asiyst/sdk 0.1.9 → 0.1.12

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/README.md CHANGED
@@ -30,12 +30,15 @@ await Asiyst.init({
30
30
  publicKey: "<PUBLIC_KEY>",
31
31
  avatarId: "<PUBLIC_AVATAR_ID>",
32
32
  });
33
+ Asiyst.open();
33
34
  ```
34
35
 
35
36
  Do not pass a secret API key as `publicKey` or omit `projectId`.
36
37
 
37
38
  `avatarId` selects the avatar that the dashboard configured for this project. It is a public identifier, not an authorization credential. The SDK sends it as a selection hint while the Asiyst API still authenticates and authorizes the project with the public project key.
38
39
 
40
+ Knowledge sources, including optional GitHub repositories, are configured in Asiyst Web. The SDK does not receive GitHub credentials and does not copy Knowledge Base content into the website. It initializes the verified project/avatar and retrieves authorized knowledge through the Asiyst backend.
41
+
39
42
  ```ts
40
43
  await Asiyst.init({
41
44
  publicKey: "<PUBLIC_KEY>",
package/dist/index.cjs CHANGED
@@ -71,7 +71,7 @@ var ALL_ACTION_KINDS = [
71
71
  ];
72
72
 
73
73
  // src/core/constants.ts
74
- var SDK_VERSION = "0.1.9" ;
74
+ var SDK_VERSION = "0.1.11" ;
75
75
  var DEFAULT_API_BASE_URL = "https://nqhxpgsjofzqudyqkqib.supabase.co/functions/v1/api";
76
76
  var CONFIG_SCHEMA_VERSION = 1;
77
77
  var HOST_ELEMENT_ID = "asiyst-host";
@@ -434,7 +434,8 @@ var HttpTransport = class {
434
434
  "X-Asiyst-Project-Id": this.options.projectId,
435
435
  "X-Asiyst-Public-Key": this.options.publicKey,
436
436
  ...this.options.avatarId ? { "X-Asiyst-Avatar-Id": this.options.avatarId } : {},
437
- "X-Asiyst-SDK-Version": SDK_VERSION
437
+ "X-Asiyst-SDK-Version": SDK_VERSION,
438
+ ...req.authorizationToken ? { Authorization: `Bearer ${req.authorizationToken}` } : {}
438
439
  },
439
440
  body: req.body === void 0 ? void 0 : JSON.stringify(req.body),
440
441
  signal: req.signal
@@ -460,12 +461,14 @@ var HttpTransport = class {
460
461
 
461
462
  // src/communication/CloudClient.ts
462
463
  var CloudClient = class {
463
- constructor(transport, projectId) {
464
+ constructor(transport, projectId, publicKey = "", runtimeAuth) {
464
465
  this.transport = transport;
465
466
  this.projectId = projectId;
467
+ this.publicKey = publicKey;
468
+ this.runtimeAuth = runtimeAuth;
466
469
  }
467
470
  async fetchConfig() {
468
- const response = await this.transport.request({
471
+ const response = await this.runtimeRequest({
469
472
  path: `/projects/${encodeURIComponent(this.projectId)}/avatar`,
470
473
  method: "GET"
471
474
  });
@@ -478,21 +481,40 @@ var CloudClient = class {
478
481
  return normalizeProjectConfig(response.data.config ?? response.data);
479
482
  }
480
483
  async heartbeat(metadata) {
481
- const response = await this.transport.request({
484
+ const response = await this.runtimeRequest({
482
485
  path: "/sdk/heartbeat",
483
486
  method: "POST",
484
487
  body: {
485
- projectId: this.projectId,
486
- sdkVersion: SDK_VERSION,
487
- websiteOrigin: metadata.origin,
488
+ project_id: this.projectId,
489
+ public_key: this.publicKey,
490
+ sdk_version: SDK_VERSION,
491
+ origin: metadata.origin,
488
492
  environment: metadata.environment,
489
493
  timestamp: metadata.timestamp
490
494
  }
495
+ }, "assistant:heartbeat");
496
+ const body = response.data && typeof response.data === "object" && !Array.isArray(response.data) ? response.data : void 0;
497
+ const rawStatus = body?.status ?? body?.connectionStatus ?? body?.verificationStatus;
498
+ const verificationStatus = rawStatus === "connected" || rawStatus === "inactive" || rawStatus === "not_detected" || rawStatus === "error" ? rawStatus : void 0;
499
+ return {
500
+ ok: response.ok && (verificationStatus === void 0 || verificationStatus === "connected"),
501
+ status: response.status,
502
+ verificationStatus
503
+ };
504
+ }
505
+ async registerInstallation(registration) {
506
+ const response = await this.transport.request({
507
+ path: "/sdk/installations/register",
508
+ method: "POST",
509
+ body: registration
491
510
  });
492
- return { ok: response.ok, status: response.status };
511
+ if (!response.ok) {
512
+ throw new NetworkError(`SDK installation registration failed (${response.status}).`);
513
+ }
514
+ return response.data ?? {};
493
515
  }
494
516
  async requestTask(userText, pageUrl) {
495
- const response = await this.transport.request({
517
+ const response = await this.runtimeRequest({
496
518
  path: "/tasks",
497
519
  method: "POST",
498
520
  body: {
@@ -500,28 +522,28 @@ var CloudClient = class {
500
522
  text: userText,
501
523
  pageUrl
502
524
  }
503
- });
525
+ }, "assistant:conversation");
504
526
  if (!response.ok || !response.data?.task?.id || !Array.isArray(response.data.task.steps)) {
505
527
  throw new NetworkError("Task planning is unavailable");
506
528
  }
507
529
  return response.data.task;
508
530
  }
509
531
  async fetchWorkflow(workflowId) {
510
- const response = await this.transport.request({
532
+ const response = await this.runtimeRequest({
511
533
  path: `/workflows/${encodeURIComponent(workflowId)}`,
512
534
  method: "GET"
513
- });
535
+ }, "assistant:conversation");
514
536
  if (!response.ok || !response.data?.workflow?.id || !Array.isArray(response.data.workflow.steps)) {
515
537
  throw new NetworkError("Workflow is unavailable");
516
538
  }
517
539
  return response.data.workflow;
518
540
  }
519
541
  async sendConversationMessage(text, pageUrl) {
520
- const response = await this.transport.request({
542
+ const response = await this.runtimeRequest({
521
543
  path: "/conversations/messages",
522
544
  method: "POST",
523
545
  body: { projectId: this.projectId, text, pageUrl }
524
- });
546
+ }, "assistant:conversation");
525
547
  if (!response.ok || !response.data?.message?.text) {
526
548
  throw new NetworkError("Conversation service is unavailable");
527
549
  }
@@ -541,10 +563,23 @@ var CloudClient = class {
541
563
  }
542
564
  async safePost(path, body) {
543
565
  try {
544
- await this.transport.request({ path, method: "POST", body });
566
+ await this.runtimeRequest({ path, method: "POST", body }, "assistant:telemetry");
545
567
  } catch {
546
568
  }
547
569
  }
570
+ async runtimeRequest(request, capability = "assistant:config") {
571
+ if (!this.runtimeAuth) {
572
+ return this.transport.request(request);
573
+ }
574
+ let token = await this.runtimeAuth.getToken(capability);
575
+ let response = await this.transport.request({ ...request, authorizationToken: token });
576
+ if (response.status === 401) {
577
+ this.runtimeAuth.invalidate();
578
+ token = await this.runtimeAuth.getToken(capability);
579
+ response = await this.transport.request({ ...request, authorizationToken: token });
580
+ }
581
+ return response;
582
+ }
548
583
  };
549
584
 
550
585
  // src/storage/NamespacedStorage.ts
@@ -1762,7 +1797,14 @@ var AvatarController = class {
1762
1797
 
1763
1798
  // src/interaction/permissions.ts
1764
1799
  function normalizeHost(host) {
1765
- return host.replace(/^https?:\/\//i, "").replace(/\/$/, "").toLowerCase();
1800
+ const candidate = host.trim();
1801
+ try {
1802
+ const parsed = new URL(/^[a-z][a-z\d+\-.]*:\/\//i.test(candidate) ? candidate : `https://${candidate}`);
1803
+ return (parsed.hostname ?? "").replace(/^www\./i, "").toLowerCase();
1804
+ } catch {
1805
+ const fallbackHost = candidate.replace(/^https?:\/\//i, "").split("/", 1)[0] ?? "";
1806
+ return fallbackHost.replace(/^www\./i, "").replace(/:\d+$/, "").toLowerCase();
1807
+ }
1766
1808
  }
1767
1809
  function matchesRoutePattern(pathname, pattern) {
1768
1810
  const candidate = pathname;
@@ -2355,6 +2397,134 @@ function withIsolation(fn) {
2355
2397
  }
2356
2398
  }
2357
2399
 
2400
+ // src/installation/Installation.ts
2401
+ var INSTALLATION_KEY = "installation_id";
2402
+ var INSTALLATION_ID_PATTERN = /^inst_[A-Za-z0-9][A-Za-z0-9_-]{7,127}$/;
2403
+ var memoryIds = /* @__PURE__ */ new Map();
2404
+ function randomInstallationId() {
2405
+ try {
2406
+ const cryptoApi = globalThis.crypto;
2407
+ if (typeof cryptoApi?.randomUUID === "function") {
2408
+ return `inst_${cryptoApi.randomUUID()}`;
2409
+ }
2410
+ if (typeof cryptoApi?.getRandomValues === "function") {
2411
+ const bytes = cryptoApi.getRandomValues(new Uint8Array(16));
2412
+ return `inst_${Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("")}`;
2413
+ }
2414
+ } catch {
2415
+ return void 0;
2416
+ }
2417
+ return void 0;
2418
+ }
2419
+ function loadOrCreateInstallationId(projectId) {
2420
+ const inMemory = memoryIds.get(projectId);
2421
+ if (inMemory) return inMemory;
2422
+ const storage = new NamespacedStorage(projectId, browserLocalStorage());
2423
+ const existing = storage.read(INSTALLATION_KEY)?.trim();
2424
+ if (existing && INSTALLATION_ID_PATTERN.test(existing)) {
2425
+ memoryIds.set(projectId, existing);
2426
+ return existing;
2427
+ }
2428
+ const installationId = randomInstallationId();
2429
+ if (!installationId) return void 0;
2430
+ memoryIds.set(projectId, installationId);
2431
+ storage.write(INSTALLATION_KEY, installationId);
2432
+ return installationId;
2433
+ }
2434
+
2435
+ // src/communication/RuntimeAuth.ts
2436
+ var RUNTIME_AUDIENCE = "asiyst-sdk-runtime";
2437
+ var RUNTIME_CAPABILITIES = [
2438
+ "assistant:config",
2439
+ "assistant:conversation",
2440
+ "assistant:telemetry",
2441
+ "assistant:heartbeat"
2442
+ ];
2443
+ var RuntimeAuth = class {
2444
+ constructor(options) {
2445
+ this.options = options;
2446
+ }
2447
+ async getToken(capability) {
2448
+ if (this.token && this.isUsable(this.token) && this.token.capabilities.has(capability)) {
2449
+ return this.token.value;
2450
+ }
2451
+ if (!this.requestInFlight) {
2452
+ this.requestInFlight = this.issueToken().finally(() => {
2453
+ this.requestInFlight = void 0;
2454
+ });
2455
+ }
2456
+ const token = await this.requestInFlight;
2457
+ if (!token.capabilities.has(capability)) {
2458
+ throw new AuthenticationError("ASIYST runtime authorization does not allow this operation.");
2459
+ }
2460
+ return token.value;
2461
+ }
2462
+ invalidate() {
2463
+ this.token = void 0;
2464
+ }
2465
+ isUsable(token) {
2466
+ return token.expiresAt - Date.now() > 3e4;
2467
+ }
2468
+ async issueToken() {
2469
+ const controller = new AbortController();
2470
+ const timeout = setTimeout(() => controller.abort(), 1e4);
2471
+ let response;
2472
+ try {
2473
+ response = await fetch(`${this.options.apiBaseUrl.replace(/\/$/, "")}/sdk/runtime/token`, {
2474
+ method: "POST",
2475
+ headers: {
2476
+ Accept: "application/json",
2477
+ "Content-Type": "application/json"
2478
+ },
2479
+ body: JSON.stringify({
2480
+ projectId: this.options.projectId,
2481
+ publicKey: this.options.publicKey,
2482
+ installationId: this.options.installationId,
2483
+ origin: this.options.origin,
2484
+ environment: this.options.environment,
2485
+ sdkVersion: SDK_VERSION,
2486
+ capabilities: [...RUNTIME_CAPABILITIES]
2487
+ }),
2488
+ signal: controller.signal
2489
+ });
2490
+ } catch {
2491
+ throw new NetworkError("ASIYST runtime authentication is unavailable.");
2492
+ } finally {
2493
+ clearTimeout(timeout);
2494
+ }
2495
+ let body;
2496
+ try {
2497
+ body = await response.json();
2498
+ } catch {
2499
+ body = void 0;
2500
+ }
2501
+ if (!response.ok) {
2502
+ if (response.status === 403) {
2503
+ throw new AuthenticationError("ASIYST runtime authorization was rejected.");
2504
+ }
2505
+ if (response.status === 429) {
2506
+ throw new NetworkError("ASIYST runtime authentication is rate limited.");
2507
+ }
2508
+ throw new NetworkError("ASIYST runtime authentication is unavailable.");
2509
+ }
2510
+ const data = body?.data;
2511
+ if (!data || body?.success !== true || typeof data.token !== "string" || data.token.length < 20 || data.tokenType !== "Bearer" || data.audience !== RUNTIME_AUDIENCE || typeof data.expiresIn !== "number" || !Number.isFinite(data.expiresIn) || data.expiresIn <= 0 || typeof data.expiresAt !== "string" || !Array.isArray(data.capabilities) || data.capabilities.some((capability) => !RUNTIME_CAPABILITIES.includes(capability))) {
2512
+ throw new AuthenticationError("ASIYST returned an invalid runtime authorization response.");
2513
+ }
2514
+ const expiresAt = Date.parse(data.expiresAt);
2515
+ if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) {
2516
+ throw new AuthenticationError("ASIYST runtime authorization has expired.");
2517
+ }
2518
+ const token = {
2519
+ value: data.token,
2520
+ expiresAt,
2521
+ capabilities: new Set(data.capabilities)
2522
+ };
2523
+ this.token = token;
2524
+ return token;
2525
+ }
2526
+ };
2527
+
2358
2528
  // src/core/Runtime.ts
2359
2529
  var AsiystRuntime = class {
2360
2530
  constructor(options, doc, win) {
@@ -2363,18 +2533,30 @@ var AsiystRuntime = class {
2363
2533
  this.observer = new DomObserver(() => this.rescan());
2364
2534
  this.destroyed = false;
2365
2535
  this.connectionStatus = "disconnected";
2536
+ this.verificationStatus = "not_detected";
2366
2537
  this.rescanDebounced = debounce(() => this.rescan(), DOM_SCAN_DEBOUNCE_MS);
2367
2538
  if (!doc.body) {
2368
2539
  throw new InitializationError("document.body is not available");
2369
2540
  }
2370
2541
  this.options = options;
2542
+ this.installationId = loadOrCreateInstallationId(options.projectId);
2543
+ const isLocalOrigin = /^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i.test(win.location.hostname);
2544
+ this.environment = options.apiBaseUrl || isLocalOrigin ? "development" : "production";
2371
2545
  const transport = new HttpTransport({
2372
2546
  apiBaseUrl: options.apiBaseUrl ?? DEFAULT_API_BASE_URL,
2373
2547
  projectId: options.projectId,
2374
2548
  publicKey: options.publicKey,
2375
2549
  avatarId: options.avatarId
2376
2550
  });
2377
- this.cloud = new CloudClient(transport, options.projectId);
2551
+ const runtimeAuth = this.installationId ? new RuntimeAuth({
2552
+ apiBaseUrl: options.apiBaseUrl ?? DEFAULT_API_BASE_URL,
2553
+ projectId: options.projectId,
2554
+ publicKey: options.publicKey,
2555
+ installationId: this.installationId,
2556
+ origin: win.location.origin,
2557
+ environment: this.environment
2558
+ }) : void 0;
2559
+ this.cloud = new CloudClient(transport, options.projectId, options.publicKey, runtimeAuth);
2378
2560
  this.config = new ConfigManager(options, this.cloud, this.events);
2379
2561
  this.analytics = new Analytics(options.projectId, this.cloud);
2380
2562
  this.host = new HostRoot(doc);
@@ -2432,6 +2614,7 @@ var AsiystRuntime = class {
2432
2614
  const domainCheck = validateWebsiteDomain(cfg, window.location.href);
2433
2615
  if (!domainCheck.allowed) {
2434
2616
  this.connectionStatus = "disconnected";
2617
+ this.verificationStatus = "not_detected";
2435
2618
  this.events.emit("asiyst:error", {
2436
2619
  code: "domain_not_authorized",
2437
2620
  message: "This website is not authorized for the current Asiyst project."
@@ -2440,21 +2623,27 @@ var AsiystRuntime = class {
2440
2623
  }
2441
2624
  this.avatar.applyConfig(cfg);
2442
2625
  this.avatar.show();
2626
+ await this.registerInstallation();
2443
2627
  try {
2444
2628
  const heartbeat = await this.cloud.heartbeat({
2445
2629
  origin: window.location.origin,
2446
- environment: this.options.apiBaseUrl ? "development" : "production",
2630
+ environment: this.environment,
2447
2631
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
2448
2632
  });
2449
2633
  this.connectionStatus = heartbeat.ok ? "connected" : "disconnected";
2634
+ this.verificationStatus = heartbeat.verificationStatus ?? (heartbeat.ok ? "connected" : "not_detected");
2450
2635
  } catch {
2451
2636
  this.connectionStatus = "offline";
2637
+ this.verificationStatus = "error";
2452
2638
  }
2453
2639
  this.events.emit("asiyst:ready", { projectId: this.options.projectId, configVersion: cfg.version });
2454
2640
  }
2455
2641
  getConnectionStatus() {
2456
2642
  return this.connectionStatus;
2457
2643
  }
2644
+ getVerificationStatus() {
2645
+ return this.verificationStatus;
2646
+ }
2458
2647
  getConfig() {
2459
2648
  return this.config.get();
2460
2649
  }
@@ -2510,6 +2699,38 @@ var AsiystRuntime = class {
2510
2699
  this.events.removeAll();
2511
2700
  await this.analytics.destroy();
2512
2701
  }
2702
+ async registerInstallation() {
2703
+ const origin = window.location.origin;
2704
+ const environment = this.environment;
2705
+ const installationId = this.installationId;
2706
+ if (!installationId) {
2707
+ if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
2708
+ console.debug("[asiyst] SDK installation identity is unavailable; registration skipped.");
2709
+ }
2710
+ return;
2711
+ }
2712
+ for (let attempt = 0; attempt < 2; attempt += 1) {
2713
+ try {
2714
+ await this.cloud.registerInstallation({
2715
+ project_id: this.options.projectId,
2716
+ public_key: this.options.publicKey,
2717
+ installation_id: installationId,
2718
+ origin,
2719
+ environment,
2720
+ sdk_version: SDK_VERSION
2721
+ });
2722
+ return;
2723
+ } catch (error) {
2724
+ if (attempt === 1) {
2725
+ if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
2726
+ console.debug("[asiyst] SDK installation registration failed.", error);
2727
+ }
2728
+ return;
2729
+ }
2730
+ await new Promise((resolve) => setTimeout(resolve, 250));
2731
+ }
2732
+ }
2733
+ }
2513
2734
  rescan() {
2514
2735
  withIsolation(() => {
2515
2736
  const doc = this.host.host.ownerDocument;
@@ -2577,6 +2798,9 @@ var Asiyst = {
2577
2798
  getConnectionStatus() {
2578
2799
  return requireRuntime().getConnectionStatus();
2579
2800
  },
2801
+ getVerificationStatus() {
2802
+ return requireRuntime().getVerificationStatus();
2803
+ },
2580
2804
  avatar: {
2581
2805
  show() {
2582
2806
  withIsolation(() => requireRuntime().avatarApi().show());