@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.cjs CHANGED
@@ -819,6 +819,166 @@ function connection(value) {
819
819
  return invalidResponse();
820
820
  return value;
821
821
  }
822
+ var THESIS_RECOMMENDATION_QUERY = `
823
+ query ToolkitForYouTheses($input: ThesisRecommendationInput) {
824
+ viewer {
825
+ thesisRecommendations(input: $input) {
826
+ listId pageCursor nextCursor exhausted scanLimited
827
+ pageInfo { startCursor endCursor hasNextPage hasPreviousPage }
828
+ edges {
829
+ cursor
830
+ node {
831
+ itemKey
832
+ publication {
833
+ thesisId playbookId authorVersionId materialVersionId itemKey
834
+ title body publishedAtMs changeKind visibility
835
+ closed archived note closingNote researchPaused
836
+ entityIds categoryIds
837
+ entityStances { entityId stance }
838
+ entities { id ticker name }
839
+ publisher {
840
+ id displayName avatarUrl bio followersCount
841
+ viewerState { following }
842
+ }
843
+ medias { type coverUrl url }
844
+ signalFeed { id }
845
+ snapshotRelease {
846
+ versionId materialVersionId publishedAtMs changeKind
847
+ sourceRefs {
848
+ title sourceKind sourceContentId publicUrl sourceTimeMs locator
849
+ }
850
+ }
851
+ }
852
+ }
853
+ }
854
+ }
855
+ }
856
+ }
857
+ `.trim();
858
+ function validateForYouThesesParams(params) {
859
+ if (!record(params)) throw new Error("Thesis parameters must be an object");
860
+ const first = params.first === void 0 ? 10 : params.first;
861
+ if (typeof first !== "number" || !Number.isInteger(first) || first < 1 || first > 10) {
862
+ throw new Error("first must be an integer between 1 and 10");
863
+ }
864
+ if (params.after !== void 0 && (typeof params.after !== "string" || !params.after.trim())) {
865
+ throw new Error("after must be a non-empty cursor");
866
+ }
867
+ }
868
+ function graphqlViewerField(response, field) {
869
+ if (!record(response)) {
870
+ throw new AlvaError(
871
+ "GRAPHQL_INVALID_RESPONSE",
872
+ `GraphQL returned an invalid viewer.${field} response`,
873
+ 502
874
+ );
875
+ }
876
+ if (response.errors !== void 0) {
877
+ if (!Array.isArray(response.errors)) {
878
+ throw new AlvaError(
879
+ "GRAPHQL_INVALID_RESPONSE",
880
+ `GraphQL returned an invalid viewer.${field} response`,
881
+ 502
882
+ );
883
+ }
884
+ if (response.errors.length > 0) {
885
+ const messages = response.errors.flatMap(
886
+ (error) => record(error) && typeof error.message === "string" ? [error.message] : []
887
+ );
888
+ throw new AlvaError(
889
+ "GRAPHQL_ERROR",
890
+ messages.join("; ") || "GraphQL request failed",
891
+ 400,
892
+ { errors: response.errors }
893
+ );
894
+ }
895
+ }
896
+ if (!record(response.data) || !record(response.data.viewer) || response.data.viewer[field] == null) {
897
+ throw new AlvaError(
898
+ "GRAPHQL_EMPTY_RESPONSE",
899
+ `GraphQL response did not include viewer.${field}`,
900
+ 502
901
+ );
902
+ }
903
+ return response.data.viewer[field];
904
+ }
905
+ function invalidPage() {
906
+ throw new AlvaError(
907
+ "GRAPHQL_INVALID_RESPONSE",
908
+ "GraphQL returned an invalid Thesis recommendation page",
909
+ 502
910
+ );
911
+ }
912
+ function positiveInt64List(value) {
913
+ return Array.isArray(value) && value.every(isPositiveInt64);
914
+ }
915
+ function stanceList(value) {
916
+ return Array.isArray(value) && value.every(
917
+ (item) => record(item) && isPositiveInt64(item.entityId) && typeof item.stance === "string" && item.stance.trim() !== ""
918
+ );
919
+ }
920
+ function entityList(value) {
921
+ return Array.isArray(value) && value.every(
922
+ (item) => record(item) && typeof item.id === "string" && item.id.trim() !== "" && typeof item.ticker === "string" && typeof item.name === "string"
923
+ );
924
+ }
925
+ function mediaList(value) {
926
+ return Array.isArray(value) && value.every(
927
+ (item) => record(item) && typeof item.type === "string" && item.type.trim() !== "" && typeof item.coverUrl === "string" && (item.url === null || typeof item.url === "string")
928
+ );
929
+ }
930
+ function sourceRefList(value) {
931
+ return Array.isArray(value) && value.every(
932
+ (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"
933
+ );
934
+ }
935
+ function nullableMs(value) {
936
+ return value === null || typeof value === "number" && Number.isFinite(value);
937
+ }
938
+ function snapshot(value) {
939
+ 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);
940
+ }
941
+ function publisher(value) {
942
+ 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");
943
+ }
944
+ function publication(value) {
945
+ if (!record(value)) return false;
946
+ for (const field of [
947
+ "thesisId",
948
+ "playbookId",
949
+ "authorVersionId",
950
+ "materialVersionId"
951
+ ]) {
952
+ if (!isPositiveInt64(value[field])) return false;
953
+ }
954
+ 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") {
955
+ return false;
956
+ }
957
+ for (const field of ["closed", "archived", "researchPaused"]) {
958
+ if (typeof value[field] !== "boolean") return false;
959
+ }
960
+ if (!positiveInt64List(value.entityIds) || !positiveInt64List(value.categoryIds) || !stanceList(value.entityStances) || !entityList(value.entities) || !mediaList(value.medias) || !publisher(value.publisher) || !snapshot(value.snapshotRelease)) {
961
+ return false;
962
+ }
963
+ return value.signalFeed === null || record(value.signalFeed) && isPositiveInt64(value.signalFeed.id);
964
+ }
965
+ function recommendationPage(value) {
966
+ 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") {
967
+ return invalidPage();
968
+ }
969
+ const page = value.pageInfo;
970
+ if (typeof page.startCursor !== "string" || typeof page.endCursor !== "string" || typeof page.hasNextPage !== "boolean" || typeof page.hasPreviousPage !== "boolean" || page.hasNextPage !== (value.nextCursor !== null)) {
971
+ return invalidPage();
972
+ }
973
+ for (const edge of value.edges) {
974
+ 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)) {
975
+ return invalidPage();
976
+ }
977
+ }
978
+ const first = value.edges[0];
979
+ if (page.startCursor !== (first?.cursor ?? "")) return invalidPage();
980
+ return value;
981
+ }
822
982
  var ForYouResource = class {
823
983
  constructor(client) {
824
984
  this.client = client;
@@ -841,29 +1001,29 @@ var ForYouResource = class {
841
1001
  }
842
1002
  }
843
1003
  });
