@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.js CHANGED
@@ -673,6 +673,134 @@ function requireFeedID(id) {
673
673
  return id;
674
674
  }
675
675
 
676
+ // src/resources/forYou.ts
677
+ var FOR_YOU_QUERY = `
678
+ query ToolkitForYou($input: FeedEntryConnectionInput) {
679
+ viewer {
680
+ forYou(input: $input) {
681
+ edges {
682
+ cursor
683
+ node {
684
+ id
685
+ feed { id }
686
+ major { id feedId number }
687
+ displayName source eventTimeMs publishedAtMs title body
688
+ actions { type label url prompt }
689
+ presentation {
690
+ card {
691
+ accentColor url thumbnailUrl footer
692
+ fields { label value inline }
693
+ }
694
+ }
695
+ tickers { symbol logoUrl sentiment }
696
+ media { type coverUrl url }
697
+ sources { type url iconUrl title subtitle description publishedAtMs }
698
+ }
699
+ }
700
+ pageInfo { startCursor endCursor hasNextPage hasPreviousPage }
701
+ }
702
+ }
703
+ }
704
+ `.trim();
705
+ function record(value) {
706
+ return typeof value === "object" && value !== null && !Array.isArray(value);
707
+ }
708
+ function validateForYouListParams(params) {
709
+ if (!record(params)) throw new Error("For You parameters must be an object");
710
+ const first = params.first === void 0 ? 20 : params.first;
711
+ if (typeof first !== "number" || !Number.isInteger(first) || first < 1 || first > 50) {
712
+ throw new Error("first must be an integer between 1 and 50");
713
+ }
714
+ for (const field of ["after", "newerThan"]) {
715
+ const value = params[field];
716
+ if (value !== void 0 && (typeof value !== "string" || !value.trim())) {
717
+ throw new Error(`${field} must be a non-empty cursor`);
718
+ }
719
+ }
720
+ if (params.feedId !== void 0 && !isPositiveInt64(params.feedId)) {
721
+ throw new Error("feedId must be a positive decimal int64 string");
722
+ }
723
+ }
724
+ function isPositiveInt64(value) {
725
+ return typeof value === "string" && /^[1-9]\d{0,18}$/.test(value) && BigInt(value) <= 9223372036854775807n;
726
+ }
727
+ function invalidResponse() {
728
+ throw new AlvaError(
729
+ "GRAPHQL_INVALID_RESPONSE",
730
+ "GraphQL returned an invalid For You connection",
731
+ 502
732
+ );
733
+ }
734
+ function connection(value) {
735
+ if (!record(value) || !Array.isArray(value.edges) || !record(value.pageInfo)) {
736
+ return invalidResponse();
737
+ }
738
+ const page = value.pageInfo;
739
+ if (typeof page.startCursor !== "string" || typeof page.endCursor !== "string" || typeof page.hasNextPage !== "boolean" || typeof page.hasPreviousPage !== "boolean") {
740
+ return invalidResponse();
741
+ }
742
+ for (const edge of value.edges) {
743
+ if (!record(edge) || typeof edge.cursor !== "string" || !edge.cursor.trim() || !record(edge.node))
744
+ return invalidResponse();
745
+ const node = edge.node;
746
+ 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") {
747
+ return invalidResponse();
748
+ }
749
+ }
750
+ const first = value.edges[0];
751
+ const last = value.edges[value.edges.length - 1];
752
+ if (page.startCursor !== (first?.cursor ?? "") || page.endCursor !== (last?.cursor ?? "") || value.edges.length === 0 && page.hasNextPage)
753
+ return invalidResponse();
754
+ return value;
755
+ }
756
+ var ForYouResource = class {
757
+ constructor(client) {
758
+ this.client = client;
759
+ }
760
+ client;
761
+ /** One newest-first page. Does not truncate content or advance a watermark. */
762
+ async list(params = {}) {
763
+ validateForYouListParams(params);
764
+ this.client._requireAuth();
765
+ const response = await this.client._request("POST", "/query", {
766
+ body: {
767
+ query: FOR_YOU_QUERY,
768
+ variables: {
769
+ input: {
770
+ first: params.first ?? 20,
771
+ after: params.after,
772
+ newerThan: params.newerThan,
773
+ feedId: params.feedId
774
+ }
775
+ }
776
+ }
777
+ });
778
+ if (!record(response)) return invalidResponse();
779
+ if (response.errors !== void 0) {
780
+ if (!Array.isArray(response.errors)) return invalidResponse();
781
+ if (response.errors.length > 0) {
782
+ const messages = response.errors.flatMap(
783
+ (error) => record(error) && typeof error.message === "string" ? [error.message] : []
784
+ );
785
+ throw new AlvaError(
786
+ "GRAPHQL_ERROR",
787
+ messages.join("; ") || "GraphQL request failed",
788
+ 400,
789
+ { errors: response.errors }
790
+ );
791
+ }
792
+ }
793
+ if (!record(response.data) || !record(response.data.viewer) || response.data.viewer.forYou == null) {
794
+ throw new AlvaError(
795
+ "GRAPHQL_EMPTY_RESPONSE",
796
+ "GraphQL response did not include viewer.forYou",
797
+ 502
798
+ );
799
+ }
800
+ return connection(response.data.viewer.forYou);
801
+ }
802
+ };
803
+
676
804
  // src/resources/automation.ts
