@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.cjs CHANGED
@@ -56,15 +56,56 @@ module.exports = __toCommonJS(src_exports);
56
56
  var AlvaError = class extends Error {
57
57
  code;
58
58
  status;
59
- constructor(code, message, status) {
59
+ details;
60
+ constructor(code, message, status, details) {
60
61
  super(message);
61
62
  this.name = "AlvaError";
62
63
  this.code = code;
63
64
  this.status = status;
65
+ this.details = details;
64
66
  }
65
67
  };
66
68
 
67
69
  // src/resources/fs.ts
70
+ function isValidUtf8(bytes) {
71
+ let i = 0;
72
+ while (i < bytes.length) {
73
+ const byte = bytes[i];
74
+ if (byte <= 127) {
75
+ i += 1;
76
+ continue;
77
+ }
78
+ let needed = 0;
79
+ let minCodePoint = 0;
80
+ let codePoint = 0;
81
+ if (byte >= 194 && byte <= 223) {
82
+ needed = 1;
83
+ minCodePoint = 128;
84
+ codePoint = byte & 31;
85
+ } else if (byte >= 224 && byte <= 239) {
86
+ needed = 2;
87
+ minCodePoint = 2048;
88
+ codePoint = byte & 15;
89
+ } else if (byte >= 240 && byte <= 244) {
90
+ needed = 3;
91
+ minCodePoint = 65536;
92
+ codePoint = byte & 7;
93
+ } else {
94
+ return false;
95
+ }
96
+ if (i + needed >= bytes.length) return false;
97
+ for (let j = 1; j <= needed; j += 1) {
98
+ const next = bytes[i + j];
99
+ if ((next & 192) !== 128) return false;
100
+ codePoint = codePoint << 6 | next & 63;
101
+ }
102
+ if (codePoint < minCodePoint || codePoint > 1114111 || codePoint >= 55296 && codePoint <= 57343) {
103
+ return false;
104
+ }
105
+ i += needed + 1;
106
+ }
107
+ return true;
108
+ }
68
109
  var FsResource = class {
69
110
  constructor(client) {
70
111
  this.client = client;
@@ -76,15 +117,14 @@ var FsResource = class {
76
117
  query: { path: params.path, offset: params.offset, size: params.size }
77
118
  });
78
119
  if (!(result instanceof ArrayBuffer)) return result;
120
+ if (!isValidUtf8(new Uint8Array(result))) {
121
+ return result;
122
+ }
123
+ const text = new TextDecoder("utf-8").decode(result);
79
124
  try {
80
- const text = new TextDecoder("utf-8", { fatal: true }).decode(result);
81
- try {
82
- return JSON.parse(text);
83
- } catch {
84
- return text;
85
- }
125
+ return JSON.parse(text);
86
126
  } catch {
87
- return result;
127
+ return text;
88
128
  }
89
129
  }
90
130
  /** Write file using JSON body (Mode 2). For text content. */
@@ -203,7 +243,8 @@ var RunResource = class {
203
243
  working_dir: params.working_dir,
204
244
  args: params.args,
205
245
  max_heap_size_mb: params.max_heap_size_mb
206
- }
246
+ },
247
+ timeoutMs: params.timeout_ms
207
248
  });
208
249
  }
209
250
  };
@@ -418,6 +459,69 @@ var PlaybooksResource = class {
418
459
  this.client = client;
419
460
  }
420
461
  client;