844
- if (!record(response)) return invalidResponse();
845
- if (response.errors !== void 0) {
846
- if (!Array.isArray(response.errors)) return invalidResponse();
847
- if (response.errors.length > 0) {
848
- const messages = response.errors.flatMap(
849
- (error) => record(error) && typeof error.message === "string" ? [error.message] : []
850
- );
851
- throw new AlvaError(
852
- "GRAPHQL_ERROR",
853
- messages.join("; ") || "GraphQL request failed",
854
- 400,
855
- { errors: response.errors }
856
- );
1004
+ return connection(graphqlViewerField(response, "forYou"));
1005
+ }
1006
+ /**
1007
+ * One ranked page of Thesis recommendations -- the stream the Feed App reads,
1008
+ * which is not the chronological `list` stream. Page to `exhausted` and filter
1009
+ * on `publication.publishedAtMs` yourself; the order is slot-mixed, so a time
1010
+ * bound is never a reason to stop paging. Publications the viewer already saw
1011
+ * are withheld by an upstream cooldown, so a window read is "recommended and
1012
+ * recent", not every publication in the window.
1013
+ */
1014
+ async theses(params = {}) {
1015
+ validateForYouThesesParams(params);
1016
+ this.client._requireAuth();
1017
+ const response = await this.client._request("POST", "/query", {
1018
+ body: {
1019
+ query: THESIS_RECOMMENDATION_QUERY,
1020
+ variables: {
1021
+ input: { first: params.first ?? 10, after: params.after }
1022
+ }
857
1023
  }
858
- }
859
- if (!record(response.data) || !record(response.data.viewer) || response.data.viewer.forYou == null) {
860
- throw new AlvaError(
861
- "GRAPHQL_EMPTY_RESPONSE",
862
- "GraphQL response did not include viewer.forYou",
863
- 502
864
- );
865
- }
866
- return connection(response.data.viewer.forYou);
1024
+ });
1025
+ const field = graphqlViewerField(response, "thesisRecommendations");
1026
+ return recommendationPage(field);
867
1027
  }
868
1028
  };
869
1029
 
@@ -3777,9 +3937,7 @@ function requireDeliveryId(value, label = "delivery id") {
3777
3937
  throw invalid2(`${label} must be a positive integer`);
3778
3938
  return value;
3779
3939
  }
