@alva-ai/toolkit 0.11.3-beta.0 → 0.12.1-beta.0

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
@@ -2,15 +2,56 @@
2
2
  var AlvaError = class extends Error {
3
3
  code;
4
4
  status;
5
- constructor(code, message, status) {
5
+ details;
6
+ constructor(code, message, status, details) {
6
7
  super(message);
7
8
  this.name = "AlvaError";
8
9
  this.code = code;
9
10
  this.status = status;
11
+ this.details = details;
10
12
  }
11
13
  };
12
14
 
13
15
  // src/resources/fs.ts
16
+ function isValidUtf8(bytes) {
17
+ let i = 0;
18
+ while (i < bytes.length) {
19
+ const byte = bytes[i];
20
+ if (byte <= 127) {
21
+ i += 1;
22
+ continue;
23
+ }
24
+ let needed = 0;
25
+ let minCodePoint = 0;
26
+ let codePoint = 0;
27
+ if (byte >= 194 && byte <= 223) {
28
+ needed = 1;
29
+ minCodePoint = 128;
30
+ codePoint = byte & 31;
31
+ } else if (byte >= 224 && byte <= 239) {
32
+ needed = 2;
33
+ minCodePoint = 2048;
34
+ codePoint = byte & 15;
35
+ } else if (byte >= 240 && byte <= 244) {
36
+ needed = 3;
37
+ minCodePoint = 65536;
38
+ codePoint = byte & 7;
39
+ } else {
40
+ return false;
41
+ }
42
+ if (i + needed >= bytes.length) return false;
43
+ for (let j = 1; j <= needed; j += 1) {
44
+ const next = bytes[i + j];
45
+ if ((next & 192) !== 128) return false;
46
+ codePoint = codePoint << 6 | next & 63;
47
+ }
48
+ if (codePoint < minCodePoint || codePoint > 1114111 || codePoint >= 55296 && codePoint <= 57343) {
49
+ return false;
50
+ }
51
+ i += needed + 1;
52
+ }
53
+ return true;
54
+ }
14
55
  var FsResource = class {
15
56
  constructor(client) {
16
57
  this.client = client;
@@ -22,15 +63,14 @@ var FsResource = class {
22
63
  query: { path: params.path, offset: params.offset, size: params.size }
23
64
  });
24
65
  if (!(result instanceof ArrayBuffer)) return result;
66
+ if (!isValidUtf8(new Uint8Array(result))) {
67
+ return result;
68
+ }
69
+ const text = new TextDecoder("utf-8").decode(result);
25
70
  try {
26
- const text = new TextDecoder("utf-8", { fatal: true }).decode(result);
27
- try {
28
- return JSON.parse(text);
29
- } catch {
30
- return text;
31
- }
71
+ return JSON.parse(text);
32
72
  } catch {
33
- return result;
73
+ return text;
34
74
  }
35
75
  }
36
76
  /** Write file using JSON body (Mode 2). For text content. */
@@ -149,7 +189,8 @@ var RunResource = class {
149
189
  working_dir: params.working_dir,
150
190
  args: params.args,
151
191
  max_heap_size_mb: params.max_heap_size_mb
152
- }
192
+ },
193
+ timeoutMs: params.timeout_ms
153
194
  });
154
195
  }
155
196
  };
@@ -364,6 +405,69 @@ var PlaybooksResource = class {
364
405
  this.client = client;
365
406
  }
366
407
  client;
