@alva-ai/toolkit 0.29.0 → 0.31.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
@@ -754,6 +754,166 @@ function connection(value) {
754
754
  return invalidResponse();
755
755
  return value;
756
756
  }
757
+ var THESIS_RECOMMENDATION_QUERY = `
758
+ query ToolkitForYouTheses($input: ThesisRecommendationInput) {
759
+ viewer {
760
+ thesisRecommendations(input: $input) {
761
+ listId pageCursor nextCursor exhausted scanLimited
762
+ pageInfo { startCursor endCursor hasNextPage hasPreviousPage }
763
+ edges {
764
+ cursor
765
+ node {
766
+ itemKey
767
+ publication {
768
+ thesisId playbookId authorVersionId materialVersionId itemKey
769
+ title body publishedAtMs changeKind visibility
770
+ closed archived note closingNote researchPaused
771
+ entityIds categoryIds
772
+ entityStances { entityId stance }
773
+ entities { id ticker name }
774
+ publisher {
775
+ id displayName avatarUrl bio followersCount
776
+ viewerState { following }
777
+ }
778
+ medias { type coverUrl url }
779
+ signalFeed { id }
780
+ snapshotRelease {
781
+ versionId materialVersionId publishedAtMs changeKind
782
+ sourceRefs {
783
+ title sourceKind sourceContentId publicUrl sourceTimeMs locator
784
+ }
785
+ }
786
+ }
787
+ }
788
+ }
789
+ }
790
+ }
791
+ }
792
+ `.trim();
793
+ function validateForYouThesesParams(params) {
794
+ if (!record(params)) throw new Error("Thesis parameters must be an object");
795
+ const first = params.first === void 0 ? 10 : params.first;
796
+ if (typeof first !== "number" || !Number.isInteger(first) || first < 1 || first > 10) {
797
+ throw new Error("first must be an integer between 1 and 10");
798
+ }
799
+ if (params.after !== void 0 && (typeof params.after !== "string" || !params.after.trim())) {
800
+ throw new Error("after must be a non-empty cursor");
801
+ }
802
+ }
803
+ function graphqlViewerField(response, field) {
804
+ if (!record(response)) {
805
+ throw new AlvaError(
806
+ "GRAPHQL_INVALID_RESPONSE",
807
+ `GraphQL returned an invalid viewer.${field} response`,
808
+ 502
809
+ );
810
+ }
811
+ if (response.errors !== void 0) {
812
+ if (!Array.isArray(response.errors)) {
813
+ throw new AlvaError(
814
+ "GRAPHQL_INVALID_RESPONSE",
815
+ `GraphQL returned an invalid viewer.${field} response`,
816
+ 502
817
+ );
818
+ }
819
+ if (response.errors.length > 0) {
820
+ const messages = response.errors.flatMap(
821
+ (error) => record(error) && typeof error.message === "string" ? [error.message] : []
822
+ );
823
+ throw new AlvaError(
824
+ "GRAPHQL_ERROR",
825
+ messages.join("; ") || "GraphQL request failed",
826
+ 400,
827
+ { errors: response.errors }
828
+ );
829
+ }
830
+ }
831
+ if (!record(response.data) || !record(response.data.viewer) || response.data.viewer[field] == null) {
832
+ throw new AlvaError(
833
+ "GRAPHQL_EMPTY_RESPONSE",
834
+ `GraphQL response did not include viewer.${field}`,
835
+ 502
836
+ );
837
+ }
838
+ return response.data.viewer[field];
839
+ }
840
+ function invalidPage() {
841
+ throw new AlvaError(
842
+ "GRAPHQL_INVALID_RESPONSE",
843
+ "GraphQL returned an invalid Thesis recommendation page",
844
+ 502
845
+ );
846
+ }
847
+ function positiveInt64List(value) {
848
+ return Array.isArray(value) && value.every(isPositiveInt64);
849
+ }
850
+ function stanceList(value) {
851
+ return Array.isArray(value) && value.every(
852
+ (item) => record(item) && isPositiveInt64(item.entityId) && typeof item.stance === "string" && item.stance.trim() !== ""
853
+ );
854
+ }
855
+ function entityList(value) {
856
+ return Array.isArray(value) && value.every(
857
+ (item) => record(item) && typeof item.id === "string" && item.id.trim() !== "" && typeof item.ticker === "string" && typeof item.name === "string"
858
+ );
859
+ }
860
+ function mediaList(value) {
861
+ return Array.isArray(value) && value.every(
862
+ (item) => record(item) && typeof item.type === "string" && item.type.trim() !== "" && typeof item.coverUrl === "string" && (item.url === null || typeof item.url === "string")
863
+ );
864
+ }
865
+ function sourceRefList(value) {
866
+ return Array.isArray(value) && value.every(
867
+ (item) => record(item) && (item.title === null || typeof item.title === "string") && typeof item.sourceKind === "string" && typeof item.sourceContentId === "string" && typeof item.publicUrl === "string" && nullableMs(item.sourceTimeMs) && typeof item.locator === "string"
868
+ );
869
+ }
870
+ function nullableMs(value) {
871
+ return value === null || typeof value === "number" && Number.isFinite(value);
872
+ }
873
+ function snapshot(value) {
874
+ return record(value) && isPositiveInt64(value.versionId) && isPositiveInt64(value.materialVersionId) && typeof value.publishedAtMs === "number" && Number.isFinite(value.publishedAtMs) && typeof value.changeKind === "string" && value.changeKind.trim() !== "" && sourceRefList(value.sourceRefs);
875
+ }
876
+ function publisher(value) {
877
+ return record(value) && typeof value.id === "string" && value.id.trim() !== "" && typeof value.displayName === "string" && typeof value.avatarUrl === "string" && typeof value.bio === "string" && typeof value.followersCount === "number" && Number.isInteger(value.followersCount) && record(value.viewerState) && (value.viewerState.following === null || typeof value.viewerState.following === "boolean");
878
+ }
879
+ function publication(value) {
880
+ if (!record(value)) return false;
881
+ for (const field of [
882
+ "thesisId",
883
+ "playbookId",
884
+ "authorVersionId",
885
+ "materialVersionId"
886
+ ]) {
887
+ if (!isPositiveInt64(value[field])) return false;
888
+ }
889
+ if (typeof value.itemKey !== "string" || !value.itemKey.trim() || typeof value.title !== "string" || typeof value.body !== "string" || typeof value.publishedAtMs !== "number" || !Number.isFinite(value.publishedAtMs) || typeof value.changeKind !== "string" || !value.changeKind.trim() || typeof value.visibility !== "string" || typeof value.note !== "string" || typeof value.closingNote !== "string") {
890
+ return false;
891
+ }
892
+ for (const field of ["closed", "archived", "researchPaused"]) {
893
+ if (typeof value[field] !== "boolean") return false;
894
+ }
895
+ if (!positiveInt64List(value.entityIds) || !positiveInt64List(value.categoryIds) || !stanceList(value.entityStances) || !entityList(value.entities) || !mediaList(value.medias) || !publisher(value.publisher) || !snapshot(value.snapshotRelease)) {
896
+ return false;
897
+ }
898
+ return value.signalFeed === null || record(value.signalFeed) && isPositiveInt64(value.signalFeed.id);
899
+ }
900
+ function recommendationPage(value) {
901
+ if (!record(value) || !Array.isArray(value.edges) || !record(value.pageInfo) || typeof value.listId !== "string" || typeof value.pageCursor !== "string" || typeof value.exhausted !== "boolean" || typeof value.scanLimited !== "boolean" || value.nextCursor !== null && typeof value.nextCursor !== "string") {
902
+ return invalidPage();
903
+ }
904
+ const page = value.pageInfo;
905
+ if (typeof page.startCursor !== "string" || typeof page.endCursor !== "string" || typeof page.hasNextPage !== "boolean" || typeof page.hasPreviousPage !== "boolean" || page.hasNextPage !== (value.nextCursor !== null)) {
906
+ return invalidPage();
907
+ }
908
+ for (const edge of value.edges) {
909
+ if (!record(edge) || typeof edge.cursor !== "string" || !edge.cursor.trim() || !record(edge.node) || typeof edge.node.itemKey !== "string" || !edge.node.itemKey.trim() || !publication(edge.node.publication)) {
910
+ return invalidPage();
911
+ }
912
+ }
913
+ const first = value.edges[0];
914
+ if (page.startCursor !== (first?.cursor ?? "")) return invalidPage();
915
+ return value;
916
+ }
757
917
  var ForYouResource = class {
758
918
  constructor(client) {
759
919
  this.client = client;
@@ -776,29 +936,29 @@ var ForYouResource = class {
776
936
  }
777
937
  }
778
938
  });
