@alva-ai/toolkit 0.23.1 → 0.25.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
@@ -23,6 +23,7 @@ __export(src_exports, {
23
23
  AlertsResource: () => AlertsResource,
24
24
  AlvaClient: () => AlvaClient,
25
25
  AlvaError: () => AlvaError,
26
+ AutomationAlertDeliveryResource: () => AutomationAlertDeliveryResource,
26
27
  AutomationResource: () => AutomationResource,
27
28
  CliUsageError: () => CliUsageError,
28
29
  MarketsResource: () => MarketsResource,
@@ -249,6 +250,134 @@ var FsResource = class {
249
250
  }
250
251
  };
251
252
 
253
+ // src/jsonPayload.ts
254
+ var MAX_SAFE_INTEGER_DIGITS = "9007199254740991";
255
+ function scaledIntegerGreater(left, leftTrailingZeros, right, rightTrailingZeros) {
256
+ const leftLength = left.length + leftTrailingZeros;
257
+ const rightLength = right.length + rightTrailingZeros;
258
+ if (leftLength !== rightLength) return leftLength > rightLength;
259
+ for (let index = 0; index < leftLength; index++) {
260
+ const leftDigit = index < left.length ? left[index] : "0";
261
+ const rightDigit = index < right.length ? right[index] : "0";
262
+ if (leftDigit !== rightDigit) return leftDigit > rightDigit;
263
+ }
264
+ return false;
265
+ }
266
+ function numberOutsideSafeRange(token) {
267
+ const match = token.match(
268
+ /^-?(?<whole>\d+)(?:\.(?<fraction>\d+))?(?:[eE](?<exponent>[+-]?\d+))?$/
269
+ );
270
+ if (!match?.groups) return true;
271
+ const whole = match.groups.whole;
272
+ const fraction = match.groups.fraction ?? "";
273
+ const exponent = Number(match.groups.exponent ?? "0");
274
+ if (!Number.isSafeInteger(exponent)) return true;
275
+ const digits = (whole + fraction).replace(/^0+/, "") || "0";
276
+ if (digits === "0") return false;
277
+ const scale = exponent - fraction.length;
278
+ return scale >= 0 ? scaledIntegerGreater(digits, scale, MAX_SAFE_INTEGER_DIGITS, 0) : scaledIntegerGreater(digits, 0, MAX_SAFE_INTEGER_DIGITS, -scale);
279
+ }
280
+ function validateJSONNumberTokens(raw) {
281
+ let index = 0;
282
+ while (index < raw.length) {
283
+ if (raw[index] === '"') {
284
+ index++;
285
+ while (index < raw.length) {
286
+ if (raw[index] === "\\") {
287
+ index += 2;
288
+ } else if (raw[index++] === '"') {
289
+ break;
290
+ }
291
+ }
292
+ continue;
293
+ }
294
+ if (raw[index] === "-" || /\d/.test(raw[index] ?? "")) {
295
+ const match = raw.slice(index).match(/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/);
296
+ if (match) {
297
+ if (numberOutsideSafeRange(match[0])) {
298
+ throw new TypeError(
299
+ "args contains a number outside JavaScript's safe range; use a string for int64 and identifier values"
300
+ );
301
+ }
302
+ index += match[0].length;
303
+ continue;
304
+ }
305
+ }
306
+ index++;
307
+ }
308
+ }
309
+ function assertPlainJSONData(value, path, seen) {
310
+ if (value === null || typeof value === "string" || typeof value === "boolean")
311
+ return;
312
+ if (typeof value === "number") {
313
+ if (!Number.isFinite(value)) {
314
+ throw new TypeError(`${path} must contain only finite numbers`);
315
+ }
316
+ if (Number.isInteger(value) && !Number.isSafeInteger(value)) {
317
+ throw new TypeError(
318
+ `${path} contains a number outside JavaScript's safe range; use a string for int64 and identifier values`
319
+ );
320
+ }
321
+ return;
322
+ }
323
+ if (typeof value !== "object") {
324
+ throw new TypeError(`${path} must contain only JSON data`);
325
+ }
326
+ if (seen.has(value)) {
327
+ throw new TypeError(`${path} must not contain circular references`);
328
+ }
329
+ seen.add(value);
330
+ if (Array.isArray(value)) {
331
+ value.forEach(
332
+ (item, index) => assertPlainJSONData(item, `${path}[${index}]`, seen)
333
+ );
334
+ } else {
335
+ const prototype = Object.getPrototypeOf(value);
336
+ if (prototype !== Object.prototype && prototype !== null) {
337
+ throw new TypeError(`${path} must contain only plain JSON objects`);
338
+ }
339
+ for (const [key, descriptor] of Object.entries(
340
+ Object.getOwnPropertyDescriptors(value)
341
+ )) {
342
+ if (!descriptor.enumerable) continue;
343
+ if (!("value" in descriptor)) {
344
+ throw new TypeError(`${path} must not contain accessors`);
345
+ }
346
+ assertPlainJSONData(descriptor.value, `${path}.${key}`, seen);
347
+ }
348
+ }
349
+ seen.delete(value);
350
+ }
351
+ function serializeStructuredArgs(value) {
352
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
353
+ throw new TypeError("args must be a JSON object");
354
+ }
355
+ assertPlainJSONData(value, "args", /* @__PURE__ */ new Set());
356
+ const serialized = JSON.stringify(value);
357
+ validateSerializedArgs(serialized);
358
+ return serialized;
359
+ }
360
+ function validateSerializedArgs(raw) {
361
+ const value = JSON.parse(raw);
362
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
363
+ throw new TypeError("args must be a JSON object");
364
+ }
365
+ validateJSONNumberTokens(raw);
366
+ }
367
+ function objectWithRawJSONField(fields, fieldName, rawValue) {
368
+ const entries = Object.entries(fields).filter(
369
+ ([key, value]) => value !== void 0 && (rawValue === void 0 || key !== fieldName)
370
+ );
371
+ if (rawValue !== void 0) {
372
+ validateSerializedArgs(rawValue);
373
+ entries.push([fieldName, rawValue]);
374
+ }
375
+ return `{${entries.map(([key, value]) => {
376
+ const encodedValue = key === fieldName && rawValue !== void 0 ? rawValue : JSON.stringify(value);
377
+ return `${JSON.stringify(key)}:${encodedValue}`;
378
+ }).join(",")}}`;
379
+ }
380
+
252
381
  // src/resources/run.ts