408
+ /**
409
+ * Resolve playbook ids to named, addressable records (mono-meta#584 A2).
410
+ * Visibility-gated server-side; ids the caller cannot see — and DELETED
411
+ * playbook ids — return no row. Treat a missing id as "deleted or not
412
+ * visible" (the subscriptions list's `target_status` distinguishes ghosts).
413
+ * Ids are strings (snowflake-safe). Max 100 per call.
414
+ *
415
+ * Auth is optional (like `trending`): with an API key, private/paid
416
+ * visibility is evaluated for the caller; without one, only public
417
+ * playbooks resolve. The server decides — no client-side gate.
418
+ */
419
+ async getByIds(ids) {
420
+ return await this.client._request("GET", "/api/v1/playbooks", {
421
+ query: { ids: ids.join(",") }
422
+ });
423
+ }
424
+ /**
425
+ * List a user's playbooks by owner username (mono-meta#584 C10).
426
+ * Visibility-gated: another user's private playbooks are omitted.
427
+ * Auth is optional (like `trending`); without credentials only public
428
+ * playbooks are listed.
429
+ */
430
+ async listByOwner(params) {
431
+ const query = { owner: params.owner };
432
+ if (params.limit !== void 0 && params.limit > 0) {
433
+ query.limit = String(params.limit);
434
+ }
435
+ if (params.cursor) query.cursor = params.cursor;
436
+ return await this.client._request("GET", "/api/v1/playbooks", {
437
+ query
438
+ });
439
+ }
440
+ /**
441
+ * Get one playbook by numeric id or by "owner/name" ref. Returns null when
442
+ * not found / not visible / deleted.
443
+ */
444
+ async get(params) {
445
+ if (params.id) {
446
+ const resp = await this.getByIds([params.id]);
447
+ return resp.items[0] ?? null;
448
+ }
449
+ if (params.ref) {
450
+ const slash = params.ref.indexOf("/");
451
+ if (slash <= 0 || slash === params.ref.length - 1) {
452
+ throw new AlvaError(
453
+ "INVALID_ARGUMENT",
454
+ `Invalid ref "${params.ref}". Expected "owner/name".`,
455
+ 400
456
+ );
457
+ }
458
+ const owner = params.ref.slice(0, slash);
459
+ const name = params.ref.slice(slash + 1);
460
+ let cursor;
461
+ for (; ; ) {
462
+ const page = await this.listByOwner({ owner, cursor, limit: 100 });
463
+ const hit = page.items.find((item) => item.name === name);
464
+ if (hit) return hit;
465
+ if (!page.has_next || !page.next_cursor) return null;
466
+ cursor = page.next_cursor;
467
+ }
468
+ }
469
+ throw new AlvaError("INVALID_ARGUMENT", "id or ref is required", 400);
470
+ }
367
471
  /**
368
472
  * List trending / searchable playbooks. Auth is optional: when the client
369
473
  * has an API key it is forwarded, otherwise this uses the public surface.
@@ -2149,6 +2253,42 @@ var SubscriptionsResource = class {
2149
2253
  query
2150
2254
  });
2151
2255
  }
2256
+ /**
2257
+ * List the playbooks the caller FOLLOWS (the social relation — the UI's
2258
+ * "Subscribed Playbooks"). Rows carry the playbook identity; follows of
2259
+ * deleted playbooks are filtered server-side. Cursor-paginated.
2260
+ */
2261
+ async follows(params = {}) {
2262
+ this.client._requireAuth();
2263
+ const query = {};
2264
+ if (params.limit !== void 0 && params.limit > 0) {
2265
+ query.limit = String(params.limit);
2266
+ }
2267
+ if (params.cursor) query.cursor = params.cursor;
2268
+ return this.client._request("GET", "/api/v1/me/follows", {
2269
+ query
2270
+ });
2271
+ }
2272
+ /**
2273
+ * Disable alerts for many playbook/feed targets BY TARGET ID in one
2274
+ * idempotent call (max 100 ids). Ids are strings (snowflake-safe). Works
2275
+ * for ghost rows (deleted targets) because no name resolution happens —
2276
+ * the per-id results report `INVALID_ID` for malformed entries while
2277
+ * valid ones proceed. Safe to re-run: already-gone rows are no-ops.
2278
+ */
2279
+ async unsubscribeBatch(params) {
2280
+ this.client._requireAuth();
2281
+ return this.client._request(
2282
+ "POST",
2283
+ "/api/v1/subscriptions/unsubscribe-batch",
2284
+ {
2285
+ body: {
2286
+ playbook_ids: params.playbookIds ?? [],
2287
+ feed_ids: params.feedIds ?? []
2288
+ }
2289
+ }
2290
+ );
2291
+ }
2152
2292
  };
2153
2293
 
2154
2294
  // src/resources/channelGroupSubscriptions.ts
