@alva-ai/toolkit 0.23.0 → 0.24.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
@@ -190,6 +190,134 @@ var FsResource = class {
190
190
  }
191
191
  };
192
192
 
193
+ // src/jsonPayload.ts
194
+ var MAX_SAFE_INTEGER_DIGITS = "9007199254740991";
195
+ function scaledIntegerGreater(left, leftTrailingZeros, right, rightTrailingZeros) {
196
+ const leftLength = left.length + leftTrailingZeros;
197
+ const rightLength = right.length + rightTrailingZeros;
198
+ if (leftLength !== rightLength) return leftLength > rightLength;
199
+ for (let index = 0; index < leftLength; index++) {
200
+ const leftDigit = index < left.length ? left[index] : "0";
201
+ const rightDigit = index < right.length ? right[index] : "0";
202
+ if (leftDigit !== rightDigit) return leftDigit > rightDigit;
203
+ }
204
+ return false;
205
+ }
206
+ function numberOutsideSafeRange(token) {
207
+ const match = token.match(
208
+ /^-?(?<whole>\d+)(?:\.(?<fraction>\d+))?(?:[eE](?<exponent>[+-]?\d+))?$/
209
+ );
210
+ if (!match?.groups) return true;
211
+ const whole = match.groups.whole;
212
+ const fraction = match.groups.fraction ?? "";
213
+ const exponent = Number(match.groups.exponent ?? "0");
214
+ if (!Number.isSafeInteger(exponent)) return true;
215
+ const digits = (whole + fraction).replace(/^0+/, "") || "0";
216
+ if (digits === "0") return false;
217
+ const scale = exponent - fraction.length;
218
+ return scale >= 0 ? scaledIntegerGreater(digits, scale, MAX_SAFE_INTEGER_DIGITS, 0) : scaledIntegerGreater(digits, 0, MAX_SAFE_INTEGER_DIGITS, -scale);
219
+ }
220
+ function validateJSONNumberTokens(raw) {
221
+ let index = 0;
222
+ while (index < raw.length) {
223
+ if (raw[index] === '"') {
224
+ index++;
225
+ while (index < raw.length) {
226
+ if (raw[index] === "\\") {
227
+ index += 2;
228
+ } else if (raw[index++] === '"') {
229
+ break;
230
+ }
231
+ }
232
+ continue;
233
+ }
234
+ if (raw[index] === "-" || /\d/.test(raw[index] ?? "")) {
235
+ const match = raw.slice(index).match(/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/);
236
+ if (match) {
237
+ if (numberOutsideSafeRange(match[0])) {
238
+ throw new TypeError(
239
+ "args contains a number outside JavaScript's safe range; use a string for int64 and identifier values"
240
+ );
241
+ }
242
+ index += match[0].length;
243
+ continue;
244
+ }
245
+ }
246
+ index++;
247
+ }
248
+ }
249
+ function assertPlainJSONData(value, path, seen) {
250
+ if (value === null || typeof value === "string" || typeof value === "boolean")
251
+ return;
252
+ if (typeof value === "number") {
253
+ if (!Number.isFinite(value)) {
254
+ throw new TypeError(`${path} must contain only finite numbers`);
255
+ }
256
+ if (Number.isInteger(value) && !Number.isSafeInteger(value)) {
257
+ throw new TypeError(
258
+ `${path} contains a number outside JavaScript's safe range; use a string for int64 and identifier values`
259
+ );
260
+ }
261
+ return;
262
+ }
263
+ if (typeof value !== "object") {
264
+ throw new TypeError(`${path} must contain only JSON data`);
265
+ }
266
+ if (seen.has(value)) {
267
+ throw new TypeError(`${path} must not contain circular references`);
268
+ }
269
+ seen.add(value);
270
+ if (Array.isArray(value)) {
271
+ value.forEach(
272
+ (item, index) => assertPlainJSONData(item, `${path}[${index}]`, seen)
273
+ );
274
+ } else {
275
+ const prototype = Object.getPrototypeOf(value);
276
+ if (prototype !== Object.prototype && prototype !== null) {
277
+ throw new TypeError(`${path} must contain only plain JSON objects`);
278
+ }
279
+ for (const [key, descriptor] of Object.entries(
280
+ Object.getOwnPropertyDescriptors(value)
281
+ )) {
282
+ if (!descriptor.enumerable) continue;
283
+ if (!("value" in descriptor)) {
284
+ throw new TypeError(`${path} must not contain accessors`);
285
+ }
286
+ assertPlainJSONData(descriptor.value, `${path}.${key}`, seen);
287
+ }
288
+ }
289
+ seen.delete(value);
290
+ }
291
+ function serializeStructuredArgs(value) {
292
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
293
+ throw new TypeError("args must be a JSON object");
294
+ }
295
+ assertPlainJSONData(value, "args", /* @__PURE__ */ new Set());
296
+ const serialized = JSON.stringify(value);
297
+ validateSerializedArgs(serialized);
298
+ return serialized;
299
+ }
300
+ function validateSerializedArgs(raw) {
301
+ const value = JSON.parse(raw);
302
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
303
+ throw new TypeError("args must be a JSON object");
304
+ }
305
+ validateJSONNumberTokens(raw);
306
+ }
307
+ function objectWithRawJSONField(fields, fieldName, rawValue) {
308
+ const entries = Object.entries(fields).filter(
309
+ ([key, value]) => value !== void 0 && (rawValue === void 0 || key !== fieldName)
310
+ );
311
+ if (rawValue !== void 0) {
312
+ validateSerializedArgs(rawValue);
313
+ entries.push([fieldName, rawValue]);
314
+ }
315
+ return `{${entries.map(([key, value]) => {
316
+ const encodedValue = key === fieldName && rawValue !== void 0 ? rawValue : JSON.stringify(value);
317
+ return `${JSON.stringify(key)}:${encodedValue}`;
318
+ }).join(",")}}`;
319
+ }
320
+
193
321
  // src/resources/run.ts