779
- if (!record(response)) return invalidResponse();
780
- if (response.errors !== void 0) {
781
- if (!Array.isArray(response.errors)) return invalidResponse();
782
- if (response.errors.length > 0) {
783
- const messages = response.errors.flatMap(
784
- (error) => record(error) && typeof error.message === "string" ? [error.message] : []
785
- );
786
- throw new AlvaError(
787
- "GRAPHQL_ERROR",
788
- messages.join("; ") || "GraphQL request failed",
789
- 400,
790
- { errors: response.errors }
791
- );
939
+ return connection(graphqlViewerField(response, "forYou"));
940
+ }
941
+ /**
942
+ * One ranked page of Thesis recommendations -- the stream the Feed App reads,
943
+ * which is not the chronological `list` stream. Page to `exhausted` and filter
944
+ * on `publication.publishedAtMs` yourself; the order is slot-mixed, so a time
945
+ * bound is never a reason to stop paging. Publications the viewer already saw
946
+ * are withheld by an upstream cooldown, so a window read is "recommended and
947
+ * recent", not every publication in the window.
948
+ */
949
+ async theses(params = {}) {
950
+ validateForYouThesesParams(params);
951
+ this.client._requireAuth();
952
+ const response = await this.client._request("POST", "/query", {
953
+ body: {
954
+ query: THESIS_RECOMMENDATION_QUERY,
955
+ variables: {
956
+ input: { first: params.first ?? 10, after: params.after }
957
+ }
792
958
  }
793
- }
794
- if (!record(response.data) || !record(response.data.viewer) || response.data.viewer.forYou == null) {
795
- throw new AlvaError(
796
- "GRAPHQL_EMPTY_RESPONSE",
797
- "GraphQL response did not include viewer.forYou",
798
- 502
799
- );
800
- }
801
- return connection(response.data.viewer.forYou);
959
+ });
960
+ const field = graphqlViewerField(response, "thesisRecommendations");
961
+ return recommendationPage(field);
802
962
  }
