@alva-ai/toolkit 0.26.0 → 0.28.0-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
@@ -26,12 +26,14 @@ __export(src_exports, {
26
26
  AutomationAlertDeliveryResource: () => AutomationAlertDeliveryResource,
27
27
  AutomationResource: () => AutomationResource,
28
28
  CliUsageError: () => CliUsageError,
29
+ ForYouResource: () => ForYouResource,
29
30
  MarketsResource: () => MarketsResource,
30
31
  PBSV_UPDATE_MESSAGE: () => PBSV_UPDATE_MESSAGE,
31
32
  SUBSCRIBE_MANAGE_MESSAGE: () => SUBSCRIBE_MANAGE_MESSAGE,
32
33
  SUBSCRIBE_PROPOSE_MESSAGE: () => SUBSCRIBE_PROPOSE_MESSAGE,
33
34
  SUBSCRIBE_RESULT_MESSAGE: () => SUBSCRIBE_RESULT_MESSAGE,
34
35
  SchedulesResource: () => SchedulesResource,
36
+ TradingPairsResource: () => TradingPairsResource,
35
37
  UDF_AUTH_REQUIRED_MESSAGE: () => UDF_AUTH_REQUIRED_MESSAGE,
36
38
  UDF_CONSENT_REQUEST_MESSAGE: () => UDF_CONSENT_REQUEST_MESSAGE,
37
39
  UDF_CONSENT_RESPONSE_MESSAGE: () => UDF_CONSENT_RESPONSE_MESSAGE,
@@ -734,6 +736,134 @@ function requireFeedID(id) {
734
736
  return id;
735
737
  }
736
738
 
739
+ // src/resources/forYou.ts
740
+ var FOR_YOU_QUERY = `
741
+ query ToolkitForYou($input: FeedEntryConnectionInput) {
742
+ viewer {
743
+ forYou(input: $input) {
744
+ edges {
745
+ cursor
746
+ node {
747
+ id
748
+ feed { id }
749
+ major { id feedId number }
750
+ displayName source eventTimeMs publishedAtMs title body
751
+ actions { type label url prompt }
752
+ presentation {
753
+ card {
754
+ accentColor url thumbnailUrl footer
755
+ fields { label value inline }
756
+ }
757
+ }
758
+ tickers { symbol logoUrl sentiment }
759
+ media { type coverUrl url }
760
+ sources { type url iconUrl title subtitle description publishedAtMs }
761
+ }
762
+ }
763
+ pageInfo { startCursor endCursor hasNextPage hasPreviousPage }
764
+ }
765
+ }
766
+ }
767
+ `.trim();
768
+ function record(value) {
769
+ return typeof value === "object" && value !== null && !Array.isArray(value);
770
+ }
771
+ function validateForYouListParams(params) {
772
+ if (!record(params)) throw new Error("For You parameters must be an object");
773
+ const first = params.first === void 0 ? 20 : params.first;
774
+ if (typeof first !== "number" || !Number.isInteger(first) || first < 1 || first > 50) {
775
+ throw new Error("first must be an integer between 1 and 50");
776
+ }
777
+ for (const field of ["after", "newerThan"]) {
778
+ const value = params[field];
779
+ if (value !== void 0 && (typeof value !== "string" || !value.trim())) {
780
+ throw new Error(`${field} must be a non-empty cursor`);
781
+ }
782
+ }
783
+ if (params.feedId !== void 0 && !isPositiveInt64(params.feedId)) {
784
+ throw new Error("feedId must be a positive decimal int64 string");
785
+ }
786
+ }
787
+ function isPositiveInt64(value) {
788
+ return typeof value === "string" && /^[1-9]\d{0,18}$/.test(value) && BigInt(value) <= 9223372036854775807n;
789
+ }
790
+ function invalidResponse() {
791
+ throw new AlvaError(
792
+ "GRAPHQL_INVALID_RESPONSE",
793
+ "GraphQL returned an invalid For You connection",
794
+ 502
795
+ );
796
+ }
797
+ function connection(value) {
798
+ if (!record(value) || !Array.isArray(value.edges) || !record(value.pageInfo)) {
799
+ return invalidResponse();
800
+ }
801
+ const page = value.pageInfo;
802
+ if (typeof page.startCursor !== "string" || typeof page.endCursor !== "string" || typeof page.hasNextPage !== "boolean" || typeof page.hasPreviousPage !== "boolean") {
803
+ return invalidResponse();
804
+ }
805
+ for (const edge of value.edges) {
806
+ if (!record(edge) || typeof edge.cursor !== "string" || !edge.cursor.trim() || !record(edge.node))
807
+ return invalidResponse();
808
+ const node = edge.node;
809
+ if (typeof node.id !== "string" || !node.id.startsWith("FeedEntry:") || !isPositiveInt64(node.id.slice("FeedEntry:".length)) || !record(node.feed) || !isPositiveInt64(node.feed.id) || !record(node.major) || typeof node.major.id !== "string" || !isPositiveInt64(node.major.feedId) || typeof node.title !== "string" || typeof node.body !== "string") {
810
+ return invalidResponse();
811
+ }
812
+ }
813
+ const first = value.edges[0];
814
+ const last = value.edges[value.edges.length - 1];
815
+ if (page.startCursor !== (first?.cursor ?? "") || page.endCursor !== (last?.cursor ?? "") || value.edges.length === 0 && page.hasNextPage)
816
+ return invalidResponse();
817
+ return value;
818
+ }
819
+ var ForYouResource = class {
820
+ constructor(client) {
821
+ this.client = client;
822
+ }
823
+ client;
824
+ /** One newest-first page. Does not truncate content or advance a watermark. */
825
+ async list(params = {}) {
826
+ validateForYouListParams(params);
827
+ this.client._requireAuth();
828
+ const response = await this.client._request("POST", "/query", {
829
+ body: {
830
+ query: FOR_YOU_QUERY,
831
+ variables: {
832
+ input: {
833
+ first: params.first ?? 20,
834
+ after: params.after,
835
+ newerThan: params.newerThan,
836
+ feedId: params.feedId
837
+ }
838
+ }
839
+ }
840
+ });
841
+ if (!record(response)) return invalidResponse();
842
+ if (response.errors !== void 0) {
843
+ if (!Array.isArray(response.errors)) return invalidResponse();
844
+ if (response.errors.length > 0) {
845
+ const messages = response.errors.flatMap(
846
+ (error) => record(error) && typeof error.message === "string" ? [error.message] : []
847
+ );
848
+ throw new AlvaError(
849
+ "GRAPHQL_ERROR",
850
+ messages.join("; ") || "GraphQL request failed",
851
+ 400,
852
+ { errors: response.errors }
853
+ );
854
+ }
855
+ }
856
+ if (!record(response.data) || !record(response.data.viewer) || response.data.viewer.forYou == null) {
857
+ throw new AlvaError(
858
+ "GRAPHQL_EMPTY_RESPONSE",
859
+ "GraphQL response did not include viewer.forYou",
860
+ 502
861
+ );
862
+ }
863
+ return connection(response.data.viewer.forYou);
864
+ }
865
+ };
866
+
737
867
  // src/resources/automation.ts
738
868
  var AUTOMATION_ALERT_DELIVERY_QUERY = `
739
869
  query ToolkitAutomationAlertDelivery($automationId: ID!) {
@@ -2286,8 +2416,8 @@ var NotificationsResource = class {
2286
2416
  client;
2287
2417
  /**
2288
2418
  * List the caller's notification history for one feed
2289
- * `(username, name)`. Authorization is alfs read on
2290
- * `/alva/home/<username>/feeds/<name>`.
2419
+ * `(username, name)`. Authorization uses the backend's canonical Feed read
2420
+ * decision (owner, public, bundled paid access, Plan, or Access Group).
2291
2421
  */
2292
2422
  async listFeed(params) {
2293
2423
  this.client._requireAuth();
@@ -3246,14 +3376,14 @@ var SchedulesResource = class {
3246
3376
  LIST_SCHEDULES,
3247
3377
  { channelId: id, after }
3248
3378
  );
3249
- const connection = data.viewer?.channel?.schedules;
3250
- if (!connection?.edges) throw scheduleNotFound();
3251
- for (const edge of connection.edges) {
3379
+ const connection2 = data.viewer?.channel?.schedules;
3380
+ if (!connection2?.edges) throw scheduleNotFound();
3381
+ for (const edge of connection2.edges) {
3252
3382
  if (!edge?.node) throw scheduleEmptyResponse();
3253
3383
  schedules.push(fromWireSchedule(edge.node));
3254
3384
  }
3255
- if (connection.pageInfo?.hasNextPage !== true) return schedules;
3256
- const next = connection.pageInfo.endCursor;
3385
+ if (connection2.pageInfo?.hasNextPage !== true) return schedules;
3386
+ const next = connection2.pageInfo.endCursor;
3257
3387
  if (!next || seenCursors.has(next)) throw scheduleEmptyResponse();
3258
3388
  seenCursors.add(next);
3259
3389
  after = next;
@@ -3549,14 +3679,199 @@ function scheduleEmptyResponse() {
3549
3679
  );
3550
3680
  }
3551
3681
 
3682
+ // src/resources/tradingPairs.ts
3683
+ function isRecord(value) {
3684
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3685
+ }
3686
+ function stringValue(value) {
3687
+ return typeof value === "string" && value.trim() !== "" ? value : void 0;
3688
+ }
3689
+ function numberValue(value) {
3690
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
3691
+ }
3692
+ function upper(value) {
3693
+ return value === void 0 ? void 0 : value.trim().toUpperCase();
3694
+ }
3695
+ function pairParts(pair) {
3696
+ return pair.split("_");
3697
+ }
3698
+ function inferInstrumentType(rawType, tradingPair) {
3699
+ const type = rawType?.toLowerCase();
3700
+ if (type?.includes("spot")) return "spot";
3701
+ if (type?.includes("perp")) return "perp";
3702
+ if (type?.includes("option")) return "option";
3703
+ return pairParts(tradingPair)[1]?.toLowerCase() ?? "";
3704
+ }
3705
+ function inferUnderlyingType(rawType) {
3706
+ if (rawType === void 0) return void 0;
3707
+ const prefix = rawType.split("-")[0]?.trim().toLowerCase();
3708
+ return prefix && prefix !== rawType.toLowerCase() ? prefix : void 0;
3709
+ }
3710
+ function normalizeCandidate(raw, outerSymbol) {
3711
+ const tradingPair = stringValue(raw.trading_pair) ?? stringValue(raw.tradingPair) ?? stringValue(raw.symbol);
3712
+ if (tradingPair === void 0) return void 0;
3713
+ const type = stringValue(raw.type);
3714
+ const parts = pairParts(tradingPair);
3715
+ const symbol = stringValue(raw.base) ?? outerSymbol ?? (parts.length >= 4 ? parts.slice(2, -1).join("_") : parts.length === 3 ? parts[2] : tradingPair);
3716
+ const market = stringValue(raw.market) ?? stringValue(raw.exchange) ?? parts[0] ?? "";
3717
+ const quote = stringValue(raw.quote) ?? parts[parts.length - 1] ?? "";
3718
+ const instrumentType = stringValue(raw.instrument_type) ?? stringValue(raw.instrumentType) ?? inferInstrumentType(type, tradingPair);
3719
+ const underlyingType = stringValue(raw.underlying_type) ?? stringValue(raw.underlyingType) ?? inferUnderlyingType(type);
3720
+ return {
3721
+ symbol,
3722
+ tradingPair,
3723
+ market,
3724
+ instrumentType,
3725
+ ...underlyingType === void 0 ? {} : { underlyingType },
3726
+ quote,
3727
+ ...type === void 0 ? {} : { type },
3728
+ ...stringValue(raw.description) === void 0 ? {} : { description: stringValue(raw.description) },
3729
+ ...numberValue(raw.fee_rate) === void 0 ? numberValue(raw.feeRate) === void 0 ? {} : { feeRate: numberValue(raw.feeRate) } : { feeRate: numberValue(raw.fee_rate) },
3730
+ ...stringValue(raw.symbol_icon_url) === void 0 ? stringValue(raw.symbolIconUrl) === void 0 ? {} : { symbolIconUrl: stringValue(raw.symbolIconUrl) } : { symbolIconUrl: stringValue(raw.symbol_icon_url) }
3731
+ };
3732
+ }
3733
+ function flattenResponse(value) {
3734
+ if (!isRecord(value)) return [];
3735
+ const flat = value.trading_pairs;
3736
+ if (Array.isArray(flat)) {
3737
+ return flat.flatMap(
3738
+ (item) => isRecord(item) ? [normalizeCandidate(item)].filter(
3739
+ (candidate) => candidate !== void 0
3740
+ ) : []
3741
+ );
3742
+ }
3743
+ const data = value.data;
3744
+ if (!Array.isArray(data)) return [];
3745
+ const candidates = [];
3746
+ for (const symbolGroup of data) {
3747
+ if (!isRecord(symbolGroup)) continue;
3748
+ const symbol = stringValue(symbolGroup.symbol);
3749
+ const groups = symbolGroup.trading_pairs;
3750
+ if (!Array.isArray(groups)) continue;
3751
+ for (const group of groups) {
3752
+ if (!isRecord(group) || !Array.isArray(group.pairs)) continue;
3753
+ for (const pair of group.pairs) {
3754
+ if (!isRecord(pair)) continue;
3755
+ const candidate = normalizeCandidate(
3756
+ {
3757
+ ...pair,
3758
+ instrument_type: pair.instrument_type ?? group.instrument_type
3759
+ },
3760
+ symbol
3761
+ );
3762
+ if (candidate !== void 0) candidates.push(candidate);
3763
+ }
3764
+ }
3765
+ }
3766
+ return candidates;
3767
+ }
3768
+ function matchesQuery(candidate, query) {
3769
+ const expected = query.trim();
3770
+ if (candidate.tradingPair === expected) return true;
3771
+ return upper(candidate.symbol) === upper(expected);
3772
+ }
3773
+ function matchesFilter(value, expected) {
3774
+ return expected === void 0 || upper(value) === upper(expected);
3775
+ }
3776
+ function dedupe(candidates) {
3777
+ const seen = /* @__PURE__ */ new Set();
3778
+ return candidates.filter((candidate) => {
3779
+ if (seen.has(candidate.tradingPair)) return false;
3780
+ seen.add(candidate.tradingPair);
3781
+ return true;
3782
+ });
3783
+ }
3784
+ function resolveFilters(params) {
3785
+ const record2 = isRecord(params) ? params : {};
3786
+ return {
3787
+ market: typeof record2.market === "string" ? record2.market : void 0,
3788
+ instrumentType: typeof record2.instrumentType === "string" ? record2.instrumentType : void 0,
3789
+ underlyingType: typeof record2.underlyingType === "string" ? record2.underlyingType : void 0,
3790
+ quote: typeof record2.quote === "string" ? record2.quote : void 0
3791
+ };
3792
+ }
3793
+ function pairSearchParams(pair, params) {
3794
+ const parts = pair.split("_");
3795
+ const market = parts[0];
3796
+ const instrumentType = parts[1];
3797
+ const symbol = parts.length >= 4 ? parts.slice(2, -1).join("_") : parts.length === 3 ? parts[2] : void 0;
3798
+ const quote = parts.at(-1);
3799
+ if (!market || !instrumentType || !symbol || !quote) {
3800
+ return { symbol: pair, ...params };
3801
+ }
3802
+ return {
3803
+ symbol,
3804
+ market: params.market ?? market,
3805
+ instrumentType: params.instrumentType ?? instrumentType,
3806
+ underlyingType: params.underlyingType,
3807
+ quote: params.quote ?? quote
3808
+ };
3809
+ }
3810
+ var TradingPairsResource = class {
3811
+ constructor(client) {
3812
+ this.client = client;
3813
+ }
3814
+ client;
3815
+ async search(params) {
3816
+ this.client._requireAuth();
3817
+ const rawSymbol = isRecord(params) ? params.symbol : void 0;
3818
+ const query = typeof rawSymbol === "string" ? rawSymbol.trim() : "";
3819
+ if (!query)
3820
+ throw new AlvaError("INVALID_ARGUMENT", "symbol is required", 400);
3821
+ const response = await this.client._request(
3822
+ "GET",
3823
+ "/api/v1/trading-pairs/search",
3824
+ { query: { q: query, strict: true } }
3825
+ );
3826
+ const candidates = dedupe(flattenResponse(response)).filter((candidate) => matchesQuery(candidate, query)).filter((candidate) => matchesFilter(candidate.market, params.market)).filter(
3827
+ (candidate) => matchesFilter(candidate.instrumentType, params.instrumentType)
3828
+ ).filter(
3829
+ (candidate) => matchesFilter(candidate.underlyingType, params.underlyingType)
3830
+ ).filter((candidate) => matchesFilter(candidate.quote, params.quote));
3831
+ const limit = params.limit;
3832
+ if (limit !== void 0 && candidates.length > limit) {
3833
+ return { query, candidates: candidates.slice(0, limit), truncated: true };
3834
+ }
3835
+ return { query, candidates };
3836
+ }
3837
+ async resolve(params) {
3838
+ const record2 = isRecord(params) ? params : {};
3839
+ const pair = typeof record2.pair === "string" ? record2.pair.trim() : void 0;
3840
+ const filters = resolveFilters(params);
3841
+ const searchParams = pair === void 0 ? {
3842
+ symbol: typeof record2.symbol === "string" ? record2.symbol : "",
3843
+ ...filters
3844
+ } : pairSearchParams(pair, filters);
3845
+ const result = await this.search(searchParams);
3846
+ const candidates = pair === void 0 ? result.candidates : result.candidates.filter(
3847
+ (candidate) => candidate.tradingPair === pair
3848
+ );
3849
+ if (candidates.length !== 1) {
3850
+ const detailLimit = 50;
3851
+ throw new AlvaError(
3852
+ candidates.length === 0 ? "TRADING_PAIR_NOT_FOUND" : "TRADING_PAIR_NOT_UNIQUE",
3853
+ candidates.length === 0 ? `no canonical trading pair matched "${pair ?? searchParams.symbol}"` : `multiple canonical trading pairs matched "${searchParams.symbol}"`,
3854
+ candidates.length === 0 ? 404 : 409,
3855
+ {
3856
+ query: pair ?? searchParams.symbol,
3857
+ candidateCount: candidates.length,
3858
+ candidates: candidates.slice(0, detailLimit),
3859
+ ...candidates.length > detailLimit ? { truncated: true } : {}
3860
+ }
3861
+ );
3862
+ }
3863
+ return candidates[0];
3864
+ }
3865
+ };
3866
+
3552
3867
  // src/client.ts
3553
3868
  var DEFAULT_BASE_URL = "https://api-llm.prd.alva.ai";
3554
3869
  var DEFAULT_ARRAYS_BASE_URL = "https://data-tools.prd.space.id";
3555
- function isRecord(value) {
3870
+ function isRecord2(value) {
3556
3871
  return typeof value === "object" && value !== null;
3557
3872
  }
3558
3873
  function stringField(value, field) {
3559
- if (!isRecord(value)) return void 0;
3874
+ if (!isRecord2(value)) return void 0;
3560
3875
  const fieldValue = value[field];
3561
3876
  return typeof fieldValue === "string" && fieldValue ? fieldValue : void 0;
3562
3877
  }
@@ -3570,7 +3885,7 @@ function describeCause(cause) {
3570
3885
  if (cause.message) details.message = cause.message;
3571
3886
  const code = stringField(cause, "code");
3572
3887
  if (code) details.code = code;
3573
- } else if (isRecord(cause)) {
3888
+ } else if (isRecord2(cause)) {
3574
3889
  const code = stringField(cause, "code");
3575
3890
  const name = stringField(cause, "name");
3576
3891
  const message = stringField(cause, "message");
@@ -3598,7 +3913,7 @@ function describeFetchFailure(err) {
3598
3913
  details.message = String(err);
3599
3914
  }
3600
3915
  const { message: causeMessage, details: causeDetails } = describeCause(
3601
- isRecord(err) ? err.cause : void 0
3916
+ isRecord2(err) ? err.cause : void 0
3602
3917
  );
3603
3918
  if (causeDetails) {
3604
3919
  details.cause = causeDetails;
@@ -3635,6 +3950,7 @@ var AlvaClient = class {
3635
3950
  _serviceAccount;
3636
3951
  _release;
3637
3952
  _feed;
3953
+ _forYou;
3638
3954
  _automation;
3639
3955
  _playbooks;
3640
3956
  _secrets;
@@ -3658,6 +3974,7 @@ var AlvaClient = class {
3658
3974
  _credits;
3659
3975
  _markets;
3660
3976
  _schedules;
3977
+ _tradingPairs;
3661
3978
  constructor(config) {
3662
3979
  this.baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;
3663
3980
  this.arraysBaseUrl = config.arraysBaseUrl ?? DEFAULT_ARRAYS_BASE_URL;
@@ -3755,6 +4072,9 @@ var AlvaClient = class {
3755
4072
  get markets() {
3756
4073
  return this._markets ??= new MarketsResource(this);
3757
4074
  }
4075
+ get tradingPairs() {
4076
+ return this._tradingPairs ??= new TradingPairsResource(this);
4077
+ }
3758
4078
  get schedules() {
3759
4079
  return this._schedules ??= new SchedulesResource(this);
3760
4080
  }
@@ -3767,6 +4087,9 @@ var AlvaClient = class {
3767
4087
  );
3768
4088
  }
3769
4089
  }
4090
+ get forYou() {
4091
+ return this._forYou ??= new ForYouResource(this);
4092
+ }
3770
4093
  async _request(method, path, options) {
3771
4094
  const baseUrl = options?.baseUrl ?? this.baseUrl;
3772
4095
  let url = `${baseUrl}${path}`;
@@ -4371,7 +4694,7 @@ var installPlaybookRuntime = (targetWindow) => {
4371
4694
  };
4372
4695
 
4373
4696
  // src/index.ts
4374
- var VERSION = true ? "0.26.0" : "dev";
4697
+ var VERSION = true ? "0.28.0-beta.0" : "dev";
4375
4698
  // Annotate the CommonJS export names for ESM import in node:
4376
4699
  0 && (module.exports = {
4377
4700
  AlertsResource,
@@ -4380,12 +4703,14 @@ var VERSION = true ? "0.26.0" : "dev";
4380
4703
  AutomationAlertDeliveryResource,
4381
4704
  AutomationResource,
4382
4705
  CliUsageError,
4706
+ ForYouResource,
4383
4707
  MarketsResource,
4384
4708
  PBSV_UPDATE_MESSAGE,
4385
4709
  SUBSCRIBE_MANAGE_MESSAGE,
4386
4710
  SUBSCRIBE_PROPOSE_MESSAGE,
4387
4711
  SUBSCRIBE_RESULT_MESSAGE,
4388
4712
  SchedulesResource,
4713
+ TradingPairsResource,
4389
4714
  UDF_AUTH_REQUIRED_MESSAGE,
4390
4715
  UDF_CONSENT_REQUEST_MESSAGE,
4391
4716
  UDF_CONSENT_RESPONSE_MESSAGE,