677
805
  var AUTOMATION_ALERT_DELIVERY_QUERY = `
678
806
  query ToolkitAutomationAlertDelivery($automationId: ID!) {
@@ -2225,8 +2353,8 @@ var NotificationsResource = class {
2225
2353
  client;
2226
2354
  /**
2227
2355
  * List the caller's notification history for one feed
2228
- * `(username, name)`. Authorization is alfs read on
2229
- * `/alva/home/<username>/feeds/<name>`.
2356
+ * `(username, name)`. Authorization uses the backend's canonical Feed read
2357
+ * decision (owner, public, bundled paid access, Plan, or Access Group).
2230
2358
  */
2231
2359
  async listFeed(params) {
2232
2360
  this.client._requireAuth();
@@ -3185,14 +3313,14 @@ var SchedulesResource = class {
3185
3313
  LIST_SCHEDULES,
3186
3314
  { channelId: id, after }
3187
3315
  );
3188
- const connection = data.viewer?.channel?.schedules;
3189
- if (!connection?.edges) throw scheduleNotFound();
3190
- for (const edge of connection.edges) {
3316
+ const connection2 = data.viewer?.channel?.schedules;
3317
+ if (!connection2?.edges) throw scheduleNotFound();
3318
+ for (const edge of connection2.edges) {
3191
3319
  if (!edge?.node) throw scheduleEmptyResponse();
3192
3320
  schedules.push(fromWireSchedule(edge.node));
3193
3321
  }
3194
- if (connection.pageInfo?.hasNextPage !== true) return schedules;
3195
- const next = connection.pageInfo.endCursor;
3322
+ if (connection2.pageInfo?.hasNextPage !== true) return schedules;
3323
+ const next = connection2.pageInfo.endCursor;
3196
3324
  if (!next || seenCursors.has(next)) throw scheduleEmptyResponse();
3197
3325
  seenCursors.add(next);
3198
3326
  after = next;
@@ -3488,14 +3616,199 @@ function scheduleEmptyResponse() {
3488
3616
  );
3489
3617
  }
3490
3618
 
3619
+ // src/resources/tradingPairs.ts
3620
+ function isRecord(value) {
3621
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3622
+ }
3623
+ function stringValue(value) {
3624
+ return typeof value === "string" && value.trim() !== "" ? value : void 0;
3625
+ }
3626
+ function numberValue(value) {
3627
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
3628
+ }
3629
+ function upper(value) {
3630
+ return value === void 0 ? void 0 : value.trim().toUpperCase();
3631
+ }
3632
+ function pairParts(pair) {
3633
+ return pair.split("_");
3634
+ }
3635
+ function inferInstrumentType(rawType, tradingPair) {
3636
+ const type = rawType?.toLowerCase();
3637
+ if (type?.includes("spot")) return "spot";
3638
+ if (type?.includes("perp")) return "perp";
3639
+ if (type?.includes("option")) return "option";
3640
+ return pairParts(tradingPair)[1]?.toLowerCase() ?? "";
3641
+ }
3642
+ function inferUnderlyingType(rawType) {
3643
+ if (rawType === void 0) return void 0;
3644
+ const prefix = rawType.split("-")[0]?.trim().toLowerCase();
3645
+ return prefix && prefix !== rawType.toLowerCase() ? prefix : void 0;
3646
+ }
3647
+ function normalizeCandidate(raw, outerSymbol) {
3648
+ const tradingPair = stringValue(raw.trading_pair) ?? stringValue(raw.tradingPair) ?? stringValue(raw.symbol);
3649
+ if (tradingPair === void 0) return void 0;
3650
+ const type = stringValue(raw.type);
3651
+ const parts = pairParts(tradingPair);
3652
+ const symbol = stringValue(raw.base) ?? outerSymbol ?? (parts.length >= 4 ? parts.slice(2, -1).join("_") : parts.length === 3 ? parts[2] : tradingPair);
3653
+ const market = stringValue(raw.market) ?? stringValue(raw.exchange) ?? parts[0] ?? "";
3654
+ const quote = stringValue(raw.quote) ?? parts[parts.length - 1] ?? "";
3655
+ const instrumentType = stringValue(raw.instrument_type) ?? stringValue(raw.instrumentType) ?? inferInstrumentType(type, tradingPair);
3656
+ const underlyingType = stringValue(raw.underlying_type) ?? stringValue(raw.underlyingType) ?? inferUnderlyingType(type);
3657
+ return {
3658
+ symbol,
3659
+ tradingPair,
3660
+ market,
3661
+ instrumentType,
3662
+ ...underlyingType === void 0 ? {} : { underlyingType },
3663
+ quote,
3664
+ ...type === void 0 ? {} : { type },
3665
+ ...stringValue(raw.description) === void 0 ? {} : { description: stringValue(raw.description) },
3666
+ ...numberValue(raw.fee_rate) === void 0 ? numberValue(raw.feeRate) === void 0 ? {} : { feeRate: numberValue(raw.feeRate) } : { feeRate: numberValue(raw.fee_rate) },
3667
+ ...stringValue(raw.symbol_icon_url) === void 0 ? stringValue(raw.symbolIconUrl) === void 0 ? {} : { symbolIconUrl: stringValue(raw.symbolIconUrl) } : { symbolIconUrl: stringValue(raw.symbol_icon_url) }
3668
+ };
3669
+ }
3670
+ function flattenResponse(value) {
3671
+ if (!isRecord(value)) return [];
3672
+ const flat = value.trading_pairs;
3673
+ if (Array.isArray(flat)) {
3674
+ return flat.flatMap(
3675
+ (item) => isRecord(item) ? [normalizeCandidate(item)].filter(
3676
+ (candidate) => candidate !== void 0
3677
+ ) : []
3678
+ );
3679
+ }
3680
+ const data = value.data;
3681
+ if (!Array.isArray(data)) return [];
3682
+ const candidates = [];
3683
+ for (const symbolGroup of data) {
3684
+ if (!isRecord(symbolGroup)) continue;
3685
+ const symbol = stringValue(symbolGroup.symbol);
3686
+ const groups = symbolGroup.trading_pairs;
3687
+ if (!Array.isArray(groups)) continue;
3688
+ for (const group of groups) {
3689
+ if (!isRecord(group) || !Array.isArray(group.pairs)) continue;
3690
+ for (const pair of group.pairs) {
3691
+ if (!isRecord(pair)) continue;
3692
+ const candidate = normalizeCandidate(
3693
+ {
3694
+ ...pair,
3695
+ instrument_type: pair.instrument_type ?? group.instrument_type
3696
+ },
3697
+ symbol
3698
+ );
3699
+ if (candidate !== void 0) candidates.push(candidate);
3700
+ }
3701
+ }
3702
+ }
3703
+ return candidates;
3704
+ }
3705
+ function matchesQuery(candidate, query) {
3706
+ const expected = query.trim();
3707
+ if (candidate.tradingPair === expected) return true;
3708
+ return upper(candidate.symbol) === upper(expected);
3709
+ }
3710
+ function matchesFilter(value, expected) {
3711
+ return expected === void 0 || upper(value) === upper(expected);
3712
+ }
3713
+ function dedupe(candidates) {
3714
+ const seen = /* @__PURE__ */ new Set();
3715
+ return candidates.filter((candidate) => {
3716
+ if (seen.has(candidate.tradingPair)) return false;
3717
+ seen.add(candidate.tradingPair);
3718
+ return true;
3719
+ });
3720
+ }
3721
+ function resolveFilters(params) {
3722
+ const record2 = isRecord(params) ? params : {};
3723
+ return {
3724
+ market: typeof record2.market === "string" ? record2.market : void 0,
3725
+ instrumentType: typeof record2.instrumentType === "string" ? record2.instrumentType : void 0,
3726
+ underlyingType: typeof record2.underlyingType === "string" ? record2.underlyingType : void 0,
3727
+ quote: typeof record2.quote === "string" ? record2.quote : void 0
3728
+ };
3729
+ }
3730
+ function pairSearchParams(pair, params) {
3731
+ const parts = pair.split("_");
3732
+ const market = parts[0];
3733
+ const instrumentType = parts[1];
3734
+ const symbol = parts.length >= 4 ? parts.slice(2, -1).join("_") : parts.length === 3 ? parts[2] : void 0;
3735
+ const quote = parts.at(-1);
3736
+ if (!market || !instrumentType || !symbol || !quote) {
3737
+ return { symbol: pair, ...params };
3738
+ }
3739
+ return {
3740
+ symbol,
3741
+ market: params.market ?? market,
3742
+ instrumentType: params.instrumentType ?? instrumentType,
3743
+ underlyingType: params.underlyingType,
3744
+ quote: params.quote ?? quote
3745
+ };
3746
+ }
3747
+ var TradingPairsResource = class {
3748
+ constructor(client) {
3749
+ this.client = client;
3750
+ }
3751
+ client;
3752
+ async search(params) {
3753
+ this.client._requireAuth();
3754
+ const rawSymbol = isRecord(params) ? params.symbol : void 0;
3755
+ const query = typeof rawSymbol === "string" ? rawSymbol.trim() : "";
3756
+ if (!query)
3757
+ throw new AlvaError("INVALID_ARGUMENT", "symbol is required", 400);
3758
+ const response = await this.client._request(
3759
+ "GET",
3760
+ "/api/v1/trading-pairs/search",
3761
+ { query: { q: query, strict: true } }
3762
+ );
3763
+ const candidates = dedupe(flattenResponse(response)).filter((candidate) => matchesQuery(candidate, query)).filter((candidate) => matchesFilter(candidate.market, params.market)).filter(
3764
+ (candidate) => matchesFilter(candidate.instrumentType, params.instrumentType)
3765
+ ).filter(
3766
+ (candidate) => matchesFilter(candidate.underlyingType, params.underlyingType)
3767
+ ).filter((candidate) => matchesFilter(candidate.quote, params.quote));
3768
+ const limit = params.limit;
3769
+ if (limit !== void 0 && candidates.length > limit) {
3770
+ return { query, candidates: candidates.slice(0, limit), truncated: true };
3771
+ }
3772
+ return { query, candidates };
3773
+ }
3774
+ async resolve(params) {
3775
+ const record2 = isRecord(params) ? params : {};
3776
+ const pair = typeof record2.pair === "string" ? record2.pair.trim() : void 0;
3777
+ const filters = resolveFilters(params);
3778
+ const searchParams = pair === void 0 ? {
3779
+ symbol: typeof record2.symbol === "string" ? record2.symbol : "",
3780
+ ...filters
3781
+ } : pairSearchParams(pair, filters);
3782
+ const result = await this.search(searchParams);
3783
+ const candidates = pair === void 0 ? result.candidates : result.candidates.filter(
3784
+ (candidate) => candidate.tradingPair === pair
3785
+ );
3786
+ if (candidates.length !== 1) {
3787
+ const detailLimit = 50;
3788
+ throw new AlvaError(
3789
+ candidates.length === 0 ? "TRADING_PAIR_NOT_FOUND" : "TRADING_PAIR_NOT_UNIQUE",
3790
+ candidates.length === 0 ? `no canonical trading pair matched "${pair ?? searchParams.symbol}"` : `multiple canonical trading pairs matched "${searchParams.symbol}"`,
3791
+ candidates.length === 0 ? 404 : 409,
3792
+ {
3793
+ query: pair ?? searchParams.symbol,
3794
+ candidateCount: candidates.length,
3795
+ candidates: candidates.slice(0, detailLimit),
3796
+ ...candidates.length > detailLimit ? { truncated: true } : {}
3797
+ }
3798
+ );
3799
+ }
3800
+ return candidates[0];
3801
+ }
3802
+ };
3803
+
3491
3804
  // src/client.ts
3492
3805
  var DEFAULT_BASE_URL = "https://api-llm.prd.alva.ai";
3493
3806
  var DEFAULT_ARRAYS_BASE_URL = "https://data-tools.prd.space.id";
3494
- function isRecord(value) {
3807
+ function isRecord2(value) {
3495
3808
  return typeof value === "object" && value !== null;
3496
3809
  }
3497
3810
  function stringField(value, field) {
3498
- if (!isRecord(value)) return void 0;
3811
+ if (!isRecord2(value)) return void 0;
3499
3812
  const fieldValue = value[field];
3500
3813
  return typeof fieldValue === "string" && fieldValue ? fieldValue : void 0;
3501
3814
  }
@@ -3509,7 +3822,7 @@ function describeCause(cause) {
3509
3822
  if (cause.message) details.message = cause.message;
3510
3823
  const code = stringField(cause, "code");
3511
3824
  if (code) details.code = code;
3512
- } else if (isRecord(cause)) {
3825
+ } else if (isRecord2(cause)) {
3513
3826
  const code = stringField(cause, "code");
3514
3827
  const name = stringField(cause, "name");
3515
3828
  const message = stringField(cause, "message");
@@ -3537,7 +3850,7 @@ function describeFetchFailure(err) {
3537
3850
  details.message = String(err);
3538
3851
  }
3539
3852
  const { message: causeMessage, details: causeDetails } = describeCause(
3540
- isRecord(err) ? err.cause : void 0
3853
+ isRecord2(err) ? err.cause : void 0
3541
3854
  );
3542
3855
  if (causeDetails) {
3543
3856
  details.cause = causeDetails;
@@ -3574,6 +3887,7 @@ var AlvaClient = class {
3574
3887
  _serviceAccount;
3575
3888
  _release;
3576
3889
  _feed;
3890
+ _forYou;
3577
3891
  _automation;
3578
3892
  _playbooks;
3579
3893
  _secrets;
@@ -3597,6 +3911,7 @@ var AlvaClient = class {
3597
3911
  _credits;
3598
3912
  _markets;
3599
3913
  _schedules;
3914
+ _tradingPairs;
3600
3915
  constructor(config) {
3601
3916
  this.baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;
3602
3917
  this.arraysBaseUrl = config.arraysBaseUrl ?? DEFAULT_ARRAYS_BASE_URL;
@@ -3694,6 +4009,9 @@ var AlvaClient = class {
3694
4009
  get markets() {
3695
4010
  return this._markets ??= new MarketsResource(this);
3696
4011
  }
4012
+ get tradingPairs() {
4013
+ return this._tradingPairs ??= new TradingPairsResource(this);
4014
+ }
3697
4015
  get schedules() {
3698
4016
  return this._schedules ??= new SchedulesResource(this);
3699
4017
  }
@@ -3706,6 +4024,9 @@ var AlvaClient = class {
3706
4024
  );
3707
4025
  }
3708
4026
  }
4027
+ get forYou() {
4028
+ return this._forYou ??= new ForYouResource(this);
4029
+ }
3709
4030
  async _request(method, path, options) {
3710
4031
  const baseUrl = options?.baseUrl ?? this.baseUrl;
3711
4032
  let url = `${baseUrl}${path}`;
@@ -4310,7 +4631,7 @@ var installPlaybookRuntime = (targetWindow) => {
4310
4631
  };
4311
4632
 
4312
4633
  // src/index.ts
4313
- var VERSION = true ? "0.26.0" : "dev";
4634
+ var VERSION = true ? "0.28.0-beta.0" : "dev";
4314
4635
  export {
4315
4636
  AlertsResource,
4316
4637
  AlvaClient,
@@ -4318,12 +4639,14 @@ export {
4318
4639
  AutomationAlertDeliveryResource,
4319
4640
  AutomationResource,
4320
4641
  CliUsageError,
4642
+ ForYouResource,
4321
4643
  MarketsResource,
4322
4644
  PBSV_UPDATE_MESSAGE,
4323
4645
  SUBSCRIBE_MANAGE_MESSAGE,
4324
4646
  SUBSCRIBE_PROPOSE_MESSAGE,
4325
4647
  SUBSCRIBE_RESULT_MESSAGE,
4326
4648
  SchedulesResource,
4649
+ TradingPairsResource,
4327
4650
  UDF_AUTH_REQUIRED_MESSAGE,
4328
4651
  UDF_CONSENT_REQUEST_MESSAGE,
4329
4652
  UDF_CONSENT_RESPONSE_MESSAGE,