803
963
  };
804
964
 
@@ -3712,9 +3872,7 @@ function requireDeliveryId(value, label = "delivery id") {
3712
3872
  throw invalid2(`${label} must be a positive integer`);
3713
3873
  return value;
3714
3874
  }
3715
- function requireDeliveryIds(values) {
3716
- if (values.length === 0)
3717
- throw invalid2("at least one delivery id is required");
3875
+ function normalizeDeliveryIds(values) {
3718
3876
  const unique = /* @__PURE__ */ new Set();
3719
3877
  for (const value of values) {
3720
3878
  requireDeliveryId(value);
@@ -3723,6 +3881,11 @@ function requireDeliveryIds(values) {
3723
3881
  }
3724
3882
  return [...unique];
3725
3883
  }
3884
+ function requireDeliveryIds(values) {
3885
+ if (values.length === 0)
3886
+ throw invalid2("at least one delivery id is required");
3887
+ return normalizeDeliveryIds(values);
3888
+ }
3726
3889
  function requireDecision(value) {
3727
3890
  if (!DECISIONS.has(value))
3728
3891
  throw invalid2("decision must be one of immediate, digest, suppress");
@@ -3805,7 +3968,10 @@ var StewardResource = class {
3805
3968
  inboxPath: requireInboxPath(params),
3806
3969
  requestId: requireRequestId(params.requestId),
3807
3970
  body: params.body,
3808
- deliveryIds: requireDeliveryIds(params.deliveryIds)
3971
+ // A For-You-only Brief covers no ledger delivery, so an empty (or
3972
+ // omitted) set is valid here; the backend accepts it. `briefed` still
3973
+ // requires ids.
3974
+ deliveryIds: normalizeDeliveryIds(params.deliveryIds ?? [])
3809
3975
  }
3810
3976
  });
3811
3977
  const message = data.postStewardMessage?.message;
@@ -4079,6 +4245,56 @@ var ThesesResource = class {
4079
4245
  this.client = client;
4080
4246
  }
4081
4247
  client;
4248
+ async assetCandidates(text) {
4249
+ this.client._requireAuth();
4250
+ const source = requireBody(text);
4251
+ const response = await this.client._request("POST", "/query", {
4252
+ body: {
4253
+ query: `query ThesisAssetCandidates($input: ThesisAssetCandidatesInput!) {
4254
+ viewer { thesisAssetCandidates(input: $input) {
4255
+ mentions { quote ticker resolution stance candidates { entityId ticker name kind } }
4256
+ } }
4257
+ }`,
4258
+ variables: { input: { text: source } }
4259
+ }
4260
+ });
4261
+ if (Array.isArray(response?.errors) && response.errors.length > 0) {
4262
+ throw new AlvaError("GRAPHQL_ERROR", "Asset extraction failed", 400, {
4263
+ errors: response.errors
4264
+ });
4265
+ }
4266
+ const data = response?.data;
4267
+ const viewer = isRecord2(data) ? data.viewer : void 0;
4268
+ const result = isRecord2(viewer) ? viewer.thesisAssetCandidates : void 0;
4269
+ if (!isRecord2(result) || !Array.isArray(result.mentions)) {
4270
+ throw invalidResponse2("asset candidates response must contain mentions");
4271
+ }
4272
+ const mentions = result.mentions.map((item, index) => {
4273
+ if (!isRecord2(item) || typeof item.quote !== "string" || typeof item.ticker !== "string" || !["RESOLVED", "AMBIGUOUS", "UNRESOLVED"].includes(
4274
+ item.resolution
4275
+ ) || !["UNKNOWN", "BULLISH", "BEARISH"].includes(item.stance) || !Array.isArray(item.candidates)) {
4276
+ throw invalidResponse2(`asset mention ${index} is invalid`);
4277
+ }
4278
+ const candidates = item.candidates.map((candidate) => {
4279
+ if (!isRecord2(candidate) || typeof candidate.ticker !== "string" || typeof candidate.name !== "string" || !["STOCK", "ETF", "CRYPTO", "INDEX"].includes(
4280
+ candidate.kind
4281
+ )) {
4282
+ throw invalidResponse2(`asset mention ${index} has invalid candidate`);
4283
+ }
4284
+ return {
4285
+ entityId: responseID(
4286
+ candidate.entityId,
4287
+ `asset mention ${index} candidate.entityId`
4288
+ ),
4289
+ ticker: candidate.ticker,
4290
+ name: candidate.name,
4291
+ kind: candidate.kind
4292
+ };
4293
+ });
4294
+ return { ...item, candidates };
4295
+ });
4296
+ return { mentions };
4297
+ }
4082
4298
  async create(params) {
4083
4299
  this.client._requireAuth();
4084
4300
  const body = createBody(params);
@@ -4223,8 +4439,36 @@ function createBody(params) {
4223
4439
  };
4224
4440
  if (params.tickers !== void 0)
4225
4441
  body.tickers = requireTickers(params.tickers);
4442
+ if (params.entity_stances !== void 0) {
4443
+ body.entity_stances = requireEntityStances(
4444
+ params.entity_stances,
4445
+ body.entity_ids
4446
+ );
4447
+ }
4226
4448
  return body;
4227
4449
  }
4450
+ function requireEntityStances(value, entityIDs) {
4451
+ if (!Array.isArray(value) || value.length > MAX_ENTITY_IDS)
4452
+ throw invalidArgument("entity_stances must contain at most 100 values");
4453
+ const allowed = new Set(entityIDs);
4454
+ const seen = /* @__PURE__ */ new Set();
4455
+ return value.map((item, index) => {
4456
+ if (!isRecord2(item))
4457
+ throw invalidArgument(`entity_stances[${index}] must be an object`);
4458
+ const entityID = requireID(
4459
+ item.entity_id,
4460
+ `entity_stances[${index}].entity_id`
4461
+ );
4462
+ if (!allowed.has(entityID) || seen.has(entityID))
4463
+ throw invalidArgument(
4464
+ "entity stance must reference one unique entity_id"
4465
+ );
4466
+ seen.add(entityID);
4467
+ if (!["unknown", "bullish", "bearish"].includes(item.stance))
4468
+ throw invalidArgument(`entity_stances[${index}].stance is invalid`);
4469
+ return { entity_id: entityID, stance: item.stance };
4470
+ });
4471
+ }
4228
4472
  function updateBody(params) {
4229
4473
  return {
4230
4474
  request_id: requireRequestID(params.request_id),
@@ -4263,6 +4507,20 @@ function thesisResponse(response) {
4263
4507
  author_kind: responseText(thesis.author_kind, "thesis.author_kind"),
4264
4508
  author_ref: responseText(thesis.author_ref, "thesis.author_ref")
4265
4509
  };
4510
+ if (thesis.entity_stances !== void 0) {
4511
+ if (!Array.isArray(thesis.entity_stances))
4512
+ throw invalidResponse2("thesis.entity_stances must be an array");
4513
+ value.entity_stances = thesis.entity_stances.map((item) => {
4514
+ if (!isRecord2(item))
4515
+ throw invalidResponse2("thesis.entity_stances contains invalid entry");
4516
+ const entityID = responseID(item.entity_id, "entity_stances.entity_id");
4517
+ if (!value.entity_ids.includes(entityID))
4518
+ throw invalidResponse2("entity stance must reference a thesis entity");
4519
+ if (!["unknown", "bullish", "bearish"].includes(item.stance))
4520
+ throw invalidResponse2("thesis.entity_stances contains invalid stance");
4521
+ return { entity_id: entityID, stance: item.stance };
4522
+ });
4523
+ }
4266
4524
  return { thesis: value };
4267
4525
  }
4268
4526
  function thesisGetResponse(response) {
@@ -4426,10 +4684,13 @@ function requireID(value, field) {
4426
4684
  }
4427
4685
  return value;
4428
4686
  }
4687
+ var MAX_ENTITY_IDS = 100;
4429
4688
  function requireIDs(value, field) {
4430
4689
  if (!Array.isArray(value)) throw invalidArgument(`${field} must be an array`);
4431
- if (value.length > 20) {
4432
- throw invalidArgument(`${field} must contain at most 20 IDs`);
4690
+ if (value.length > MAX_ENTITY_IDS) {
4691
+ throw invalidArgument(
4692
+ `${field} must contain at most ${MAX_ENTITY_IDS} IDs`
4693
+ );
4433
4694
  }
4434
4695
  return value.map((item, index) => requireID(item, `${field}[${index}]`));
4435
4696
  }
@@ -4500,8 +4761,10 @@ function responseID(value, field) {
4500
4761
  }
4501
4762
  function responseIDs(value, field) {
4502
4763
  if (!Array.isArray(value)) throw invalidResponse2(`${field} must be an array`);
4503
- if (value.length > 20) {
4504
- throw invalidResponse2(`${field} must contain at most 20 IDs`);
4764
+ if (value.length > MAX_ENTITY_IDS) {
4765
+ throw invalidResponse2(
4766
+ `${field} must contain at most ${MAX_ENTITY_IDS} IDs`
4767
+ );
4505
4768
  }
4506
4769
  return value.map((item, index) => responseID(item, `${field}[${index}]`));
4507
4770
  }
@@ -5400,7 +5663,7 @@ var installPlaybookRuntime = (targetWindow) => {
5400
5663
  };
5401
5664
 
5402
5665
  // src/index.ts
5403
- var VERSION = true ? "0.29.0" : "dev";
5666
+ var VERSION = true ? "0.31.0" : "dev";
5404
5667
  export {
5405
5668
  AlertsResource,
5406
5669
  AlvaClient,