462
+ /**
463
+ * Resolve playbook ids to named, addressable records (mono-meta#584 A2).
464
+ * Visibility-gated server-side; ids the caller cannot see — and DELETED
465
+ * playbook ids — return no row. Treat a missing id as "deleted or not
466
+ * visible" (the subscriptions list's `target_status` distinguishes ghosts).
467
+ * Ids are strings (snowflake-safe). Max 100 per call.
468
+ *
469
+ * Auth is optional (like `trending`): with an API key, private/paid
470
+ * visibility is evaluated for the caller; without one, only public
471
+ * playbooks resolve. The server decides — no client-side gate.
472
+ */
473
+ async getByIds(ids) {
474
+ return await this.client._request("GET", "/api/v1/playbooks", {
475
+ query: { ids: ids.join(",") }
476
+ });
477
+ }
478
+ /**
479
+ * List a user's playbooks by owner username (mono-meta#584 C10).
480
+ * Visibility-gated: another user's private playbooks are omitted.
481
+ * Auth is optional (like `trending`); without credentials only public
482
+ * playbooks are listed.
483
+ */
484
+ async listByOwner(params) {
485
+ const query = { owner: params.owner };
486
+ if (params.limit !== void 0 && params.limit > 0) {
487
+ query.limit = String(params.limit);
488
+ }
489
+ if (params.cursor) query.cursor = params.cursor;
490
+ return await this.client._request("GET", "/api/v1/playbooks", {
491
+ query
492
+ });
493
+ }
494
+ /**
495
+ * Get one playbook by numeric id or by "owner/name" ref. Returns null when
496
+ * not found / not visible / deleted.
497
+ */
498
+ async get(params) {
499
+ if (params.id) {
500
+ const resp = await this.getByIds([params.id]);
501
+ return resp.items[0] ?? null;
502
+ }
503
+ if (params.ref) {
504
+ const slash = params.ref.indexOf("/");
505
+ if (slash <= 0 || slash === params.ref.length - 1) {
506
+ throw new AlvaError(
507
+ "INVALID_ARGUMENT",
508
+ `Invalid ref "${params.ref}". Expected "owner/name".`,
509
+ 400
510
+ );
511
+ }
512
+ const owner = params.ref.slice(0, slash);
513
+ const name = params.ref.slice(slash + 1);
514
+ let cursor;
515
+ for (; ; ) {
516
+ const page = await this.listByOwner({ owner, cursor, limit: 100 });
517
+ const hit = page.items.find((item) => item.name === name);
518
+ if (hit) return hit;
519
+ if (!page.has_next || !page.next_cursor) return null;
520
+ cursor = page.next_cursor;
521
+ }
522
+ }
523
+ throw new AlvaError("INVALID_ARGUMENT", "id or ref is required", 400);
524
+ }
421
525
  /**
422
526
  * List trending / searchable playbooks. Auth is optional: when the client
423
527
  * has an API key it is forwarded, otherwise this uses the public surface.
@@ -2203,6 +2307,42 @@ var SubscriptionsResource = class {
2203
2307
  query
2204
2308
  });
2205
2309
  }
2310
+ /**
2311
+ * List the playbooks the caller FOLLOWS (the social relation — the UI's
2312
+ * "Subscribed Playbooks"). Rows carry the playbook identity; follows of
2313
+ * deleted playbooks are filtered server-side. Cursor-paginated.
2314
+ */
2315
+ async follows(params = {}) {
2316
+ this.client._requireAuth();
2317
+ const query = {};
2318
+ if (params.limit !== void 0 && params.limit > 0) {
2319
+ query.limit = String(params.limit);
2320
+ }
2321
+ if (params.cursor) query.cursor = params.cursor;
2322
+ return this.client._request("GET", "/api/v1/me/follows", {
2323
+ query
2324
+ });
2325
+ }
2326
+ /**
2327
+ * Disable alerts for many playbook/feed targets BY TARGET ID in one
2328
+ * idempotent call (max 100 ids). Ids are strings (snowflake-safe). Works
2329
+ * for ghost rows (deleted targets) because no name resolution happens —
2330
+ * the per-id results report `INVALID_ID` for malformed entries while
2331
+ * valid ones proceed. Safe to re-run: already-gone rows are no-ops.
2332
+ */
2333
+ async unsubscribeBatch(params) {
2334
+ this.client._requireAuth();
2335
+ return this.client._request(
2336
+ "POST",
2337
+ "/api/v1/subscriptions/unsubscribe-batch",
2338
+ {
2339
+ body: {
2340
+ playbook_ids: params.playbookIds ?? [],
2341
+ feed_ids: params.feedIds ?? []
2342
+ }
2343
+ }
2344
+ );
2345
+ }
2206
2346
  };
2207
2347
 
2208
2348
  // src/resources/channelGroupSubscriptions.ts
