@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/dist/index.js CHANGED
@@ -69,7 +69,7 @@ var ALL_ACTION_KINDS = [
69
69
  ];
70
70
 
71
71
  // src/core/constants.ts
72
- var SDK_VERSION = "0.1.9" ;
72
+ var SDK_VERSION = "0.1.11" ;
73
73
  var DEFAULT_API_BASE_URL = "https://nqhxpgsjofzqudyqkqib.supabase.co/functions/v1/api";
74
74
  var CONFIG_SCHEMA_VERSION = 1;
75
75
  var HOST_ELEMENT_ID = "asiyst-host";
@@ -432,7 +432,8 @@ var HttpTransport = class {
432
432
  "X-Asiyst-Project-Id": this.options.projectId,
433
433
  "X-Asiyst-Public-Key": this.options.publicKey,
434
434
  ...this.options.avatarId ? { "X-Asiyst-Avatar-Id": this.options.avatarId } : {},
435
- "X-Asiyst-SDK-Version": SDK_VERSION
435
+ "X-Asiyst-SDK-Version": SDK_VERSION,
436
+ ...req.authorizationToken ? { Authorization: `Bearer ${req.authorizationToken}` } : {}
436
437
  },
437
438
  body: req.body === void 0 ? void 0 : JSON.stringify(req.body),
438
439
  signal: req.signal