@@ -2385,6 +2525,62 @@ function parseResultPayload(result) {
2385
2525
  // src/client.ts
2386
2526
  var DEFAULT_BASE_URL = "https://api-llm.prd.alva.ai";
2387
2527
  var DEFAULT_ARRAYS_BASE_URL = "https://data-tools.prd.space.id";
2528
+ function isRecord(value) {
2529
+ return typeof value === "object" && value !== null;
2530
+ }
2531
+ function stringField(value, field) {
2532
+ if (!isRecord(value)) return void 0;
2533
+ const fieldValue = value[field];
2534
+ return typeof fieldValue === "string" && fieldValue ? fieldValue : void 0;
2535
+ }
2536
+ function describeCause(cause) {
2537
+ if (cause === void 0 || cause === null) {
2538
+ return {};
2539
+ }
2540
+ const details = {};
2541
+ if (cause instanceof Error) {
2542
+ if (cause.name) details.name = cause.name;
2543
+ if (cause.message) details.message = cause.message;
2544
+ const code = stringField(cause, "code");
2545
+ if (code) details.code = code;
2546
+ } else if (isRecord(cause)) {
2547
+ const code = stringField(cause, "code");
2548
+ const name = stringField(cause, "name");
2549
+ const message = stringField(cause, "message");
2550
+ if (code) details.code = code;
2551
+ if (name) details.name = name;
2552
+ if (message) details.message = message;
2553
+ } else {
2554
+ details.message = String(cause);
2555
+ }
2556
+ const parts = [details.code, details.name, details.message].filter(
2557
+ (part) => Boolean(part)
2558
+ );
2559
+ return {
2560
+ message: parts.length > 0 ? parts.join(": ") : void 0,
2561
+ details: Object.keys(details).length > 0 ? details : void 0
2562
+ };
2563
+ }
2564
+ function describeFetchFailure(err) {
2565
+ const message = err instanceof Error && err.message ? err.message : "Network request failed";
2566
+ const details = {};
2567
+ if (err instanceof Error) {
2568
+ details.name = err.name;
2569
+ details.message = err.message;
2570
+ } else {
2571
+ details.message = String(err);
2572
+ }
2573
+ const { message: causeMessage, details: causeDetails } = describeCause(
2574
+ isRecord(err) ? err.cause : void 0
2575
+ );
2576
+ if (causeDetails) {
2577
+ details.cause = causeDetails;
2578
+ }
2579
+ return {
2580
+ message: causeMessage ? `${message}; cause: ${causeMessage}` : message,
2581
+ details
2582
+ };
2583
+ }
2388
2584
  var AlvaClient = class {
2389
2585
  baseUrl;
2390
2586
  arraysBaseUrl;
@@ -2394,6 +2590,16 @@ var AlvaClient = class {
2394
2590
  gaClientId;
2395
2591
  gaSessionId;
2396
2592
  utmParams;
2593
+ signal;
2594
+ /**
2595
+ * Alva chat session that owns work produced through this client (playbooks,
2596
+ * feeds, uploaded files). Forwarded as `X-Alva-Origin-Session-Id` so the
2597
+ * backend can attribute created artifacts to the originating session. This
2598
+ * is a request-context hint, NOT auth — the backend still verifies the
2599
+ * session belongs to the authenticated user before honoring it. Distinct
2600
+ * from `gaSessionId` (browser analytics).
2601
+ */
2602
+ originSessionId;
2397
2603
  _fs;
2398
2604
  _run;
2399
2605
  _deploy;
@@ -2426,6 +2632,8 @@ var AlvaClient = class {
2426
2632
  this.gaClientId = config.gaClientId;
2427
2633
  this.gaSessionId = config.gaSessionId;
2428
2634
  this.utmParams = config.utmParams;
2635
+ this.signal = config.signal;
2636
+ this.originSessionId = config.originSessionId;
2429
2637
  }
2430
2638
  get fs() {
2431
2639
  return this._fs ??= new FsResource(this);
@@ -2540,6 +2748,9 @@ var AlvaClient = class {
2540
2748
  if (this.utmParams) {
2541
2749
  headers["X-Alva-UTM-Params"] = this.utmParams;
2542
2750
  }
2751
+ if (this.originSessionId && !options?.noAuth) {
2752
+ headers["X-Alva-Origin-Session-Id"] = this.originSessionId;
2753
+ }
2543
2754
  let fetchBody;
2544
2755
  if (options?.rawBody !== void 0) {
2545
2756
  headers["Content-Type"] = "application/octet-stream";
@@ -2552,21 +2763,89 @@ var AlvaClient = class {
2552
2763
  fetchBody = JSON.stringify(options.body);
2553
2764
  }
2554
2765
  let response;
2766
+ const timeoutMs = options?.timeoutMs;
2767
+ const externalSignal = options?.signal ?? this.signal;
2768
+ if (externalSignal?.aborted) {
2769
+ throw new AlvaError(
2770
+ "NETWORK_ABORTED",
2771
+ `Request aborted while calling ${method} ${path}`,
2772
+ 0,
2773
+ {
2774
+ method,
2775
+ path
2776
+ }
2777
+ );
2778
+ }
2779
+ const controller = timeoutMs !== void 0 ? new AbortController() : void 0;
2780
+ let didTimeout = false;
2781
+ let timeoutId;
2782
+ let abortListener;
2783
+ if (controller && timeoutMs !== void 0) {
2784
+ if (externalSignal) {
2785
+ abortListener = () => controller.abort(externalSignal.reason);
2786
+ externalSignal.addEventListener("abort", abortListener, { once: true });
2787
+ }
2788
+ timeoutId = setTimeout(() => {
2789
+ didTimeout = true;
2790
+ controller.abort(
2791
+ new Error(
2792
+ `Request timed out after ${timeoutMs}ms while calling ${method} ${path}`
2793
+ )
2794
+ );
2795
+ }, timeoutMs);
2796
+ }
2797
+ const fetchInit = {
2798
+ method,
2799
+ headers,
2800
+ body: fetchBody,
2801
+ signal: controller?.signal ?? externalSignal
2802
+ };
2803
+ if (timeoutMs !== void 0) {
2804
+ fetchInit.timeout = timeoutMs;
2805
+ }
2555
2806
  try {
2556
- response = await fetch(url, {
2807
+ response = await fetch(url, fetchInit);
2808
+ } catch (err) {
2809
+ if (externalSignal?.aborted && !didTimeout) {
2810
+ throw new AlvaError(
2811
+ "NETWORK_ABORTED",
2812
+ `Request aborted while calling ${method} ${path}`,
2813
+ 0,
2814
+ {
2815
+ method,
2816
+ path
2817
+ }
2818
+ );
2819
+ }
2820
+ if (didTimeout) {
2821
+ throw new AlvaError(
2822
+ "NETWORK_TIMEOUT",
2823
+ `Request timed out after ${timeoutMs}ms while calling ${method} ${path}`,
2824
+ 0,
2825
+ { method, path, timeout_ms: timeoutMs }
2826
+ );
2827
+ }
2828
+ const failure = describeFetchFailure(err);
2829
+ throw new AlvaError("NETWORK_ERROR", failure.message, 0, {
2557
2830
  method,
2558
- headers,
2559
- body: fetchBody
2831
+ path,
2832
+ ...failure.details
2560
2833
  });
2561
- } catch (err) {
2562
- throw new AlvaError(
2563
- "NETWORK_ERROR",
2564
- err instanceof Error ? err.message : "Network request failed",
2565
- 0
2566
- );
2834
+ } finally {
2835
+ if (abortListener && externalSignal) {
2836
+ externalSignal.removeEventListener("abort", abortListener);
2837
+ }
2838
+ if (timeoutId !== void 0) {
2839
+ clearTimeout(timeoutId);
2840
+ }
2567
2841
  }
2568
2842
  if (!response.ok) {
2569
- const bodyText = await response.text().catch(() => "");
2843
+ let bodyText = "";
2844
+ try {
2845
+ bodyText = await Promise.resolve(response.text());
2846
+ } catch {
2847
+ bodyText = "";
2848
+ }
2570
2849
  const contentType2 = response.headers.get("content-type") ?? "";
2571
2850
  if (contentType2.includes("application/json") && bodyText) {
2572
2851
  try {
@@ -3026,7 +3305,7 @@ var installPlaybookRuntime = (targetWindow) => {
3026
3305
  };
3027
3306
 
3028
3307
  // src/index.ts
3029
- var VERSION = true ? "0.11.3-beta.0" : "dev";
3308
+ var VERSION = true ? "0.12.1-beta.0" : "dev";
3030
3309
  export {
3031
3310
  AlvaClient,
3032
3311
  AlvaError,