@asiyst/sdk 0.1.11 → 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,6 +30,7 @@ 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`.
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,13 +461,14 @@ var HttpTransport = class {
460
461
 
461
462
  // src/communication/CloudClient.ts
462
463
  var CloudClient = class {
463
- constructor(transport, projectId, publicKey = "") {
464
+ constructor(transport, projectId, publicKey = "", runtimeAuth) {
464
465
  this.transport = transport;
465
466
  this.projectId = projectId;
466
467
  this.publicKey = publicKey;
468
+ this.runtimeAuth = runtimeAuth;
467
469
  }
468
470
  async fetchConfig() {
469
- const response = await this.transport.request({
471
+ const response = await this.runtimeRequest({
470
472
  path: `/projects/${encodeURIComponent(this.projectId)}/avatar`,
471
473
  method: "GET"
472
474
  });
@@ -479,7 +481,7 @@ var CloudClient = class {
479
481
  return normalizeProjectConfig(response.data.config ?? response.data);
480
482
  }
481
483
  async heartbeat(metadata) {
482
- const response = await this.transport.request({
484
+ const response = await this.runtimeRequest({
483
485
  path: "/sdk/heartbeat",
484
486
  method: "POST",
485
487
  body: {
@@ -490,7 +492,7 @@ var CloudClient = class {
490
492
  environment: metadata.environment,
491
493
  timestamp: metadata.timestamp
492
494
  }
493
- });
495
+ }, "assistant:heartbeat");
494
496
  const body = response.data && typeof response.data === "object" && !Array.isArray(response.data) ? response.data : void 0;
495
497
  const rawStatus = body?.status ?? body?.connectionStatus ?? body?.verificationStatus;
496
498
  const verificationStatus = rawStatus === "connected" || rawStatus === "inactive" || rawStatus === "not_detected" || rawStatus === "error" ? rawStatus : void 0;
@@ -500,8 +502,19 @@ var CloudClient = class {
500
502
  verificationStatus
501
503
  };
502
504
  }
503
- async requestTask(userText, pageUrl) {
505
+ async registerInstallation(registration) {
504
506
  const response = await this.transport.request({
507
+ path: "/sdk/installations/register",
508
+ method: "POST",
509
+ body: registration
510
+ });
511
+ if (!response.ok) {
512
+ throw new NetworkError(`SDK installation registration failed (${response.status}).`);
513
+ }
514
+ return response.data ?? {};
515
+ }
516
+ async requestTask(userText, pageUrl) {
517
+ const response = await this.runtimeRequest({
505
518
  path: "/tasks",
506
519
  method: "POST",
507
520
  body: {
@@ -509,28 +522,28 @@ var CloudClient = class {
509
522
  text: userText,
510
523
  pageUrl
511
524
  }
512
- });
525
+ }, "assistant:conversation");
513
526
  if (!response.ok || !response.data?.task?.id || !Array.isArray(response.data.task.steps)) {
514
527
  throw new NetworkError("Task planning is unavailable");
515
528
  }
516
529
  return response.data.task;
517
530
  }
518
531
  async fetchWorkflow(workflowId) {
519
- const response = await this.transport.request({
532
+ const response = await this.runtimeRequest({
520
533
  path: `/workflows/${encodeURIComponent(workflowId)}`,
521
534
  method: "GET"
522
- });
535
+ }, "assistant:conversation");
523
536
  if (!response.ok || !response.data?.workflow?.id || !Array.isArray(response.data.workflow.steps)) {
524
537
  throw new NetworkError("Workflow is unavailable");
525
538
  }
526
539
  return response.data.workflow;
527
540
  }
528
541
  async sendConversationMessage(text, pageUrl) {
529
- const response = await this.transport.request({
542
+ const response = await this.runtimeRequest({
530
543
  path: "/conversations/messages",
531
544
  method: "POST",
532
545
  body: { projectId: this.projectId, text, pageUrl }
533
- });
546
+ }, "assistant:conversation");
534
547
  if (!response.ok || !response.data?.message?.text) {
535
548
  throw new NetworkError("Conversation service is unavailable");
536
549
  }
@@ -550,10 +563,23 @@ var CloudClient = class {
550
563
  }
551
564
  async safePost(path, body) {
552
565
  try {
553
- await this.transport.request({ path, method: "POST", body });
566
+ await this.runtimeRequest({ path, method: "POST", body }, "assistant:telemetry");
554
567
  } catch {
555
568
  }
556
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
+ }
557
583
  };
558
584
 
559
585
  // src/storage/NamespacedStorage.ts
@@ -1771,7 +1797,14 @@ var AvatarController = class {
1771
1797
 
1772
1798
  // src/interaction/permissions.ts
1773
1799
  function normalizeHost(host) {
1774
- 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
+ }
1775
1808
  }
1776
1809
  function matchesRoutePattern(pathname, pattern) {
1777
1810
  const candidate = pathname;
@@ -2364,6 +2397,134 @@ function withIsolation(fn) {
2364
2397
  }
2365
2398
  }
2366
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
+
2367
2528
  // src/core/Runtime.ts
2368
2529
  var AsiystRuntime = class {
2369
2530
  constructor(options, doc, win) {
@@ -2378,13 +2539,24 @@ var AsiystRuntime = class {
2378
2539
  throw new InitializationError("document.body is not available");
2379
2540
  }
2380
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";
2381
2545
  const transport = new HttpTransport({
2382
2546
  apiBaseUrl: options.apiBaseUrl ?? DEFAULT_API_BASE_URL,
2383
2547
  projectId: options.projectId,
2384
2548
  publicKey: options.publicKey,
2385
2549
  avatarId: options.avatarId
2386
2550
  });
2387
- this.cloud = new CloudClient(transport, options.projectId, options.publicKey);
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);
2388
2560
  this.config = new ConfigManager(options, this.cloud, this.events);
2389
2561
  this.analytics = new Analytics(options.projectId, this.cloud);
2390
2562
  this.host = new HostRoot(doc);
@@ -2451,10 +2623,11 @@ var AsiystRuntime = class {
2451
2623
  }
2452
2624
  this.avatar.applyConfig(cfg);
2453
2625
  this.avatar.show();
2626
+ await this.registerInstallation();
2454
2627
  try {
2455
2628
  const heartbeat = await this.cloud.heartbeat({
2456
2629
  origin: window.location.origin,
2457
- environment: this.options.apiBaseUrl ? "development" : "production",
2630
+ environment: this.environment,
2458
2631
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
2459
2632
  });
2460
2633
  this.connectionStatus = heartbeat.ok ? "connected" : "disconnected";
@@ -2526,6 +2699,38 @@ var AsiystRuntime = class {
2526
2699
  this.events.removeAll();
2527
2700
  await this.analytics.destroy();
2528
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
+ }
2529
2734
  rescan() {
2530
2735
  withIsolation(() => {
2531
2736
  const doc = this.host.host.ownerDocument;