3780
- function requireDeliveryIds(values) {
3781
- if (values.length === 0)
3782
- throw invalid2("at least one delivery id is required");
3940
+ function normalizeDeliveryIds(values) {
3783
3941
  const unique = /* @__PURE__ */ new Set();
3784
3942
  for (const value of values) {
3785
3943
  requireDeliveryId(value);
@@ -3788,6 +3946,11 @@ function requireDeliveryIds(values) {
3788
3946
  }
3789
3947
  return [...unique];
3790
3948
  }
3949
+ function requireDeliveryIds(values) {
3950
+ if (values.length === 0)
3951
+ throw invalid2("at least one delivery id is required");
3952
+ return normalizeDeliveryIds(values);
3953
+ }
3791
3954
  function requireDecision(value) {
3792
3955
  if (!DECISIONS.has(value))
3793
3956
  throw invalid2("decision must be one of immediate, digest, suppress");
@@ -3870,7 +4033,10 @@ var StewardResource = class {
3870
4033
  inboxPath: requireInboxPath(params),
3871
4034
  requestId: requireRequestId(params.requestId),
3872
4035
  body: params.body,
3873
- deliveryIds: requireDeliveryIds(params.deliveryIds)
4036
+ // A For-You-only Brief covers no ledger delivery, so an empty (or
4037
+ // omitted) set is valid here; the backend accepts it. `briefed` still
4038
+ // requires ids.
4039
+ deliveryIds: normalizeDeliveryIds(params.deliveryIds ?? [])
3874
4040
  }
3875
4041
  });
3876
4042
  const message = data.postStewardMessage?.message;
@@ -4144,6 +4310,56 @@ var ThesesResource = class {
4144
4310
  this.client = client;
4145
4311
  }
4146
4312
  client;
4313
+ async assetCandidates(text) {
4314
+ this.client._requireAuth();
4315
+ const source = requireBody(text);
4316
+ const response = await this.client._request("POST", "/query", {
4317
+ body: {
4318
+ query: `query ThesisAssetCandidates($input: ThesisAssetCandidatesInput!) {
4319
+ viewer { thesisAssetCandidates(input: $input) {
4320
+ mentions { quote ticker resolution stance candidates { entityId ticker name kind } }
4321
+ } }
4322
+ }`,
4323
+ variables: { input: { text: source } }
4324
+ }
4325
+ });
4326
+ if (Array.isArray(response?.errors) && response.errors.length > 0) {
4327
+ throw new AlvaError("GRAPHQL_ERROR", "Asset extraction failed", 400, {
4328
+ errors: response.errors
4329
+ });
4330
+ }
4331
+ const data = response?.data;
4332
+ const viewer = isRecord2(data) ? data.viewer : void 0;
4333
+ const result = isRecord2(viewer) ? viewer.thesisAssetCandidates : void 0;
4334
+ if (!isRecord2(result) || !Array.isArray(result.mentions)) {
4335
+ throw invalidResponse2("asset candidates response must contain mentions");
4336
+ }
4337
+ const mentions = result.mentions.map((item, index) => {
4338
+ if (!isRecord2(item) || typeof item.quote !== "string" || typeof item.ticker !== "string" || !["RESOLVED", "AMBIGUOUS", "UNRESOLVED"].includes(
4339
+ item.resolution
4340
+ ) || !["UNKNOWN", "BULLISH", "BEARISH"].includes(item.stance) || !Array.isArray(item.candidates)) {
4341
+ throw invalidResponse2(`asset mention ${index} is invalid`);
4342
+ }
4343
+ const candidates = item.candidates.map((candidate) => {
4344
+ if (!isRecord2(candidate) || typeof candidate.ticker !== "string" || typeof candidate.name !== "string" || !["STOCK", "ETF", "CRYPTO", "INDEX"].includes(
4345
+ candidate.kind
4346
+ )) {
4347
+ throw invalidResponse2(`asset mention ${index} has invalid candidate`);
4348
+ }
4349
+ return {
4350
+ entityId: responseID(
4351
+ candidate.entityId,
4352
+ `asset mention ${index} candidate.entityId`
4353
+ ),
4354
+ ticker: candidate.ticker,
4355
+ name: candidate.name,
4356
+ kind: candidate.kind
4357
+ };
4358
+ });
4359
+ return { ...item, candidates };
4360
+ });
4361
+ return { mentions };
4362
+ }
4147
4363
  async create(params) {
4148
4364
  this.client._requireAuth();
4149
4365
  const body = createBody(params);
@@ -4288,8 +4504,36 @@ function createBody(params) {
4288
4504
  };
4289
4505
  if (params.tickers !== void 0)
4290
4506
  body.tickers = requireTickers(params.tickers);
4507
+ if (params.entity_stances !== void 0) {
4508
+ body.entity_stances = requireEntityStances(
4509
+ params.entity_stances,
4510
+ body.entity_ids
4511
+ );
4512
+ }
4291
4513
  return body;
4292
4514
  }
4515
+ function requireEntityStances(value, entityIDs) {
4516
+ if (!Array.isArray(value) || value.length > MAX_ENTITY_IDS)
4517
+ throw invalidArgument("entity_stances must contain at most 100 values");
4518
+ const allowed = new Set(entityIDs);
4519
+ const seen = /* @__PURE__ */ new Set();
4520
+ return value.map((item, index) => {
4521
+ if (!isRecord2(item))
4522
+ throw invalidArgument(`entity_stances[${index}] must be an object`);
4523
+ const entityID = requireID(
4524
+ item.entity_id,
4525
+ `entity_stances[${index}].entity_id`
4526
+ );
4527
+ if (!allowed.has(entityID) || seen.has(entityID))
4528
+ throw invalidArgument(
4529
+ "entity stance must reference one unique entity_id"
4530
+ );
4531
+ seen.add(entityID);
4532
+ if (!["unknown", "bullish", "bearish"].includes(item.stance))
4533
+ throw invalidArgument(`entity_stances[${index}].stance is invalid`);
4534
+ return { entity_id: entityID, stance: item.stance };
4535
+ });
4536
+ }
4293
4537
  function updateBody(params) {
4294
4538
  return {
4295
4539
  request_id: requireRequestID(params.request_id),
@@ -4328,6 +4572,20 @@ function thesisResponse(response) {
4328
4572
  author_kind: responseText(thesis.author_kind, "thesis.author_kind"),
4329
4573
  author_ref: responseText(thesis.author_ref, "thesis.author_ref")
4330
4574
  };
4575
+ if (thesis.entity_stances !== void 0) {
4576
+ if (!Array.isArray(thesis.entity_stances))
4577
+ throw invalidResponse2("thesis.entity_stances must be an array");
4578
+ value.entity_stances = thesis.entity_stances.map((item) => {
4579
+ if (!isRecord2(item))
4580
+ throw invalidResponse2("thesis.entity_stances contains invalid entry");
4581
+ const entityID = responseID(item.entity_id, "entity_stances.entity_id");
4582
+ if (!value.entity_ids.includes(entityID))
4583
+ throw invalidResponse2("entity stance must reference a thesis entity");
4584
+ if (!["unknown", "bullish", "bearish"].includes(item.stance))
4585
+ throw invalidResponse2("thesis.entity_stances contains invalid stance");
4586
+ return { entity_id: entityID, stance: item.stance };
4587
+ });
4588
+ }
4331
4589
  return { thesis: value };
4332
4590
  }
4333
4591
  function thesisGetResponse(response) {
@@ -4491,10 +4749,13 @@ function requireID(value, field) {
4491
4749
  }
4492
4750
  return value;
4493
4751
  }
4752
+ var MAX_ENTITY_IDS = 100;
4494
4753
  function requireIDs(value, field) {
4495
4754
  if (!Array.isArray(value)) throw invalidArgument(`${field} must be an array`);
4496
- if (value.length > 20) {
4497
- throw invalidArgument(`${field} must contain at most 20 IDs`);
4755
+ if (value.length > MAX_ENTITY_IDS) {
4756
+ throw invalidArgument(
4757
+ `${field} must contain at most ${MAX_ENTITY_IDS} IDs`
4758
+ );
4498
4759
  }
4499
4760
  return value.map((item, index) => requireID(item, `${field}[${index}]`));
4500
4761
  }
@@ -4565,8 +4826,10 @@ function responseID(value, field) {
4565
4826
  }
4566
4827
  function responseIDs(value, field) {
4567
4828
  if (!Array.isArray(value)) throw invalidResponse2(`${field} must be an array`);
4568
- if (value.length > 20) {
4569
- throw invalidResponse2(`${field} must contain at most 20 IDs`);
4829
+ if (value.length > MAX_ENTITY_IDS) {
4830
+ throw invalidResponse2(
4831
+ `${field} must contain at most ${MAX_ENTITY_IDS} IDs`
4832
+ );
4570
4833
  }
4571
4834
  return value.map((item, index) => responseID(item, `${field}[${index}]`));
4572
4835
  }
@@ -5465,7 +5728,7 @@ var installPlaybookRuntime = (targetWindow) => {
5465
5728
  };
5466
5729
 
5467
5730
  // src/index.ts
5468
- var VERSION = true ? "0.29.0" : "dev";
5731
+ var VERSION = true ? "0.31.0" : "dev";
5469
5732
  // Annotate the CommonJS export names for ESM import in node:
5470
5733
  0 && (module.exports = {
5471
5734
  AlertsResource,