194
322
  var RunResource = class {
195
323
  constructor(client) {
@@ -198,13 +326,24 @@ var RunResource = class {
198
326
  client;
199
327
  async execute(params) {
200
328
  this.client._requireAuth();
329
+ return params.args === void 0 ? this.request(params) : this.request(params, serializeStructuredArgs(params.args));
330
+ }
331
+ /** @internal Used by the CLI to preserve the exact --args JSON text. */
332
+ async _executeSerializedArgs(params, serializedArgs) {
333
+ this.client._requireAuth();
334
+ return this.request(params, serializedArgs);
335
+ }
336
+ request(params, serializedArgs) {
337
+ const body = {
338
+ code: params.code,
339
+ entry_path: params.entry_path,
340
+ working_dir: params.working_dir,
341
+ args: params.args,
342
+ max_heap_size_mb: params.max_heap_size_mb
343
+ };
201
344
  return this.client._request("POST", "/api/v1/run", {
202
- body: {
203
- code: params.code,
204
- entry_path: params.entry_path,
205
- working_dir: params.working_dir,
206
- args: params.args,
207
- max_heap_size_mb: params.max_heap_size_mb
345
+ ...serializedArgs === void 0 ? { body } : {
346
+ jsonBody: objectWithRawJSONField(body, "args", serializedArgs)
208
347
  },
209
348
  timeoutMs: params.timeout_ms
210
349
  });
@@ -219,19 +358,30 @@ var DeployResource = class {
219
358
  client;
220
359
  async create(params) {
221
360
  this.client._requireAuth();
361
+ return params.args === void 0 ? this.createRequest(params) : this.createRequest(params, serializeStructuredArgs(params.args));
362
+ }
363
+ /** @internal Used by the CLI to preserve the exact --args JSON text. */
364
+ async _createSerializedArgs(params, serializedArgs) {
365
+ this.client._requireAuth();
366
+ return this.createRequest(params, serializedArgs);
367
+ }
368
+ createRequest(params, serializedArgs) {
369
+ const body = {
370
+ name: params.name,
371
+ path: params.path,
372
+ cron_expression: params.cron_expression,
373
+ args: params.args,
374
+ push_notify: params.push_notify,
375
+ max_heap_size_mb: params.max_heap_size_mb,
376
+ execution_timeout_seconds: params.execution_timeout_seconds,
377
+ run_as_user_id: params.run_as_user_id,
378
+ start_at: params.start_at,
379
+ end_at: params.end_at,
380
+ max_runs: params.max_runs
381
+ };
222
382
  return this.client._request("POST", "/api/v1/deploy/cronjob", {
223
- body: {
224
- name: params.name,
225
- path: params.path,
226
- cron_expression: params.cron_expression,
227
- args: params.args,
228
- push_notify: params.push_notify,
229
- max_heap_size_mb: params.max_heap_size_mb,
230
- execution_timeout_seconds: params.execution_timeout_seconds,
231
- run_as_user_id: params.run_as_user_id,
232
- start_at: params.start_at,
233
- end_at: params.end_at,
234
- max_runs: params.max_runs
383
+ ...serializedArgs === void 0 ? { body } : {
384
+ jsonBody: objectWithRawJSONField(body, "args", serializedArgs)
235
385
  }
236
386
  });
237
387
  }
@@ -250,9 +400,19 @@ var DeployResource = class {
250
400
  }
251
401
  async update(params) {
252
402
  this.client._requireAuth();
403
+ return params.args === void 0 ? this.updateRequest(params) : this.updateRequest(params, serializeStructuredArgs(params.args));
404
+ }
405
+ /** @internal Used by the CLI to preserve the exact --args JSON text. */
406
+ async _updateSerializedArgs(params, serializedArgs) {
407
+ this.client._requireAuth();
408
+ return this.updateRequest(params, serializedArgs);
409
+ }
410
+ updateRequest(params, serializedArgs) {
253
411
  const { id, ...body } = params;
254
412
  return this.client._request("PATCH", `/api/v1/deploy/cronjob/${id}`, {
255
- body
413
+ ...serializedArgs === void 0 ? { body } : {
414
+ jsonBody: objectWithRawJSONField(body, "args", serializedArgs)
415
+ }
256
416
  });
257
417
  }
258
418
  async delete(params) {
@@ -508,11 +668,40 @@ function requireFeedID(id) {
508
668
  }
509
669
 
510
670
  // src/resources/automation.ts
671
+ var AUTOMATION_ALERT_DELIVERY_QUERY = `
672
+ query ToolkitAutomationAlertDelivery($automationId: ID!) {
673
+ automation(id: $automationId) {
674
+ alertDelivery {
675
+ isEnabled
676
+ alvaChannels { id }
677
+ email { isEnabled isAvailable address }
678
+ }
679
+ }
680
+ }
681
+ `.trim();
682
+ var UPDATE_AUTOMATION_ALERT_DELIVERY = `
683
+ mutation ToolkitUpdateAutomationAlertDelivery(
684
+ $input: UpdateAutomationAlertDeliveryInput!
685
+ $includeAlvaChannels: Boolean!
686
+ $includeEmail: Boolean!
687
+ ) {
688
+ updateAutomationAlertDelivery(input: $input) {
689
+ automation { id }
690
+ alertDelivery {
691
+ isEnabled
692
+ alvaChannels @include(if: $includeAlvaChannels) { id }
693
+ email @include(if: $includeEmail) { isEnabled isAvailable address }
694
+ }
695
+ }
696
+ }
697
+ `.trim();
511
698
  var AutomationResource = class {
512
699
  constructor(client) {
513
700
  this.client = client;
701
+ this.delivery = new AutomationAlertDeliveryResource(client);
514
702
  }
515
703
  client;
704
+ delivery;
516
705
  list(params = {}) {
517
706
  return this.client.feed.list(params);
518
707
  }
@@ -564,6 +753,90 @@ var AutomationResource = class {
564
753
  return this.client.release.feed(params);
565
754
  }
566
755
  };
756
+ var AutomationAlertDeliveryResource = class {
757
+ constructor(client) {
758
+ this.client = client;
759
+ }
760
+ client;
761
+ async get(params) {
762
+ this.client._requireAuth();
763
+ const id = requireAutomationIDString(params.id);
764
+ const data = await this.graphql(
765
+ AUTOMATION_ALERT_DELIVERY_QUERY,
766
+ { automationId: id }
767
+ );
768
+ const delivery = data.automation?.alertDelivery;
769
+ if (!delivery) {
770
+ throw new AlvaError(
771
+ "GRAPHQL_EMPTY_RESPONSE",
772
+ "GraphQL response did not include automation.alertDelivery",
773
+ 502
774
+ );
775
+ }
776
+ return delivery;
777
+ }
778
+ async update(params) {
779
+ this.client._requireAuth();
780
+ const id = requireAutomationIDString(params.id);
781
+ const includeAlvaChannels = params.alvaChannelIds !== void 0;
782
+ const includeEmail = params.emailEnabled !== void 0;
783
+ if (!includeAlvaChannels && !includeEmail) {
784
+ throw new Error(
785
+ "automation delivery update requires alvaChannelIds or emailEnabled"
786
+ );
787
+ }
788
+ const alvaChannelIds = includeAlvaChannels ? uniqueAlvaChannelIDs(params.alvaChannelIds ?? []) : void 0;
789
+ const data = await this.graphql(
790
+ UPDATE_AUTOMATION_ALERT_DELIVERY,
791
+ {
792
+ input: {
793
+ automationId: id,
794
+ ...includeAlvaChannels ? { alvaChannelIds } : {},
795
+ ...includeEmail ? { emailEnabled: params.emailEnabled } : {}
796
+ },
797
+ includeAlvaChannels,
798
+ includeEmail
799
+ }
800
+ );
801
+ const result = data.updateAutomationAlertDelivery;
802
+ if (!result) {
803
+ throw new AlvaError(
804
+ "GRAPHQL_EMPTY_RESPONSE",
805
+ "GraphQL response did not include updateAutomationAlertDelivery",
806
+ 502
807
+ );
808
+ }
809
+ return result;
810
+ }
811
+ async graphql(query, variables) {
812
+ const response = await this.client._request("POST", "/query", {
813
+ body: { query, variables }
814
+ });
815
+ if (!response) {
816
+ throw new AlvaError(
817
+ "GRAPHQL_EMPTY_RESPONSE",
818
+ "GraphQL response was empty",
819
+ 502
820
+ );
821
+ }
822
+ if (response.errors && response.errors.length > 0) {
823
+ throw new AlvaError(
824
+ "GRAPHQL_ERROR",
825
+ graphQLErrorMessage(response.errors),
826
+ 400,
827
+ { errors: response.errors }
828
+ );
829
+ }
830
+ if (!response.data) {
831
+ throw new AlvaError(
832
+ "GRAPHQL_EMPTY_RESPONSE",
833
+ "GraphQL response did not include data",
834
+ 502
835
+ );
836
+ }
837
+ return response.data;
838
+ }
839
+ };
567
840
  function requireAutomationID(id) {
568
841
  if (!Number.isInteger(id) || id <= 0) {
569
842
  throw new Error("automation id must be a positive integer");
@@ -579,6 +852,23 @@ function requireAutomationIDString(id) {
579
852
  function hasAutomationUpdate(params) {
580
853
  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;
581
854
  }
855
+ function uniqueAlvaChannelIDs(values) {
856
+ const ids = [...new Set(values)];
857
+ for (const id of ids) {
858
+ if (!/^(0|[1-9]\d*)$/.test(id)) {
859
+ throw new Error(
860
+ "Alva channel ids must be positive integer strings or the agent sentinel 0"
861
+ );
862
+ }
863
+ }
864
+ return ids;
865
+ }
866
+ function graphQLErrorMessage(errors) {
867
+ const messages = errors.map(
868
+ (error) => error && typeof error.message === "string" && error.message ? error.message : void 0
869
+ ).filter((message) => Boolean(message));
870
+ return messages.length > 0 ? messages.join("; ") : "GraphQL request failed";
871
+ }
582
872
 
583
873
  // src/resources/playbooks.ts
584
874
  var PLAYBOOK_VISIBILITIES = [
@@ -2434,7 +2724,7 @@ query ToolkitCreditWalletItems($input: CreditWalletItemConnectionInput!) {
2434
2724
  }
2435
2725
  }
2436
2726
  `.trim();
2437
- function graphQLErrorMessage(errors) {
2727
+ function graphQLErrorMessage2(errors) {
2438
2728
  const messages = errors.map(
2439
2729
  (error) => typeof error.message === "string" && error.message ? error.message : void 0
2440
2730
  ).filter((message) => Boolean(message));
@@ -2489,7 +2779,7 @@ var CreditsResource = class {
2489
2779
  if (response.errors && response.errors.length > 0) {
2490
2780
  throw new AlvaError(
2491
2781
  "GRAPHQL_ERROR",
2492
- graphQLErrorMessage(response.errors),
2782
+ graphQLErrorMessage2(response.errors),
2493
2783
  400,
2494
2784
  { errors: response.errors }
2495
2785
  );
@@ -2646,7 +2936,7 @@ query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
2646
2936
  }
2647
2937
  }
2648
2938
  `.trim();
2649
- function graphQLErrorMessage2(errors) {
2939
+ function graphQLErrorMessage3(errors) {
2650
2940
  const messages = errors.map(
2651
2941
  (error) => typeof error.message === "string" && error.message ? error.message : void 0
2652
2942
  ).filter((message) => Boolean(message));
@@ -2802,7 +3092,7 @@ var MarketsResource = class {
2802
3092
  if (response.errors && response.errors.length > 0) {
2803
3093
  throw new AlvaError(
2804
3094
  "GRAPHQL_ERROR",
2805
- graphQLErrorMessage2(response.errors),
3095
+ graphQLErrorMessage3(response.errors),
2806
3096
  400,
2807
3097
  { errors: response.errors }
2808
3098
  );
@@ -3255,6 +3545,7 @@ var UDF_CONSENT_RESPONSE_MESSAGE = "alva:udf:consent-response";
3255
3545
  var UDF_AUTH_REQUIRED_MESSAGE = "alva:udf:auth-required";
3256
3546
  var SUBSCRIBE_PROPOSE_MESSAGE = "alva:subscribe:propose";
3257
3547
  var SUBSCRIBE_RESULT_MESSAGE = "alva:subscribe:result";
3548
+ var SUBSCRIBE_MANAGE_MESSAGE = "alva:subscribe:manage";
3258
3549
  var DEFAULT_API_ORIGIN = "https://api-llm.prd.alva.ai";
3259
3550
  var CONSENT_TIMEOUT_MS = 5 * 60 * 1e3;
3260
3551
  var cachedToken = null;
@@ -3447,8 +3738,19 @@ var proposeSubscribe = async (input) => {
3447
3738
  );
3448
3739
  });
3449
3740
  };
3741
+ var manageSubscriptions = () => {
3742
+ if (!runtimeWindow || !expectedParentOrigin) return;
3743
+ runtimeWindow.parent.postMessage(
3744
+ {
3745
+ type: SUBSCRIBE_MANAGE_MESSAGE,
3746
+ playbook_id: playbookIdFromBoot
3747
+ },
3748
+ expectedParentOrigin
3749
+ );
3750
+ };
3450
3751
  var subscribe = {
3451
- propose: proposeSubscribe
3752
+ propose: proposeSubscribe,
3753
+ manage: manageSubscriptions
3452
3754
  };
3453
3755
  var requestAuthentication = (functionName) => {
3454
3756
  if (!runtimeWindow || !expectedParentOrigin) return;
@@ -3624,15 +3926,17 @@ var installPlaybookRuntime = (targetWindow) => {
3624
3926
  };
3625
3927
 
3626
3928
  // src/index.ts
3627
- var VERSION = true ? "0.23.0" : "dev";
3929
+ var VERSION = true ? "0.24.0" : "dev";
3628
3930
  export {
3629
3931
  AlertsResource,
3630
3932
  AlvaClient,
3631
3933
  AlvaError,
3934
+ AutomationAlertDeliveryResource,
3632
3935
  AutomationResource,
3633
3936
  CliUsageError,
3634
3937
  MarketsResource,
3635
3938
  PBSV_UPDATE_MESSAGE,
3939
+ SUBSCRIBE_MANAGE_MESSAGE,
3636
3940
  SUBSCRIBE_PROPOSE_MESSAGE,
3637
3941
  SUBSCRIBE_RESULT_MESSAGE,
3638
3942
  UDF_AUTH_REQUIRED_MESSAGE,