253
382
  var RunResource = class {
254
383
  constructor(client) {
@@ -257,13 +386,24 @@ var RunResource = class {
257
386
  client;
258
387
  async execute(params) {
259
388
  this.client._requireAuth();
389
+ return params.args === void 0 ? this.request(params) : this.request(params, serializeStructuredArgs(params.args));
390
+ }
391
+ /** @internal Used by the CLI to preserve the exact --args JSON text. */
392
+ async _executeSerializedArgs(params, serializedArgs) {
393
+ this.client._requireAuth();
394
+ return this.request(params, serializedArgs);
395
+ }
396
+ request(params, serializedArgs) {
397
+ const body = {
398
+ code: params.code,
399
+ entry_path: params.entry_path,
400
+ working_dir: params.working_dir,
401
+ args: params.args,
402
+ max_heap_size_mb: params.max_heap_size_mb
403
+ };
260
404
  return this.client._request("POST", "/api/v1/run", {
261
- body: {
262
- code: params.code,
263
- entry_path: params.entry_path,
264
- working_dir: params.working_dir,
265
- args: params.args,
266
- max_heap_size_mb: params.max_heap_size_mb
405
+ ...serializedArgs === void 0 ? { body } : {
406
+ jsonBody: objectWithRawJSONField(body, "args", serializedArgs)
267
407
  },
268
408
  timeoutMs: params.timeout_ms
269
409
  });
@@ -278,19 +418,30 @@ var DeployResource = class {
278
418
  client;
279
419
  async create(params) {
280
420
  this.client._requireAuth();
421
+ return params.args === void 0 ? this.createRequest(params) : this.createRequest(params, serializeStructuredArgs(params.args));
422
+ }
423
+ /** @internal Used by the CLI to preserve the exact --args JSON text. */
424
+ async _createSerializedArgs(params, serializedArgs) {
425
+ this.client._requireAuth();
426
+ return this.createRequest(params, serializedArgs);
427
+ }
428
+ createRequest(params, serializedArgs) {
429
+ const body = {
430
+ name: params.name,
431
+ path: params.path,
432
+ cron_expression: params.cron_expression,
433
+ args: params.args,
434
+ push_notify: params.push_notify,
435
+ max_heap_size_mb: params.max_heap_size_mb,
436
+ execution_timeout_seconds: params.execution_timeout_seconds,
437
+ run_as_user_id: params.run_as_user_id,
438
+ start_at: params.start_at,
439
+ end_at: params.end_at,
440
+ max_runs: params.max_runs
441
+ };
281
442
  return this.client._request("POST", "/api/v1/deploy/cronjob", {
282
- body: {
283
- name: params.name,
284
- path: params.path,
285
- cron_expression: params.cron_expression,
286
- args: params.args,
287
- push_notify: params.push_notify,
288
- max_heap_size_mb: params.max_heap_size_mb,
289
- execution_timeout_seconds: params.execution_timeout_seconds,
290
- run_as_user_id: params.run_as_user_id,
291
- start_at: params.start_at,
292
- end_at: params.end_at,
293
- max_runs: params.max_runs
443
+ ...serializedArgs === void 0 ? { body } : {
444
+ jsonBody: objectWithRawJSONField(body, "args", serializedArgs)
294
445
  }
295
446
  });
296
447
  }
@@ -309,9 +460,19 @@ var DeployResource = class {
309
460
  }
310
461
  async update(params) {
311
462
  this.client._requireAuth();
463
+ return params.args === void 0 ? this.updateRequest(params) : this.updateRequest(params, serializeStructuredArgs(params.args));
464
+ }
465
+ /** @internal Used by the CLI to preserve the exact --args JSON text. */
466
+ async _updateSerializedArgs(params, serializedArgs) {
467
+ this.client._requireAuth();
468
+ return this.updateRequest(params, serializedArgs);
469
+ }
470
+ updateRequest(params, serializedArgs) {
312
471
  const { id, ...body } = params;
313
472
  return this.client._request("PATCH", `/api/v1/deploy/cronjob/${id}`, {
314
- body
473
+ ...serializedArgs === void 0 ? { body } : {
474
+ jsonBody: objectWithRawJSONField(body, "args", serializedArgs)
475
+ }
315
476
  });
316
477
  }
317
478
  async delete(params) {
@@ -560,18 +721,53 @@ var FeedResource = class {
560
721
  }
561
722
  };
562
723
  function requireFeedID(id) {
563
- if (!Number.isInteger(id) || id <= 0) {
724
+ if (typeof id === "string") {
725
+ if (!/^[1-9]\d*$/.test(id)) {
726
+ throw new Error("feed id must be a positive integer");
727
+ }
728
+ return id;
729
+ }
730
+ if (!Number.isSafeInteger(id) || id <= 0) {
564
731
  throw new Error("feed id must be a positive integer");
565
732
  }
566
733
  return id;
567
734
  }
568
735
 
569
736
  // src/resources/automation.ts
737
+ var AUTOMATION_ALERT_DELIVERY_QUERY = `
738
+ query ToolkitAutomationAlertDelivery($automationId: ID!) {
739
+ automation(id: $automationId) {
740
+ alertDelivery {
741
+ isEnabled
742
+ alvaChannels { id }
743
+ email { isEnabled isAvailable address }
744
+ }
745
+ }
746
+ }
747
+ `.trim();
748
+ var UPDATE_AUTOMATION_ALERT_DELIVERY = `
749
+ mutation ToolkitUpdateAutomationAlertDelivery(
750
+ $input: UpdateAutomationAlertDeliveryInput!
751
+ $includeAlvaChannels: Boolean!
752
+ $includeEmail: Boolean!
753
+ ) {
754
+ updateAutomationAlertDelivery(input: $input) {
755
+ automation { id }
756
+ alertDelivery {
757
+ isEnabled
758
+ alvaChannels @include(if: $includeAlvaChannels) { id }
759
+ email @include(if: $includeEmail) { isEnabled isAvailable address }
760
+ }
761
+ }
762
+ }
763
+ `.trim();
570
764
  var AutomationResource = class {
571
765
  constructor(client) {
572
766
  this.client = client;
767
+ this.delivery = new AutomationAlertDeliveryResource(client);
573
768
  }
574
769
  client;
770
+ delivery;
575
771
  list(params = {}) {
576
772
  return this.client.feed.list(params);
577
773
  }
@@ -623,8 +819,93 @@ var AutomationResource = class {
623
819
  return this.client.release.feed(params);
624
820
  }
625
821
  };
822
+ var AutomationAlertDeliveryResource = class {
823
+ constructor(client) {
824
+ this.client = client;
825
+ }
826
+ client;
827
+ async get(params) {
828
+ this.client._requireAuth();
829
+ const id = requireAutomationIDString(params.id);
830
+ const data = await this.graphql(
831
+ AUTOMATION_ALERT_DELIVERY_QUERY,
832
+ { automationId: id }
833
+ );
834
+ const delivery = data.automation?.alertDelivery;
835
+ if (!delivery) {
836
+ throw new AlvaError(
837
+ "GRAPHQL_EMPTY_RESPONSE",
838
+ "GraphQL response did not include automation.alertDelivery",
839
+ 502
840
+ );
841
+ }
842
+ return delivery;
843
+ }
844
+ async update(params) {
845
+ this.client._requireAuth();
846
+ const id = requireAutomationIDString(params.id);
847
+ const includeAlvaChannels = params.alvaChannelIds !== void 0;
848
+ const includeEmail = params.emailEnabled !== void 0;
849
+ if (!includeAlvaChannels && !includeEmail) {
850
+ throw new Error(
851
+ "automation delivery update requires alvaChannelIds or emailEnabled"
852
+ );
853
+ }
854
+ const alvaChannelIds = includeAlvaChannels ? uniqueAlvaChannelIDs(params.alvaChannelIds ?? []) : void 0;
855
+ const data = await this.graphql(
856
+ UPDATE_AUTOMATION_ALERT_DELIVERY,
857
+ {
858
+ input: {
859
+ automationId: id,
860
+ ...includeAlvaChannels ? { alvaChannelIds } : {},
861
+ ...includeEmail ? { emailEnabled: params.emailEnabled } : {}
862
+ },
863
+ includeAlvaChannels,
864
+ includeEmail
865
+ }
866
+ );
867
+ const result = data.updateAutomationAlertDelivery;
868
+ if (!result) {
869
+ throw new AlvaError(
870
+ "GRAPHQL_EMPTY_RESPONSE",
871
+ "GraphQL response did not include updateAutomationAlertDelivery",
872
+ 502
873
+ );
874
+ }
875
+ return result;
876
+ }
877
+ async graphql(query, variables) {
878
+ const response = await this.client._request("POST", "/query", {
879
+ body: { query, variables }
880
+ });
881
+ if (!response) {
882
+ throw new AlvaError(
883
+ "GRAPHQL_EMPTY_RESPONSE",
884
+ "GraphQL response was empty",
885
+ 502
886
+ );
887
+ }
888
+ if (response.errors && response.errors.length > 0) {
889
+ throw new AlvaError(
890
+ "GRAPHQL_ERROR",
891
+ graphQLErrorMessage(response.errors),
892
+ 400,
893
+ { errors: response.errors }
894
+ );
895
+ }
896
+ if (!response.data) {
897
+ throw new AlvaError(
898
+ "GRAPHQL_EMPTY_RESPONSE",
899
+ "GraphQL response did not include data",
900
+ 502
901
+ );
902
+ }
903
+ return response.data;
904
+ }
905
+ };
626
906
  function requireAutomationID(id) {
627
- if (!Number.isInteger(id) || id <= 0) {
907
+ if (typeof id === "string") return requireAutomationIDString(id);
908
+ if (!Number.isSafeInteger(id) || id <= 0) {
628
909
  throw new Error("automation id must be a positive integer");
629
910
  }
630
911
  return id;
@@ -638,6 +919,23 @@ function requireAutomationIDString(id) {
638
919
  function hasAutomationUpdate(params) {
639
920
  return params.version !== void 0 || params.cronjob_id !== void 0 || params.description !== void 0 || params.changelog !== void 0 || params.agent_type !== void 0 || params.trigger === true;
640
921
  }
922
+ function uniqueAlvaChannelIDs(values) {
923
+ const ids = [...new Set(values)];
924
+ for (const id of ids) {
925
+ if (!/^(0|[1-9]\d*)$/.test(id)) {
926
+ throw new Error(
927
+ "Alva channel ids must be positive integer strings or the agent sentinel 0"
928
+ );
929
+ }
930
+ }
931
+ return ids;
932
+ }
933
+ function graphQLErrorMessage(errors) {
934
+ const messages = errors.map(
935
+ (error) => error && typeof error.message === "string" && error.message ? error.message : void 0
936
+ ).filter((message) => Boolean(message));
937
+ return messages.length > 0 ? messages.join("; ") : "GraphQL request failed";
938
+ }
641
939
 
642
940
  // src/resources/playbooks.ts
643
941
  var PLAYBOOK_VISIBILITIES = [
@@ -2493,7 +2791,7 @@ query ToolkitCreditWalletItems($input: CreditWalletItemConnectionInput!) {
2493
2791
  }
2494
2792
  }
2495
2793
  `.trim();
2496
- function graphQLErrorMessage(errors) {
2794
+ function graphQLErrorMessage2(errors) {
2497
2795
  const messages = errors.map(
2498
2796
  (error) => typeof error.message === "string" && error.message ? error.message : void 0
2499
2797
  ).filter((message) => Boolean(message));
@@ -2548,7 +2846,7 @@ var CreditsResource = class {
2548
2846
  if (response.errors && response.errors.length > 0) {
2549
2847
  throw new AlvaError(
2550
2848
  "GRAPHQL_ERROR",
2551
- graphQLErrorMessage(response.errors),
2849
+ graphQLErrorMessage2(response.errors),
2552
2850
  400,
2553
2851
  { errors: response.errors }
2554
2852
  );
@@ -2705,7 +3003,7 @@ query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
2705
3003
  }
2706
3004
  }
2707
3005
  `.trim();
2708
- function graphQLErrorMessage2(errors) {
3006
+ function graphQLErrorMessage3(errors) {
2709
3007
  const messages = errors.map(
2710
3008
  (error) => typeof error.message === "string" && error.message ? error.message : void 0
2711
3009
  ).filter((message) => Boolean(message));
@@ -2861,7 +3159,7 @@ var MarketsResource = class {
2861
3159
  if (response.errors && response.errors.length > 0) {
2862
3160
  throw new AlvaError(
2863
3161
  "GRAPHQL_ERROR",
2864
- graphQLErrorMessage2(response.errors),
3162
+ graphQLErrorMessage3(response.errors),
2865
3163
  400,
2866
3164
  { errors: response.errors }
2867
3165
  );
@@ -3695,12 +3993,13 @@ var installPlaybookRuntime = (targetWindow) => {
3695
3993
  };
3696
3994
 
3697
3995
  // src/index.ts
3698
- var VERSION = true ? "0.23.1" : "dev";
3996
+ var VERSION = true ? "0.25.0" : "dev";
3699
3997
  // Annotate the CommonJS export names for ESM import in node:
3700
3998
  0 && (module.exports = {
3701
3999
  AlertsResource,
3702
4000
  AlvaClient,
3703
4001
  AlvaError,
4002
+ AutomationAlertDeliveryResource,
3704
4003
  AutomationResource,
3705
4004
  CliUsageError,
3706
4005
  MarketsResource,