@@ -458,13 +459,14 @@ var HttpTransport = class {
458
459
 
459
460
  // src/communication/CloudClient.ts
460
461
  var CloudClient = class {
461
- constructor(transport, projectId, publicKey = "") {
462
+ constructor(transport, projectId, publicKey = "", runtimeAuth) {
462
463
  this.transport = transport;
463
464
  this.projectId = projectId;
464
465
  this.publicKey = publicKey;
466
+ this.runtimeAuth = runtimeAuth;
465
467
  }
466
468
  async fetchConfig() {
467
- const response = await this.transport.request({
469
+ const response = await this.runtimeRequest({
468
470
  path: `/projects/${encodeURIComponent(this.projectId)}/avatar`,
469
471
  method: "GET"
470
472
  });
@@ -477,7 +479,7 @@ var CloudClient = class {
477
479
  return normalizeProjectConfig(response.data.config ?? response.data);
478
480
  }
479
481
  async heartbeat(metadata) {
480
- const response = await this.transport.request({
482
+ const response = await this.runtimeRequest({
481
483
  path: "/sdk/heartbeat",
482
484
  method: "POST",
483
485
  body: {
@@ -488,7 +490,7 @@ var CloudClient = class {
488
490
  environment: metadata.environment,
489
491
  timestamp: metadata.timestamp
490
492
  }
491
- });
493
+ }, "assistant:heartbeat");
492
494
  const body = response.data && typeof response.data === "object" && !Array.isArray(response.data) ? response.data : void 0;
493
495
  const rawStatus = body?.status ?? body?.connectionStatus ?? body?.verificationStatus;
494
496
  const verificationStatus = rawStatus === "connected" || rawStatus === "inactive" || rawStatus === "not_detected" || rawStatus === "error" ? rawStatus : void 0;
@@ -498,8 +500,19 @@ var CloudClient = class {
498
500
  verificationStatus
499
501
  };
500
502
  }
501
- async requestTask(userText, pageUrl) {
503
+ async registerInstallation(registration) {
502
504
  const response = await this.transport.request({
505
+ path: "/sdk/installations/register",
506
+ method: "POST",
507
+ body: registration
508
+ });
509
+ if (!response.ok) {
510
+ throw new NetworkError(`SDK installation registration failed (${response.status}).`);
511
+ }
512
+ return response.data ?? {};
513
+ }
514
+ async requestTask(userText, pageUrl) {
515
+ const response = await this.runtimeRequest({
503
516
  path: "/tasks",
504
517
  method: "POST",
505
518
  body: {
@@ -507,28 +520,28 @@ var CloudClient = class {
507
520
  text: userText,
508
521
  pageUrl
509
522
  }
510
- });
523
+ }, "assistant:conversation");
511
524
  if (!response.ok || !response.data?.task?.id || !Array.isArray(response.data.task.steps)) {
512
525
  throw new NetworkError("Task planning is unavailable");
513
526
  }
514
527
  return response.data.task;
515
528
  }
516
529
  async fetchWorkflow(workflowId) {
517
- const response = await this.transport.request({
530
+ const response = await this.runtimeRequest({
518
531
  path: `/workflows/${encodeURIComponent(workflowId)}`,
519
532
  method: "GET"
520
- });
533
+ }, "assistant:conversation");
521
534
  if (!response.ok || !response.data?.workflow?.id || !Array.isArray(response.data.workflow.steps)) {
522
535
  throw new NetworkError("Workflow is unavailable");
523
536
  }
524
537
  return response.data.workflow;
525
538
  }
526
539
  async sendConversationMessage(text, pageUrl) {
527
- const response = await this.transport.request({
540
+ const response = await this.runtimeRequest({
528
541
  path: "/conversations/messages",
529
542
  method: "POST",
530
543
  body: { projectId: this.projectId, text, pageUrl }
531
- });
544
+ }, "assistant:conversation");
532
545
  if (!response.ok || !response.data?.message?.text) {
533
546
  throw new NetworkError("Conversation service is unavailable");
534
547
  }
@@ -548,10 +561,23 @@ var CloudClient = class {
548
561
  }
549
562
  async safePost(path, body) {
550
563
  try {
551
- await this.transport.request({ path, method: "POST", body });
564
+ await this.runtimeRequest({ path, method: "POST", body }, "assistant:telemetry");
552
565
  } catch {
553
566
  }
554
567
  }
568
+ async runtimeRequest(request, capability = "assistant:config") {
569
+ if (!this.runtimeAuth) {
570
+ return this.transport.request(request);
571
+ }
572
+ let token = await this.runtimeAuth.getToken(capability);
573
+ let response = await this.transport.request({ ...request, authorizationToken: token });
574
+ if (response.status === 401) {
575
+ this.runtimeAuth.invalidate();
576
+ token = await this.runtimeAuth.getToken(capability);
577
+ response = await this.transport.request({ ...request, authorizationToken: token });
578
+ }
579
+ return response;
580
+ }
555
581
  };
556
582
 
557
583
  // src/storage/NamespacedStorage.ts
@@ -1769,7 +1795,14 @@ var AvatarController = class {
1769
1795
 
1770
1796
  // src/interaction/permissions.ts
1771
1797
  function normalizeHost(host) {
1772
- return host.replace(/^https?:\/\//i, "").replace(/\/$/, "").toLowerCase();
1798
+ const candidate = host.trim();
1799
+ try {
1800
+ const parsed = new URL(/^[a-z][a-z\d+\-.]*:\/\//i.test(candidate) ? candidate : `https://${candidate}`);
1801
+ return (parsed.hostname ?? "").replace(/^www\./i, "").toLowerCase();
1802
+ } catch {
1803
+ const fallbackHost = candidate.replace(/^https?:\/\//i, "").split("/", 1)[0] ?? "";
1804
+ return fallbackHost.replace(/^www\./i, "").replace(/:\d+$/, "").toLowerCase();
1805
+ }
1773
1806
  }
1774
1807
  function matchesRoutePattern(pathname, pattern) {
1775
1808
  const candidate = pathname;
@@ -2362,6 +2395,134 @@ function withIsolation(fn) {
2362
2395
  }
2363
2396
  }
2364
2397
 
2398
+ // src/installation/Installation.ts
2399
+ var INSTALLATION_KEY = "installation_id";
2400
+ var INSTALLATION_ID_PATTERN = /^inst_[A-Za-z0-9][A-Za-z0-9_-]{7,127}$/;
2401
+ var memoryIds = /* @__PURE__ */ new Map();
2402
+ function randomInstallationId() {
2403
+ try {
2404
+ const cryptoApi = globalThis.crypto;
2405
+ if (typeof cryptoApi?.randomUUID === "function") {
2406
+ return `inst_${cryptoApi.randomUUID()}`;
2407
+ }
2408
+ if (typeof cryptoApi?.getRandomValues === "function") {
2409
+ const bytes = cryptoApi.getRandomValues(new Uint8Array(16));
2410
+ return `inst_${Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("")}`;
2411
+ }
2412
+ } catch {
2413
+ return void 0;
2414
+ }
2415
+ return void 0;
2416
+ }
2417
+ function loadOrCreateInstallationId(projectId) {
2418
+ const inMemory = memoryIds.get(projectId);
2419
+ if (inMemory) return inMemory;
2420
+ const storage = new NamespacedStorage(projectId, browserLocalStorage());
2421
+ const existing = storage.read(INSTALLATION_KEY)?.trim();
2422
+ if (existing && INSTALLATION_ID_PATTERN.test(existing)) {
2423
+ memoryIds.set(projectId, existing);
2424
+ return existing;
2425
+ }
2426
+ const installationId = randomInstallationId();
2427
+ if (!installationId) return void 0;
2428
+ memoryIds.set(projectId, installationId);
2429
+ storage.write(INSTALLATION_KEY, installationId);
2430
+ return installationId;
2431
+ }
2432
+
2433
+ // src/communication/RuntimeAuth.ts
2434
+ var RUNTIME_AUDIENCE = "asiyst-sdk-runtime";
2435
+ var RUNTIME_CAPABILITIES = [
2436
+ "assistant:config",
2437
+ "assistant:conversation",
2438
+ "assistant:telemetry",
2439
+ "assistant:heartbeat"
2440
+ ];
2441
+ var RuntimeAuth = class {
2442
+ constructor(options) {
2443
+ this.options = options;
2444
+ }
2445
+ async getToken(capability) {
2446
+ if (this.token && this.isUsable(this.token) && this.token.capabilities.has(capability)) {
2447
+ return this.token.value;
2448
+ }
2449
+ if (!this.requestInFlight) {
2450
+ this.requestInFlight = this.issueToken().finally(() => {
2451
+ this.requestInFlight = void 0;
2452
+ });
2453
+ }
2454
+ const token = await this.requestInFlight;
2455
+ if (!token.capabilities.has(capability)) {
2456
+ throw new AuthenticationError("ASIYST runtime authorization does not allow this operation.");
2457
+ }
2458
+ return token.value;
2459
+ }
2460
+ invalidate() {
2461
+ this.token = void 0;
2462
+ }
2463
+ isUsable(token) {
2464
+ return token.expiresAt - Date.now() > 3e4;
2465
+ }
2466
+ async issueToken() {
2467
+ const controller = new AbortController();
2468
+ const timeout = setTimeout(() => controller.abort(), 1e4);
2469
+ let response;
2470
+ try {
2471
+ response = await fetch(`${this.options.apiBaseUrl.replace(/\/$/, "")}/sdk/runtime/token`, {
2472
+ method: "POST",
2473
+ headers: {
2474
+ Accept: "application/json",
2475
+ "Content-Type": "application/json"
2476
+ },
2477
+ body: JSON.stringify({
2478
+ projectId: this.options.projectId,
2479
+ publicKey: this.options.publicKey,
2480
+ installationId: this.options.installationId,
2481
+ origin: this.options.origin,
2482
+ environment: this.options.environment,
2483
+ sdkVersion: SDK_VERSION,
2484
+ capabilities: [...RUNTIME_CAPABILITIES]
2485
+ }),
2486
+ signal: controller.signal
2487
+ });
2488
+ } catch {
2489
+ throw new NetworkError("ASIYST runtime authentication is unavailable.");
2490
+ } finally {
2491
+ clearTimeout(timeout);
2492
+ }
2493
+ let body;
2494
+ try {
2495
+ body = await response.json();
2496
+ } catch {
2497
+ body = void 0;
2498
+ }
2499
+ if (!response.ok) {
2500
+ if (response.status === 403) {
2501
+ throw new AuthenticationError("ASIYST runtime authorization was rejected.");
2502
+ }
2503
+ if (response.status === 429) {
2504
+ throw new NetworkError("ASIYST runtime authentication is rate limited.");
2505
+ }
2506
+ throw new NetworkError("ASIYST runtime authentication is unavailable.");
2507
+ }
2508
+ const data = body?.data;
2509
+ 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))) {
2510
+ throw new AuthenticationError("ASIYST returned an invalid runtime authorization response.");
2511
+ }
2512
+ const expiresAt = Date.parse(data.expiresAt);
2513
+ if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) {
2514
+ throw new AuthenticationError("ASIYST runtime authorization has expired.");
2515
+ }
2516
+ const token = {
2517
+ value: data.token,
2518
+ expiresAt,
2519
+ capabilities: new Set(data.capabilities)
2520
+ };
2521
+ this.token = token;
2522
+ return token;
2523
+ }
2524
+ };
2525
+
2365
2526
  // src/core/Runtime.ts
2366
2527
  var AsiystRuntime = class {
2367
2528
  constructor(options, doc, win) {
@@ -2376,13 +2537,24 @@ var AsiystRuntime = class {
2376
2537
  throw new InitializationError("document.body is not available");
2377
2538
  }
2378
2539
  this.options = options;
2540
+ this.installationId = loadOrCreateInstallationId(options.projectId);
2541
+ const isLocalOrigin = /^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i.test(win.location.hostname);
2542
+ this.environment = options.apiBaseUrl || isLocalOrigin ? "development" : "production";
2379
2543
  const transport = new HttpTransport({
2380
2544
  apiBaseUrl: options.apiBaseUrl ?? DEFAULT_API_BASE_URL,
2381
2545
  projectId: options.projectId,
2382
2546
  publicKey: options.publicKey,
2383
2547
  avatarId: options.avatarId
2384
2548
  });
2385
- this.cloud = new CloudClient(transport, options.projectId, options.publicKey);
2549
+ const runtimeAuth = this.installationId ? new RuntimeAuth({
2550
+ apiBaseUrl: options.apiBaseUrl ?? DEFAULT_API_BASE_URL,
2551
+ projectId: options.projectId,
2552
+ publicKey: options.publicKey,
2553
+ installationId: this.installationId,
2554
+ origin: win.location.origin,
2555
+ environment: this.environment
2556
+ }) : void 0;
2557
+ this.cloud = new CloudClient(transport, options.projectId, options.publicKey, runtimeAuth);
2386
2558
  this.config = new ConfigManager(options, this.cloud, this.events);
2387
2559
  this.analytics = new Analytics(options.projectId, this.cloud);
2388
2560
  this.host = new HostRoot(doc);
@@ -2449,10 +2621,11 @@ var AsiystRuntime = class {
2449
2621
  }
2450
2622
  this.avatar.applyConfig(cfg);
2451
2623
  this.avatar.show();
2624
+ await this.registerInstallation();
2452
2625
  try {
2453
2626
  const heartbeat = await this.cloud.heartbeat({
2454
2627
  origin: window.location.origin,
2455
- environment: this.options.apiBaseUrl ? "development" : "production",
2628
+ environment: this.environment,
2456
2629
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
2457
2630
  });
2458
2631
  this.connectionStatus = heartbeat.ok ? "connected" : "disconnected";
@@ -2524,6 +2697,38 @@ var AsiystRuntime = class {
2524
2697
  this.events.removeAll();
2525
2698
  await this.analytics.destroy();
2526
2699
  }
2700
+ async registerInstallation() {
2701
+ const origin = window.location.origin;
2702
+ const environment = this.environment;
2703
+ const installationId = this.installationId;
2704
+ if (!installationId) {
2705
+ if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
2706
+ console.debug("[asiyst] SDK installation identity is unavailable; registration skipped.");
2707
+ }
2708
+ return;
2709
+ }
2710
+ for (let attempt = 0; attempt < 2; attempt += 1) {
2711
+ try {
2712
+ await this.cloud.registerInstallation({
2713
+ project_id: this.options.projectId,
2714
+ public_key: this.options.publicKey,
2715
+ installation_id: installationId,
2716
+ origin,
2717
+ environment,
2718
+ sdk_version: SDK_VERSION
2719
+ });
2720
+ return;
2721
+ } catch (error) {
2722
+ if (attempt === 1) {
2723
+ if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
2724
+ console.debug("[asiyst] SDK installation registration failed.", error);
2725
+ }
2726
+ return;
2727
+ }
2728
+ await new Promise((resolve) => setTimeout(resolve, 250));
2729
+ }
2730
+ }
2731
+ }
2527
2732
  rescan() {
2528
2733
  withIsolation(() => {
2529
2734
  const doc = this.host.host.ownerDocument;