@@ -2439,6 +2579,62 @@ function parseResultPayload(result) {
2439
2579
  // src/client.ts
2440
2580
  var DEFAULT_BASE_URL = "https://api-llm.prd.alva.ai";
2441
2581
  var DEFAULT_ARRAYS_BASE_URL = "https://data-tools.prd.space.id";
2582
+ function isRecord(value) {
2583
+ return typeof value === "object" && value !== null;
2584
+ }
2585
+ function stringField(value, field) {
2586
+ if (!isRecord(value)) return void 0;
2587
+ const fieldValue = value[field];
2588
+ return typeof fieldValue === "string" && fieldValue ? fieldValue : void 0;
2589
+ }
2590
+ function describeCause(cause) {
2591
+ if (cause === void 0 || cause === null) {
2592
+ return {};
2593
+ }
2594
+ const details = {};
2595
+ if (cause instanceof Error) {
2596
+ if (cause.name) details.name = cause.name;
2597
+ if (cause.message) details.message = cause.message;
2598
+ const code = stringField(cause, "code");
2599
+ if (code) details.code = code;
2600
+ } else if (isRecord(cause)) {
2601
+ const code = stringField(cause, "code");
2602
+ const name = stringField(cause, "name");
2603
+ const message = stringField(cause, "message");
2604
+ if (code) details.code = code;
2605
+ if (name) details.name = name;
2606
+ if (message) details.message = message;
2607
+ } else {
2608
+ details.message = String(cause);
2609
+ }
2610
+ const parts = [details.code, details.name, details.message].filter(
2611
+ (part) => Boolean(part)
2612
+ );
2613
+ return {
2614
+ message: parts.length > 0 ? parts.join(": ") : void 0,
2615
+ details: Object.keys(details).length > 0 ? details : void 0
2616
+ };
2617
+ }
2618
+ function describeFetchFailure(err) {
2619
+ const message = err instanceof Error && err.message ? err.message : "Network request failed";
2620
+ const details = {};
2621
+ if (err instanceof Error) {
2622
+ details.name = err.name;
2623
+ details.message = err.message;
2624
+ } else {
2625
+ details.message = String(err);
2626
+ }
2627
+ const { message: causeMessage, details: causeDetails } = describeCause(
2628
+ isRecord(err) ? err.cause : void 0
2629
+ );
2630
+ if (causeDetails) {
2631
+ details.cause = causeDetails;
2632
+ }
2633
+ return {
2634
+ message: causeMessage ? `${message}; cause: ${causeMessage}` : message,
2635
+ details
2636
+ };
2637
+ }
2442
2638
  var AlvaClient = class {
2443
2639
  baseUrl;
2444
2640
  arraysBaseUrl;
@@ -2448,6 +2644,16 @@ var AlvaClient = class {
2448
2644
  gaClientId;
2449
2645
  gaSessionId;
2450
2646
  utmParams;
2647
+ signal;
2648
+ /**
2649
+ * Alva chat session that owns work produced through this client (playbooks,
2650
+ * feeds, uploaded files). Forwarded as `X-Alva-Origin-Session-Id` so the
2651
+ * backend can attribute created artifacts to the originating session. This
2652
+ * is a request-context hint, NOT auth — the backend still verifies the
2653
+ * session belongs to the authenticated user before honoring it. Distinct
2654
+ * from `gaSessionId` (browser analytics).
2655
+ */
2656
+ originSessionId;
2451
2657
  _fs;
2452
2658
  _run;
2453
2659
  _deploy;
@@ -2480,6 +2686,8 @@ var AlvaClient = class {
2480
2686
  this.gaClientId = config.gaClientId;
2481
2687
  this.gaSessionId = config.gaSessionId;
2482
2688
  this.utmParams = config.utmParams;
2689
+ this.signal = config.signal;
2690
+ this.originSessionId = config.originSessionId;
2483
2691
  }
2484
2692
  get fs() {
2485
2693
  return this._fs ??= new FsResource(this);
@@ -2594,6 +2802,9 @@ var AlvaClient = class {
2594
2802
  if (this.utmParams) {
2595
2803
  headers["X-Alva-UTM-Params"] = this.utmParams;
2596
2804
  }
2805
+ if (this.originSessionId && !options?.noAuth) {
2806
+ headers["X-Alva-Origin-Session-Id"] = this.originSessionId;
2807
+ }
2597
2808
  let fetchBody;
2598
2809
  if (options?.rawBody !== void 0) {
2599
2810
  headers["Content-Type"] = "application/octet-stream";
@@ -2606,21 +2817,89 @@ var AlvaClient = class {
2606
2817
  fetchBody = JSON.stringify(options.body);
2607
2818
  }
2608
2819
  let response;
2820
+ const timeoutMs = options?.timeoutMs;
2821
+ const externalSignal = options?.signal ?? this.signal;
2822
+ if (externalSignal?.aborted) {
2823
+ throw new AlvaError(
2824
+ "NETWORK_ABORTED",
2825
+ `Request aborted while calling ${method} ${path}`,
2826
+ 0,
2827
+ {
2828
+ method,
2829
+ path
2830
+ }
2831
+ );
2832
+ }
2833
+ const controller = timeoutMs !== void 0 ? new AbortController() : void 0;
2834
+ let didTimeout = false;
2835
+ let timeoutId;
2836
+ let abortListener;
2837
+ if (controller && timeoutMs !== void 0) {
2838
+ if (externalSignal) {
2839
+ abortListener = () => controller.abort(externalSignal.reason);
2840
+ externalSignal.addEventListener("abort", abortListener, { once: true });
2841
+ }
2842
+ timeoutId = setTimeout(() => {
2843
+ didTimeout = true;
2844
+ controller.abort(
2845
+ new Error(
2846
+ `Request timed out after ${timeoutMs}ms while calling ${method} ${path}`
2847
+ )
2848
+ );
2849
+ }, timeoutMs);
2850
+ }
2851
+ const fetchInit = {
2852
+ method,
2853
+ headers,
2854
+ body: fetchBody,
2855
+ signal: controller?.signal ?? externalSignal
2856
+ };
2857
+ if (timeoutMs !== void 0) {
2858
+ fetchInit.timeout = timeoutMs;
2859
+ }
2609
2860
  try {
2610
- response = await fetch(url, {
2861
+ response = await fetch(url, fetchInit);
2862
+ } catch (err) {
2863
+ if (externalSignal?.aborted && !didTimeout) {
2864
+ throw new AlvaError(
2865
+ "NETWORK_ABORTED",
2866
+ `Request aborted while calling ${method} ${path}`,
2867
+ 0,
2868
+ {
2869
+ method,
2870
+ path
2871
+ }
2872
+ );
2873
+ }
2874
+ if (didTimeout) {
2875
+ throw new AlvaError(
2876
+ "NETWORK_TIMEOUT",
2877
+ `Request timed out after ${timeoutMs}ms while calling ${method} ${path}`,
2878
+ 0,
2879
+ { method, path, timeout_ms: timeoutMs }
2880
+ );
2881
+ }
2882
+ const failure = describeFetchFailure(err);
2883
+ throw new AlvaError("NETWORK_ERROR", failure.message, 0, {
2611
2884
  method,
2612
- headers,
2613
- body: fetchBody
2885
+ path,
2886
+ ...failure.details
2614
2887
  });
2615
- } catch (err) {
2616
- throw new AlvaError(
2617
- "NETWORK_ERROR",
2618
- err instanceof Error ? err.message : "Network request failed",
2619
- 0
2620
- );
2888
+ } finally {
2889
+ if (abortListener && externalSignal) {
2890
+ externalSignal.removeEventListener("abort", abortListener);
2891
+ }
2892
+ if (timeoutId !== void 0) {
2893
+ clearTimeout(timeoutId);
2894
+ }
2621
2895
  }
2622
2896
  if (!response.ok) {
2623
- const bodyText = await response.text().catch(() => "");
2897
+ let bodyText = "";
2898
+ try {
2899
+ bodyText = await Promise.resolve(response.text());
2900
+ } catch {
2901
+ bodyText = "";
2902
+ }
2624
2903
  const contentType2 = response.headers.get("content-type") ?? "";
2625
2904
  if (contentType2.includes("application/json") && bodyText) {
2626
2905
  try {
@@ -3080,7 +3359,7 @@ var installPlaybookRuntime = (targetWindow) => {
3080
3359
  };
3081
3360
 
3082
3361
  // src/index.ts
3083
- var VERSION = true ? "0.11.3-beta.0" : "dev";
3362
+ var VERSION = true ? "0.12.1-beta.0" : "dev";
3084
3363
  // Annotate the CommonJS export names for ESM import in node:
3085
3364
  0 && (module.exports = {
3086
3365
  AlvaClient,