gtmmaxing 0.1.5 → 0.1.7

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.
Files changed (2) hide show
  1. package/dist/gtm.js +2833 -677
  2. package/package.json +1 -1
package/dist/gtm.js CHANGED
@@ -2919,8 +2919,8 @@ var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def
2919
2919
  $ZodStringFormat.init(inst, def);
2920
2920
  if (def.local || def.precision === -1) {
2921
2921
  inst._zod.bag.laxFormat = true;
2922
- inst._zod.onattach.push((s2) => {
2923
- s2._zod.bag.laxFormat = true;
2922
+ inst._zod.onattach.push((s3) => {
2923
+ s3._zod.bag.laxFormat = true;
2924
2924
  });
2925
2925
  }
2926
2926
  });
@@ -9087,8 +9087,8 @@ function ko_default() {
9087
9087
  }
9088
9088
 
9089
9089
  // ../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/lt.js
9090
- var capitalizeFirstCharacter = (text2) => {
9091
- return text2.charAt(0).toUpperCase() + text2.slice(1);
9090
+ var capitalizeFirstCharacter = (text4) => {
9091
+ return text4.charAt(0).toUpperCase() + text4.slice(1);
9092
9092
  };
9093
9093
  function getUnitTypeFromNumber(number4) {
9094
9094
  const abs = Math.abs(number4);
@@ -18567,12 +18567,12 @@ function convertSchema(schema, ctx) {
18567
18567
  let baseSchema = convertBaseSchema(schema, ctx);
18568
18568
  const hasExplicitType = schema.type || schema.enum !== void 0 || schema.const !== void 0;
18569
18569
  if (schema.anyOf && Array.isArray(schema.anyOf)) {
18570
- const options = schema.anyOf.map((s2) => convertSchema(s2, ctx));
18570
+ const options = schema.anyOf.map((s3) => convertSchema(s3, ctx));
18571
18571
  const anyOfUnion = z.union(options);
18572
18572
  baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion;
18573
18573
  }
18574
18574
  if (schema.oneOf && Array.isArray(schema.oneOf)) {
18575
- const options = schema.oneOf.map((s2) => convertSchema(s2, ctx));
18575
+ const options = schema.oneOf.map((s3) => convertSchema(s3, ctx));
18576
18576
  const oneOfUnion = z.xor(options);
18577
18577
  baseSchema = hasExplicitType ? z.intersection(baseSchema, oneOfUnion) : oneOfUnion;
18578
18578
  }
@@ -18657,24 +18657,24 @@ function visit(schema, fnOrHandlers) {
18657
18657
  return h ? h(node2, rewritten) : node2;
18658
18658
  };
18659
18659
  const cache = /* @__PURE__ */ new Map();
18660
- function run(s2) {
18661
- const cached2 = cache.get(s2);
18660
+ function run(s3) {
18661
+ const cached2 = cache.get(s3);
18662
18662
  if (cached2 === RESOLVING) {
18663
18663
  return new $ZodLazy({
18664
18664
  type: "lazy",
18665
- getter: () => cache.get(s2)
18665
+ getter: () => cache.get(s3)
18666
18666
  });
18667
18667
  }
18668
18668
  if (cached2 !== void 0)
18669
18669
  return cached2;
18670
- cache.set(s2, RESOLVING);
18671
- const inner = mapInner(s2);
18672
- const mapped = fn(inner, inner !== s2);
18673
- cache.set(s2, mapped);
18670
+ cache.set(s3, RESOLVING);
18671
+ const inner = mapInner(s3);
18672
+ const mapped = fn(inner, inner !== s3);
18673
+ cache.set(s3, mapped);
18674
18674
  return mapped;
18675
18675
  }
18676
- function mapInner(s2) {
18677
- const def = s2._zod.def;
18676
+ function mapInner(s3) {
18677
+ const def = s3._zod.def;
18678
18678
  const kind = def.type;
18679
18679
  switch (kind) {
18680
18680
  case "object": {
@@ -18694,11 +18694,11 @@ function visit(schema, fnOrHandlers) {
18694
18694
  if (newCatchall !== def.catchall)
18695
18695
  changed = true;
18696
18696
  }
18697
- return changed ? clone(s2, { ...def, shape: newShape, catchall: newCatchall }) : s2;
18697
+ return changed ? clone(s3, { ...def, shape: newShape, catchall: newCatchall }) : s3;
18698
18698
  }
18699
18699
  case "array": {
18700
18700
  const mapped = run(def.element);
18701
- return mapped === def.element ? s2 : clone(s2, { ...def, element: mapped });
18701
+ return mapped === def.element ? s3 : clone(s3, { ...def, element: mapped });
18702
18702
  }
18703
18703
  case "tuple": {
18704
18704
  const oldItems = def.items;
@@ -18716,17 +18716,17 @@ function visit(schema, fnOrHandlers) {
18716
18716
  if (newRest !== def.rest)
18717
18717
  changed = true;
18718
18718
  }
18719
- return changed ? clone(s2, { ...def, items: newItems, rest: newRest }) : s2;
18719
+ return changed ? clone(s3, { ...def, items: newItems, rest: newRest }) : s3;
18720
18720
  }
18721
18721
  case "record":
18722
18722
  case "map": {
18723
18723
  const newKey = run(def.keyType);
18724
18724
  const newVal = run(def.valueType);
18725
- return newKey === def.keyType && newVal === def.valueType ? s2 : clone(s2, { ...def, keyType: newKey, valueType: newVal });
18725
+ return newKey === def.keyType && newVal === def.valueType ? s3 : clone(s3, { ...def, keyType: newKey, valueType: newVal });
18726
18726
  }
18727
18727
  case "set": {
18728
18728
  const newVal = run(def.valueType);
18729
- return newVal === def.valueType ? s2 : clone(s2, { ...def, valueType: newVal });
18729
+ return newVal === def.valueType ? s3 : clone(s3, { ...def, valueType: newVal });
18730
18730
  }
18731
18731
  case "union": {
18732
18732
  const oldOptions = def.options;
@@ -18738,12 +18738,12 @@ function visit(schema, fnOrHandlers) {
18738
18738
  changed = true;
18739
18739
  newOptions.push(mapped);
18740
18740
  }
18741
- return changed ? clone(s2, { ...def, options: newOptions }) : s2;
18741
+ return changed ? clone(s3, { ...def, options: newOptions }) : s3;
18742
18742
  }
18743
18743
  case "intersection": {
18744
18744
  const newLeft = run(def.left);
18745
18745
  const newRight = run(def.right);
18746
- return newLeft === def.left && newRight === def.right ? s2 : clone(s2, { ...def, left: newLeft, right: newRight });
18746
+ return newLeft === def.left && newRight === def.right ? s3 : clone(s3, { ...def, left: newLeft, right: newRight });
18747
18747
  }
18748
18748
  case "optional":
18749
18749
  case "nullable":
@@ -18755,22 +18755,22 @@ function visit(schema, fnOrHandlers) {
18755
18755
  case "promise":
18756
18756
  case "success": {
18757
18757
  const newInner = run(def.innerType);
18758
- return newInner === def.innerType ? s2 : clone(s2, { ...def, innerType: newInner });
18758
+ return newInner === def.innerType ? s3 : clone(s3, { ...def, innerType: newInner });
18759
18759
  }
18760
18760
  case "pipe": {
18761
18761
  const newIn = run(def.in);
18762
18762
  const newOut = run(def.out);
18763
- return newIn === def.in && newOut === def.out ? s2 : clone(s2, { ...def, in: newIn, out: newOut });
18763
+ return newIn === def.in && newOut === def.out ? s3 : clone(s3, { ...def, in: newIn, out: newOut });
18764
18764
  }
18765
18765
  case "function": {
18766
18766
  const newInput = run(def.input);
18767
18767
  const newOutput = run(def.output);
18768
- return newInput === def.input && newOutput === def.output ? s2 : clone(s2, { ...def, input: newInput, output: newOutput });
18768
+ return newInput === def.input && newOutput === def.output ? s3 : clone(s3, { ...def, input: newInput, output: newOutput });
18769
18769
  }
18770
18770
  case "lazy": {
18771
18771
  const original = def.getter;
18772
18772
  const { _cachedInner, ...rest } = def;
18773
- return clone(s2, { ...rest, getter: () => run(original()) });
18773
+ return clone(s3, { ...rest, getter: () => run(original()) });
18774
18774
  }
18775
18775
  // A leaf by choice: `parts` are regex fragments, not data positions.
18776
18776
  case "template_literal":
@@ -18794,10 +18794,10 @@ function visit(schema, fnOrHandlers) {
18794
18794
  case "file":
18795
18795
  case "transform":
18796
18796
  case "custom":
18797
- return s2;
18797
+ return s3;
18798
18798
  default: {
18799
18799
  kind;
18800
- return s2;
18800
+ return s3;
18801
18801
  }
18802
18802
  }
18803
18803
  }
@@ -18807,11 +18807,11 @@ function visit(schema, fnOrHandlers) {
18807
18807
  // ../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/deep-partial.js
18808
18808
  function deepPartial(schema) {
18809
18809
  return visit(schema, {
18810
- object: (s2) => s2.partial(),
18810
+ object: (s3) => s3.partial(),
18811
18811
  // Every partialed option now admits `undefined`, which the constructor rejects as a duplicate.
18812
- union: (s2) => {
18813
- const def = s2._zod.def;
18814
- return def.discriminator === void 0 ? s2 : union(def.options);
18812
+ union: (s3) => {
18813
+ const def = s3._zod.def;
18814
+ return def.discriminator === void 0 ? s3 : union(def.options);
18815
18815
  }
18816
18816
  });
18817
18817
  }
@@ -18831,18 +18831,18 @@ function inSide(def) {
18831
18831
  }
18832
18832
  function input(schema) {
18833
18833
  return visit(schema, {
18834
- pipe: (s2) => inSide(s2._zod.def),
18834
+ pipe: (s3) => inSide(s3._zod.def),
18835
18835
  // A default value belongs to the output side, so a rewritten inner type leaves it stranded. `.default()` widens the declared input type with `undefined`, and `optional` is what carries that across.
18836
- default: (s2, rewritten) => rewritten ? optional(s2._zod.def.innerType) : s2,
18836
+ default: (s3, rewritten) => rewritten ? optional(s3._zod.def.innerType) : s3,
18837
18837
  // A catch value is output-side too, but `.catch()` leaves the declared input type alone, so the inner schema stands on its own.
18838
- catch: (s2, rewritten) => rewritten ? s2._zod.def.innerType : s2
18838
+ catch: (s3, rewritten) => rewritten ? s3._zod.def.innerType : s3
18839
18839
  });
18840
18840
  }
18841
18841
  function output(schema) {
18842
18842
  return visit(schema, {
18843
- pipe: (s2) => outSide(s2._zod.def),
18843
+ pipe: (s3) => outSide(s3._zod.def),
18844
18844
  // A prefault value is fed through the schema, which makes it input-side, so a rewritten inner type leaves it stranded.
18845
- prefault: (s2, rewritten) => rewritten ? s2._zod.def.innerType : s2
18845
+ prefault: (s3, rewritten) => rewritten ? s3._zod.def.innerType : s3
18846
18846
  });
18847
18847
  }
18848
18848
 
@@ -18871,30 +18871,46 @@ function date4(params) {
18871
18871
  return _coercedDate(ZodDate, params);
18872
18872
  }
18873
18873
 
18874
- // ../contracts/src/tools.ts
18875
- var TOOL_CATALOG = {
18876
- "seo-aeo-audit": { name: "SEO/AEO audit", credits: 35, unit: "completed audit", limit: 1 },
18877
- company: { name: "Company enrichment", credits: 1, unit: "company", limit: 1 },
18878
- "local-leads": { name: "Local business leads", credits: 1, unit: "search (up to 20 businesses)", limit: 20 },
18879
- website: { name: "Website brief", credits: 1, unit: "brief", limit: 1 },
18880
- icp: { name: "Decision-maker finder", credits: 2, unit: "search (up to 10 profiles)", limit: 10 },
18881
- signals: { name: "Hiring signals", credits: 1, unit: "search (up to 50 companies)", limit: 50 },
18882
- "verify-email": { name: "Email verification", credits: 2, unit: "definitive verification", limit: 1 },
18883
- "phone-pilot": { name: "Mobile enrichment", credits: 5, unit: "returned number", limit: 1 },
18884
- "people-search": { name: "People search", credits: 2, unit: "search (up to 100 people)", limit: 100 },
18885
- "google-search": { name: "Google search", credits: 1, unit: "search (up to 20 results)", limit: 20 },
18886
- "linkedin-profile": { name: "LinkedIn profile", credits: 1, unit: "profile", limit: 1 },
18887
- "linkedin-activity": { name: "LinkedIn activity", credits: 1, unit: "profile with posts", limit: 1 },
18888
- "profile-finder": { name: "Find LinkedIn profile", credits: 1, unit: "profile found", limit: 1 },
18889
- "page-content": { name: "Web page content", credits: 1, unit: "page", limit: 1 },
18890
- "instagram-profile": { name: "Instagram profile", credits: 1, unit: "profile", limit: 1 },
18891
- "x-search": { name: "X post search", credits: 1, unit: "search (up to 20 posts)", limit: 20 },
18892
- "reddit-search": { name: "Reddit post search", credits: 1, unit: "search (up to 20 posts)", limit: 20 },
18893
- "funding-signals": { name: "Funding signals", credits: 1, unit: "search (up to 50 companies)", limit: 50 },
18894
- "lookalike-companies": { name: "Lookalike companies", credits: 2, unit: "search", limit: 50 },
18895
- "post-engagers": { name: "LinkedIn post engagers", credits: 1, unit: "post (up to 100 people)", limit: 100 }
18896
- };
18897
- var toolIdSchema = external_exports.enum(Object.keys(TOOL_CATALOG));
18874
+ // ../contracts/src/lookup.ts
18875
+ var lookupStatusSchema = external_exports.enum(["found", "not_found", "error"]);
18876
+ var foundDeliverabilitySchema = external_exports.enum(["verified"]);
18877
+ var returnedDeliverabilitySchema = foundDeliverabilitySchema.nullable();
18878
+ var deliverabilitySchema = external_exports.union([foundDeliverabilitySchema, external_exports.literal("unverified")]).nullable().transform((value) => value === "unverified" ? null : value);
18879
+ var lookupRequestSchema = external_exports.object({
18880
+ // Individual entries remain unknown here because the API's forgiving
18881
+ // normalizer drops invalid entries while preserving valid ones in a mixed
18882
+ // paste. The max length is configuration-owned by the API route.
18883
+ urls: external_exports.array(external_exports.unknown()).min(1)
18884
+ });
18885
+ var lookupResultSchema = external_exports.object({
18886
+ /** Canonical request identity echoed for exact client-side row matching. */
18887
+ key: external_exports.string(),
18888
+ url: external_exports.string(),
18889
+ status: lookupStatusSchema,
18890
+ name: external_exports.string().nullable(),
18891
+ title: external_exports.string().nullable(),
18892
+ email: external_exports.string().nullable(),
18893
+ deliverability: deliverabilitySchema
18894
+ });
18895
+ var lookupSummarySchema = external_exports.object({
18896
+ type: external_exports.literal("summary"),
18897
+ total: external_exports.number().int().nonnegative(),
18898
+ found: external_exports.number().int().nonnegative(),
18899
+ credits: external_exports.number().int().nonnegative().optional()
18900
+ });
18901
+ var lookupErrorSchema = external_exports.object({
18902
+ error: external_exports.string(),
18903
+ detail: external_exports.string().optional(),
18904
+ credits: external_exports.object({ remaining: external_exports.number().int().nonnegative() }).optional()
18905
+ });
18906
+ var lookupEventSchema = external_exports.union([lookupResultSchema, lookupSummarySchema]);
18907
+ var externalErrorSchema = external_exports.object({
18908
+ error: external_exports.string(),
18909
+ request_id: external_exports.string(),
18910
+ detail: external_exports.string().optional()
18911
+ });
18912
+
18913
+ // ../contracts/src/tool-input.ts
18898
18914
  function publicWebsite(value) {
18899
18915
  try {
18900
18916
  const u = new URL(value);
@@ -18912,8 +18928,9 @@ function instagramHandle(value) {
18912
18928
  }
18913
18929
  var SEARCH_WINDOWS = ["day", "week", "month", "year"];
18914
18930
  var websiteUrl = (value) => /^https:\/\//i.test(value.trim()) ? value.trim() : `https://${value.trim().replace(/^http:\/\//i, "")}`;
18915
- var toolRequestSchema = external_exports.object({
18916
- tool: toolIdSchema,
18931
+
18932
+ // ../contracts/src/tool-request-fields.ts
18933
+ var toolRequestFields = external_exports.object({
18917
18934
  query: external_exports.string().trim().min(2).max(500),
18918
18935
  /** Legacy hiring-signals input, kept so saved runs still parse; no longer used. */
18919
18936
  careerBoard: external_exports.string().trim().max(500).optional(),
@@ -18935,45 +18952,71 @@ var toolRequestSchema = external_exports.object({
18935
18952
  /** Results page, from 1. */
18936
18953
  page: external_exports.number().int().min(1).max(100).optional(),
18937
18954
  limit: external_exports.number().int().min(1).max(100).default(10)
18938
- }).strict().superRefine((v, c) => {
18939
- const reject = (message) => c.addIssue({ code: "custom", path: ["query"], message });
18940
- if (v.careerBoard && !/^https:\/\/(boards\.greenhouse\.io|jobs\.lever\.co)\/[a-zA-Z0-9_-]+\/?$/.test(v.careerBoard)) reject("Use a public Greenhouse or Lever company board URL.");
18941
- if (["website", "page-content", "seo-aeo-audit"].includes(v.tool) && !publicWebsite(websiteUrl(v.query))) reject("Enter a company website, like vercel.com.");
18942
- if (["company", "icp", "lookalike-companies"].includes(v.tool) && !publicWebsite(`https://${v.query.replace(/^https?:\/\//, "").replace(/\/$/, "")}`)) reject("Enter a public company domain.");
18943
- if (v.tool === "local-leads" && !v.location) reject("Add a city or region.");
18944
- if (v.tool === "profile-finder" && !v.company) c.addIssue({ code: "custom", path: ["company"], message: "Add the person's company." });
18945
- if (v.tool === "verify-email" && !external_exports.string().email().safeParse(v.query).success) reject("Enter an email address.");
18946
- if (v.tool === "instagram-profile" && !INSTAGRAM_HANDLE.test(v.query)) reject("Enter an Instagram username, like gymshark.");
18947
- const badFilter = v.industries?.find((industry) => industry.startsWith("invalid:"));
18948
- if (badFilter) c.addIssue({ code: "custom", path: ["industries"], message: badFilter.slice(8) });
18949
- if (v.within && !["x-search", "reddit-search"].includes(v.tool)) c.addIssue({ code: "custom", path: ["within"], message: "Only post searches take a time window." });
18950
- if (v.tool === "post-engagers" && !/^https:\/\/([a-z]{2,3}\.)?linkedin\.com\/(posts|feed\/update)\//.test(v.query)) reject("Enter a LinkedIn post URL.");
18951
- if (["phone-pilot", "linkedin-profile", "linkedin-activity"].includes(v.tool) && !/^https:\/\/(www\.)?linkedin\.com\/in\/[a-zA-Z0-9%_-]+\/?$/.test(v.query)) reject("Enter a LinkedIn profile URL.");
18952
- });
18953
- var toolResultSchema = external_exports.object({
18954
- rows: external_exports.array(external_exports.record(external_exports.string(), external_exports.union([external_exports.string().max(1e5), external_exports.number(), external_exports.boolean(), external_exports.null()]))).max(100),
18955
- notes: external_exports.array(external_exports.string().max(500)).max(10),
18956
- /** There are more results: the next page and, when the source says, how many match in all. */
18957
- more: external_exports.object({ page: external_exports.number().int().positive(), total: external_exports.number().int().nonnegative().optional() }).optional(),
18958
- /** Companies dropped before the rows, by why. */
18959
- left: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).optional()
18960
18955
  });
18961
- var toolRunSchema = external_exports.object({
18962
- id: external_exports.string(),
18963
- tool: toolIdSchema,
18964
- status: external_exports.enum(["queued", "running", "completed", "not_found", "error", "reconciliation_needed"]),
18965
- input: toolRequestSchema,
18966
- result: toolResultSchema.nullable(),
18967
- creditsCharged: external_exports.number().int().nonnegative(),
18968
- creditsReserved: external_exports.number().int().nonnegative(),
18969
- createdAt: external_exports.number(),
18970
- updatedAt: external_exports.number()
18956
+
18957
+ // ../contracts/src/profiles.ts
18958
+ function canonicalProfileSlug(slug) {
18959
+ return /^AC[ow]AA/.test(slug) ? slug : slug.toLowerCase();
18960
+ }
18961
+ function linkedinProfileUrl(value) {
18962
+ const trimmed = value.trim();
18963
+ if (/^[A-Za-z0-9][A-Za-z0-9_%-]{0,99}$/.test(trimmed)) return `https://www.linkedin.com/in/${canonicalProfileSlug(trimmed)}`;
18964
+ const match = /^(?:https?:\/\/)?(?:www\.)?linkedin\.com\/in\/([A-Za-z0-9_%-]{1,100})\/?(?:[?#].*)?$/i.exec(trimmed);
18965
+ return match ? `https://www.linkedin.com/in/${canonicalProfileSlug(match[1])}` : trimmed;
18966
+ }
18967
+ function cliProfileUrl(value) {
18968
+ const url2 = linkedinProfileUrl(value);
18969
+ return /^https:\/\/www\.linkedin\.com\/in\/[A-Za-z0-9_%-]{1,100}$/.test(url2) ? url2 : null;
18970
+ }
18971
+ var isToolProfileUrl = (value) => /^https:\/\/(www\.)?linkedin\.com\/in\/[a-zA-Z0-9%_-]+\/?$/.test(value);
18972
+
18973
+ // ../contracts/src/lifecycle.ts
18974
+ function defineLifecycle({ states, transitions }) {
18975
+ const can = (from, to) => transitions[from].includes(to);
18976
+ return {
18977
+ states,
18978
+ transitions,
18979
+ can,
18980
+ before: (to) => states.filter((from) => can(from, to)),
18981
+ isTerminal: (state) => transitions[state].length === 0
18982
+ };
18983
+ }
18984
+ var MACHINE_JOB_STATUSES = ["in_progress", "failed", "completed"];
18985
+ var machineJobLifecycle = defineLifecycle({
18986
+ states: MACHINE_JOB_STATUSES,
18987
+ transitions: {
18988
+ in_progress: ["in_progress", "failed", "completed"],
18989
+ failed: ["in_progress"],
18990
+ completed: ["in_progress"]
18991
+ }
18971
18992
  });
18972
- var toolRunResponseSchema = external_exports.object({ run: toolRunSchema, credits: external_exports.number().int().nonnegative() });
18973
- var toolRunsResponseSchema = external_exports.object({ runs: external_exports.array(toolRunSchema), credits: external_exports.number().int().nonnegative() });
18993
+ var AGENT_RUN_STATUSES = ["running", "completed", "not_found", "error"];
18994
+
18995
+ // ../contracts/src/result-presentation.ts
18996
+ var RESULT_FIELD_LABELS = {
18997
+ url: "URL",
18998
+ linkedin: "LinkedIn",
18999
+ companyPage: "Company page",
19000
+ lastPostAt: "Last post",
19001
+ posts90d: "Posts in 90 days",
19002
+ posts365d: "Posts in 365 days",
19003
+ postAt: "Posted",
19004
+ mainCta: "Main call to action"
19005
+ };
18974
19006
 
18975
19007
  // ../contracts/src/filters.ts
18976
- var COMPANY_SIZES = ["< 5", "5 - 19", "20 - 99", "100 - 249", "250 - 499", "500 - 999", "1000 - 4999", "5000 - 9999", ">10000"];
19008
+ var COMPANY_SIZE_BANDS = [
19009
+ { label: "< 5", from: 1, to: 4 },
19010
+ { label: "5 - 19", from: 5, to: 19 },
19011
+ { label: "20 - 99", from: 20, to: 99 },
19012
+ { label: "100 - 249", from: 100, to: 249 },
19013
+ { label: "250 - 499", from: 250, to: 499 },
19014
+ { label: "500 - 999", from: 500, to: 999 },
19015
+ { label: "1000 - 4999", from: 1e3, to: 4999 },
19016
+ { label: "5000 - 9999", from: 5e3, to: 9999 },
19017
+ { label: ">10000", from: 1e4, to: Number.MAX_SAFE_INTEGER }
19018
+ ];
19019
+ var COMPANY_SIZES = COMPANY_SIZE_BANDS.map((band) => band.label);
18977
19020
  var INDUSTRIES = [
18978
19021
  "Abrasives and Nonmetallic Minerals Manufacturing",
18979
19022
  "Accessible Architecture and Design",
@@ -19467,12 +19510,8 @@ function companySizeLabels(value) {
19467
19510
  const high = Number(range[2]);
19468
19511
  return low <= high ? bands(low, high) : null;
19469
19512
  }
19470
- var BAND_EDGES = [[1, 4], [5, 19], [20, 99], [100, 249], [250, 499], [500, 999], [1e3, 4999], [5e3, 9999], [1e4, Number.MAX_SAFE_INTEGER]];
19471
19513
  function bands(low, high) {
19472
- const hits = COMPANY_SIZES.filter((_, index) => {
19473
- const [from, to] = BAND_EDGES[index];
19474
- return from <= high && to >= low;
19475
- });
19514
+ const hits = COMPANY_SIZE_BANDS.filter(({ from, to }) => from <= high && to >= low).map(({ label }) => label);
19476
19515
  return hits.length ? hits : null;
19477
19516
  }
19478
19517
  function directoryFilters(input2) {
@@ -19494,10 +19533,41 @@ function directoryFilters(input2) {
19494
19533
  return { ok: true, industries: [...new Set(industries)], sizes: [...new Set(sizes)] };
19495
19534
  }
19496
19535
 
19497
- // ../contracts/src/capabilities.ts
19536
+ // ../contracts/src/tool-definitions.ts
19537
+ function toolDefinition(definition) {
19538
+ return definition;
19539
+ }
19540
+ function defineTool(identity, build3) {
19541
+ const definition = build3({
19542
+ limit: external_exports.number().int().min(1).max(identity.limit).optional(),
19543
+ maxResults: identity.limit
19544
+ });
19545
+ return {
19546
+ ...identity,
19547
+ ...definition,
19548
+ title: definition.title ?? identity.name,
19549
+ price: {
19550
+ credits: identity.credits,
19551
+ unit: identity.unit,
19552
+ basis: "run",
19553
+ free: definition.free ?? "Empty results are free."
19554
+ },
19555
+ supplierReserve: Object.values(definition.suppliers).reduce(
19556
+ (sum, step) => sum + step.cap * step.maxCalls,
19557
+ definition.reservationHeadroom
19558
+ ),
19559
+ services: [
19560
+ ...new Map(
19561
+ Object.values(definition.suppliers).map(({ endpoint, provider, via, role }) => [
19562
+ endpoint,
19563
+ { endpoint, provider, via, role }
19564
+ ])
19565
+ ).values()
19566
+ ]
19567
+ };
19568
+ }
19498
19569
  var text = (max) => external_exports.string().trim().min(1).max(max);
19499
19570
  var optionalText = (max) => external_exports.string().trim().max(max).optional();
19500
- var limit = (id) => external_exports.number().int().min(1).max(TOOL_CATALOG[id].limit).optional();
19501
19571
  var s = external_exports.string();
19502
19572
  var n = external_exports.number().nullable();
19503
19573
  var companyFilters = {
@@ -19506,283 +19576,2052 @@ var companyFilters = {
19506
19576
  };
19507
19577
  var keywordsField = external_exports.array(text(60)).min(1).max(10).optional().describe("In company description");
19508
19578
  var pageField = external_exports.number().int().min(1).max(100).optional();
19509
- function directoryRequest(input2) {
19579
+ function directoryRequest(input2, request) {
19510
19580
  const filters = directoryFilters(input2);
19511
- return {
19512
- ...filters.ok ? { ...filters.industries.length ? { industries: filters.industries } : {}, ...filters.sizes.length ? { companySizes: filters.sizes } : {} } : { industries: [`invalid:${filters.message}`] },
19581
+ const base = {
19582
+ ...request,
19513
19583
  ...input2.keywords?.length ? { companyWords: input2.keywords } : {},
19514
19584
  ...input2.page ? { page: input2.page } : {}
19515
19585
  };
19586
+ if (!filters.ok) return { request: base, issue: { field: "industries", message: filters.message } };
19587
+ return {
19588
+ ...base,
19589
+ ...filters.industries.length ? { industries: filters.industries } : {},
19590
+ ...filters.sizes.length ? { companySizes: filters.sizes } : {}
19591
+ };
19516
19592
  }
19517
19593
  var MAX_BATCH_PEOPLE = 100;
19518
19594
  var batchPeople = external_exports.array(text(300)).min(1).max(MAX_BATCH_PEOPLE).optional().describe(`Up to ${MAX_BATCH_PEOPLE} LinkedIn profile URLs or handles, instead of profile`);
19519
- var toolPrice = (id, free = "Empty results are free.") => ({
19520
- credits: TOOL_CATALOG[id].credits,
19521
- unit: TOOL_CATALOG[id].unit,
19522
- basis: "run",
19523
- free
19595
+ var TOOL_DEFINITIONS = {
19596
+ "seo-aeo-audit": defineTool(
19597
+ { name: "SEO/AEO audit", credits: 35, unit: "completed audit", limit: 1 },
19598
+ () => toolDefinition({
19599
+ description: "RankAI website audit for search engine and answer engine optimization, with a report URL when complete.",
19600
+ input: external_exports.object({ url: text(300) }).strict(),
19601
+ row: external_exports.object({ url: s, auditId: s, status: s, reportUrl: s }),
19602
+ preview: ["url", "status", "reportUrl"],
19603
+ noun: "audits",
19604
+ free: "Failed audits and empty results are free.",
19605
+ example: { url: "example.com" },
19606
+ toolRequest: (input2) => ({ tool: "seo-aeo-audit", query: input2.url }),
19607
+ web: {
19608
+ route: "seo-aeo-audit",
19609
+ description: "Audit a website for search engine and answer engine optimization with RankAI. Get a report link when complete.",
19610
+ group: "social-lead-generation",
19611
+ section: "Web research",
19612
+ order: 3
19613
+ },
19614
+ columns: {
19615
+ url: { label: "Website", kind: "mono", sample: ["example.com", "example.org"], demo: "main" },
19616
+ auditId: { label: "Audit ID", kind: "mono", sample: ["audit_example_1", "audit_example_2"], demo: "sub" },
19617
+ status: { label: "Status", kind: "pill", sample: ["Completed", "Completed"] },
19618
+ reportUrl: { label: "Report URL", kind: "text", sample: ["Report link", "Report link"], demo: "end" }
19619
+ },
19620
+ output: ["url", "auditId", "status", "reportUrl"],
19621
+ form: {
19622
+ inputMode: "url",
19623
+ mono: true,
19624
+ normalize: "trim",
19625
+ validation: "website",
19626
+ fields: [],
19627
+ grid: false,
19628
+ gate: "tools",
19629
+ example: "catalog",
19630
+ exampleLabel: "Try an example",
19631
+ exampleValues: {},
19632
+ exampleMono: true,
19633
+ progress: "RankAI is preparing your report. This can take several minutes. "
19634
+ },
19635
+ presentation: {
19636
+ description: "Audit a website for search engine and answer engine optimization with RankAI. Get a report link when the audit is complete.",
19637
+ label: "Website URL",
19638
+ example: "example.com",
19639
+ action: "Audit website",
19640
+ icon: "search",
19641
+ demo: "example.com"
19642
+ },
19643
+ suppliers: {
19644
+ rankai: {
19645
+ endpoint: "https://www.getbags.app/api/agent/link/pl-7f09b306-1f84-4da1-91d4-477d6e2a9d15",
19646
+ provider: "RankAI",
19647
+ via: "BAGS",
19648
+ role: "SEO/AEO audit over x402",
19649
+ key: "rankai",
19650
+ cap: 35e4,
19651
+ maxCalls: 1,
19652
+ transport: "audit"
19653
+ }
19654
+ },
19655
+ reservationHeadroom: 0,
19656
+ badges: [],
19657
+ followUp: null
19658
+ })
19659
+ ),
19660
+ company: defineTool(
19661
+ { name: "Company enrichment", credits: 1, unit: "company", limit: 1 },
19662
+ () => toolDefinition({
19663
+ description: "Company details from a domain: industry, size, country and about.",
19664
+ input: external_exports.object({ domain: text(100) }).strict(),
19665
+ row: external_exports.object({ name: s, domain: s, industry: s, employees: s, country: s, about: s, url: s }),
19666
+ preview: ["name", "industry", "employees", "country"],
19667
+ noun: "companies",
19668
+ free: "Empty results are free.",
19669
+ example: { domain: "vercel.com" },
19670
+ toolRequest: (input2) => ({ tool: "company", query: input2.domain }),
19671
+ web: {
19672
+ route: "company-enrichment",
19673
+ description: "Start with a domain. Get company details, industry, size and location in one place.",
19674
+ group: "profile-enrichment",
19675
+ section: "Enrichment",
19676
+ order: 6
19677
+ },
19678
+ columns: {
19679
+ name: { label: "Company name", kind: "entity", sample: ["Vercel", "Linear"], demo: "main" },
19680
+ domain: { label: "Domain", kind: "mono", sample: ["vercel.com", "linear.app"], demo: "sub" },
19681
+ industry: { label: "Industry", kind: "pill", sample: ["Software development", "Software development"] },
19682
+ employees: { label: "Employees", kind: "text", sample: ["501-1,000", "51-200"], demo: "end" },
19683
+ country: { label: "Country", kind: "text" },
19684
+ about: { label: "About", kind: "text" },
19685
+ url: { label: "LinkedIn page", kind: "text" }
19686
+ },
19687
+ output: ["name", "domain", "industry", "employees", "country", "about", "url"],
19688
+ form: {
19689
+ inputMode: "url",
19690
+ mono: true,
19691
+ normalize: "trim",
19692
+ validation: "domain",
19693
+ fields: [],
19694
+ grid: false,
19695
+ gate: "tools",
19696
+ example: "catalog",
19697
+ exampleLabel: "Try an example",
19698
+ exampleValues: {},
19699
+ exampleMono: true,
19700
+ progress: ""
19701
+ },
19702
+ presentation: {
19703
+ description: "Start with a domain. Get company details, industry, size and location in one place.",
19704
+ label: "Company domain",
19705
+ example: "vercel.com",
19706
+ action: "Enrich company",
19707
+ icon: "contact",
19708
+ demo: "vercel.com"
19709
+ },
19710
+ suppliers: {
19711
+ domain: {
19712
+ endpoint: "blitzapi.companies.domain-to-linkedin",
19713
+ provider: "Blitz",
19714
+ via: "Treg",
19715
+ role: "Resolve the domain to a LinkedIn company page",
19716
+ key: "domain",
19717
+ cap: 500,
19718
+ maxCalls: 1
19719
+ },
19720
+ company: {
19721
+ endpoint: "blitzapi.companies.enrich",
19722
+ provider: "Blitz",
19723
+ via: "Treg",
19724
+ role: "Company details",
19725
+ key: "company",
19726
+ cap: 500,
19727
+ maxCalls: 1
19728
+ }
19729
+ },
19730
+ reservationHeadroom: 1e3,
19731
+ badges: [{ name: "Blitz", logo: "blitz.png" }],
19732
+ followUp: null
19733
+ })
19734
+ ),
19735
+ "local-leads": defineTool(
19736
+ { name: "Local business leads", credits: 1, unit: "search (up to 20 businesses)", limit: 20 },
19737
+ ({ limit }) => toolDefinition({
19738
+ description: "Local businesses by type and city, with address, website and listed phone.",
19739
+ input: external_exports.object({ business_type: text(100), location: text(100), limit }).strict(),
19740
+ row: external_exports.object({ name: s, address: s, phone: s, website: s, rating: n, url: s }),
19741
+ preview: ["name", "address", "phone", "website"],
19742
+ noun: "businesses",
19743
+ free: "Empty results are free.",
19744
+ example: { business_type: "Dentists", location: "Austin" },
19745
+ toolRequest: (input2) => ({
19746
+ tool: "local-leads",
19747
+ query: input2.business_type,
19748
+ location: input2.location,
19749
+ ...input2.limit ? { limit: input2.limit } : {}
19750
+ }),
19751
+ web: {
19752
+ route: "google-maps-scraper",
19753
+ description: "Find local businesses with addresses, websites and listed phone numbers.",
19754
+ group: "social-lead-generation",
19755
+ section: "Lead lists",
19756
+ order: 1
19757
+ },
19758
+ columns: {
19759
+ name: {
19760
+ label: "Business name",
19761
+ kind: "entity",
19762
+ sample: ["Harbor Dental Studio", "Mission Family Dentistry"],
19763
+ demo: "main"
19764
+ },
19765
+ address: {
19766
+ label: "Address",
19767
+ kind: "text",
19768
+ sample: ["\u2022\u2022\u2022 Market St, San Francisco", "\u2022\u2022\u2022 24th St, San Francisco"],
19769
+ demo: "sub"
19770
+ },
19771
+ phone: { label: "Phone", kind: "mono", sample: ["+1 415 \u2022\u2022\u2022 \u2022\u202218", "+1 415 \u2022\u2022\u2022 \u2022\u202262"] },
19772
+ website: {
19773
+ label: "Website",
19774
+ kind: "mono",
19775
+ sample: ["harbordental.example", "missiondentist.example"],
19776
+ demo: "end"
19777
+ },
19778
+ rating: { label: "Rating", kind: "text" },
19779
+ url: { label: "Maps link", kind: "text" }
19780
+ },
19781
+ output: ["name", "address", "phone", "website", "rating", "url"],
19782
+ form: {
19783
+ inputMode: "text",
19784
+ mono: false,
19785
+ normalize: "trim",
19786
+ validation: "text",
19787
+ fields: [
19788
+ {
19789
+ key: "location",
19790
+ label: "City or region",
19791
+ placeholder: "Austin, Texas",
19792
+ maxLength: 100,
19793
+ required: true,
19794
+ requiredMessage: "Add a city or region."
19795
+ }
19796
+ ],
19797
+ grid: false,
19798
+ gate: "tools",
19799
+ example: "catalog",
19800
+ exampleLabel: "Try dentists in Austin",
19801
+ exampleValues: { location: "Austin, Texas" },
19802
+ exampleMono: false,
19803
+ progress: "",
19804
+ limitNoun: "businesses"
19805
+ },
19806
+ presentation: {
19807
+ description: "Discover local businesses with addresses, websites and listed business phones.",
19808
+ label: "Business category",
19809
+ example: "Dentists",
19810
+ action: "Find businesses",
19811
+ icon: "map",
19812
+ demo: "Dentists in Austin"
19813
+ },
19814
+ suppliers: {
19815
+ maps: {
19816
+ endpoint: "crawl4ai.google.serp.maps",
19817
+ provider: "Crawl4AI",
19818
+ via: "Treg",
19819
+ role: "Google Maps listings",
19820
+ key: "maps",
19821
+ cap: 500,
19822
+ maxCalls: 1
19823
+ }
19824
+ },
19825
+ reservationHeadroom: 500,
19826
+ badges: [{ name: "Google Maps", logo: "google-maps.png" }],
19827
+ followUp: null
19828
+ })
19829
+ ),
19830
+ website: defineTool(
19831
+ { name: "Website brief", credits: 1, unit: "brief", limit: 1 },
19832
+ () => toolDefinition({
19833
+ description: "Sales brief from a company website: what they do, who they sell to, products and pricing.",
19834
+ input: external_exports.object({ url: text(300) }).strict(),
19835
+ row: external_exports.object({
19836
+ company: s,
19837
+ whatTheyDo: s,
19838
+ sellsTo: s,
19839
+ products: s,
19840
+ customers: s,
19841
+ pricing: s,
19842
+ mainCta: s,
19843
+ url: s,
19844
+ fetchedAt: s
19845
+ }),
19846
+ preview: ["company", "whatTheyDo", "sellsTo", "pricing"],
19847
+ noun: "briefs",
19848
+ free: "Empty results are free.",
19849
+ example: { url: "vercel.com" },
19850
+ toolRequest: (input2) => ({ tool: "website", query: input2.url }),
19851
+ web: {
19852
+ route: "rag-web-browser",
19853
+ description: "Turn a company\u2019s website into a sales brief before you reach out.",
19854
+ group: "profile-enrichment",
19855
+ section: "Web research",
19856
+ order: 2
19857
+ },
19858
+ columns: {
19859
+ company: { label: "Company", kind: "entity", sample: ["Vercel", "Linear"], demo: "main" },
19860
+ whatTheyDo: {
19861
+ label: "What they do",
19862
+ kind: "text",
19863
+ sample: [
19864
+ "Infrastructure to build, deploy and scale web apps and AI agents",
19865
+ "Project and issue tracking for product teams"
19866
+ ],
19867
+ demo: "sub"
19868
+ },
19869
+ sellsTo: { label: "Sells to", kind: "pill", sample: ["Developers and enterprises", "Software companies"] },
19870
+ products: {
19871
+ label: "Products",
19872
+ kind: "text",
19873
+ sample: ["Fluid Compute, AI Gateway", "Issues, Projects, Cycles"],
19874
+ demo: "end"
19875
+ },
19876
+ customers: { label: "Customers", kind: "text" },
19877
+ pricing: { label: "Pricing", kind: "text" },
19878
+ mainCta: { label: RESULT_FIELD_LABELS.mainCta, kind: "text" },
19879
+ url: { label: "Website", kind: "text" },
19880
+ fetchedAt: { label: "Checked at", kind: "text" }
19881
+ },
19882
+ output: ["company", "whatTheyDo", "sellsTo", "products", "customers", "pricing", "mainCta"],
19883
+ form: {
19884
+ inputMode: "url",
19885
+ mono: true,
19886
+ normalize: "trim",
19887
+ validation: "website",
19888
+ fields: [],
19889
+ grid: false,
19890
+ gate: "tools",
19891
+ example: "catalog",
19892
+ exampleLabel: "Try an example",
19893
+ exampleValues: {},
19894
+ exampleMono: true,
19895
+ progress: ""
19896
+ },
19897
+ presentation: {
19898
+ description: "Turn a company\u2019s website into a sales brief: what they do, who they sell to, products, customers and pricing.",
19899
+ label: "Company website",
19900
+ example: "vercel.com",
19901
+ action: "Get brief",
19902
+ icon: "globe",
19903
+ demo: "vercel.com"
19904
+ },
19905
+ suppliers: {
19906
+ brief: {
19907
+ endpoint: "crawl4ai.web.extract.structured",
19908
+ provider: "Crawl4AI",
19909
+ via: "Treg",
19910
+ role: "Page to structured sales brief",
19911
+ key: "brief",
19912
+ cap: 1e4,
19913
+ maxCalls: 1
19914
+ }
19915
+ },
19916
+ reservationHeadroom: 0,
19917
+ badges: [{ name: "Crawl4AI", logo: "crawl4ai.png" }],
19918
+ followUp: null
19919
+ })
19920
+ ),
19921
+ icp: defineTool(
19922
+ { name: "Decision-maker finder", credits: 2, unit: "search (up to 10 profiles)", limit: 10 },
19923
+ ({ limit }) => toolDefinition({
19924
+ description: "People at one company domain, optionally narrowed to job titles.",
19925
+ input: external_exports.object({ company: text(100), titles: external_exports.array(text(60)).max(5).optional(), limit }).strict(),
19926
+ row: external_exports.object({ name: s, title: s, company: s, domain: s, country: s.optional(), url: s }),
19927
+ preview: ["name", "title", "company"],
19928
+ noun: "people",
19929
+ free: "Empty results are free.",
19930
+ example: { company: "vercel.com", titles: ["CEO"] },
19931
+ toolRequest: (input2) => ({
19932
+ tool: "icp",
19933
+ query: input2.company,
19934
+ titles: (input2.titles ?? []).join(", "),
19935
+ ...input2.limit ? { limit: input2.limit } : {}
19936
+ }),
19937
+ web: {
19938
+ route: "icp-waterfall",
19939
+ description: "Start with a company domain. Add job titles to narrow the search, then find emails for the people you select.",
19940
+ group: "social-lead-generation",
19941
+ section: "Lead lists",
19942
+ order: 2
19943
+ },
19944
+ columns: {
19945
+ name: { label: "Name", kind: "entity", sample: ["Guillermo Rauch", "J\u2022\u2022\u2022 M\u2022\u2022\u2022"], demo: "main" },
19946
+ title: { label: "Title", kind: "pill", sample: ["CEO", "VP of Sales"], demo: "sub" },
19947
+ company: { label: "Company", kind: "text", sample: ["Vercel", "Vercel"] },
19948
+ domain: { label: "Domain", kind: "mono", sample: ["vercel.com", "vercel.com"], demo: "end" },
19949
+ country: { label: "Country", kind: "text" },
19950
+ url: { label: "LinkedIn profile", kind: "text" }
19951
+ },
19952
+ output: ["name", "title", "company", "domain", "country", "url"],
19953
+ form: {
19954
+ inputMode: "url",
19955
+ mono: true,
19956
+ normalize: "trim",
19957
+ validation: "domain",
19958
+ fields: [
19959
+ {
19960
+ key: "titles",
19961
+ label: "Job titles (optional, comma separated)",
19962
+ placeholder: "Founder, CEO, Head of Sales",
19963
+ maxLength: 200
19964
+ }
19965
+ ],
19966
+ grid: false,
19967
+ gate: "tools",
19968
+ example: "catalog",
19969
+ exampleLabel: "Try an example",
19970
+ exampleValues: {},
19971
+ exampleMono: true,
19972
+ progress: "",
19973
+ limitNoun: "profiles"
19974
+ },
19975
+ presentation: {
19976
+ description: "Start with a company domain. Add job titles to narrow the search, then select profiles to find their emails.",
19977
+ label: "Company domain",
19978
+ example: "vercel.com",
19979
+ action: "Find decision-makers",
19980
+ icon: "waterfall",
19981
+ demo: "vercel.com + CEO"
19982
+ },
19983
+ suppliers: {
19984
+ discovery: {
19985
+ endpoint: "quickenrich.people.search",
19986
+ provider: "QuickEnrich",
19987
+ via: "Treg",
19988
+ role: "Free people discovery by domain and title",
19989
+ key: "discovery",
19990
+ cap: 0,
19991
+ maxCalls: 1
19992
+ },
19993
+ "company-domain": {
19994
+ endpoint: "blitzapi.companies.domain-to-linkedin",
19995
+ provider: "Blitz",
19996
+ via: "Treg",
19997
+ role: "Fallback: resolve the company",
19998
+ key: "company-domain",
19999
+ cap: 500,
20000
+ maxCalls: 1
20001
+ },
20002
+ qualify: {
20003
+ endpoint: "blitzapi.companies.enrich",
20004
+ provider: "Blitz",
20005
+ via: "Treg",
20006
+ role: "Fallback: confirm the company domain",
20007
+ key: "qualify",
20008
+ cap: 500,
20009
+ maxCalls: 1
20010
+ },
20011
+ "title-cascade": {
20012
+ endpoint: "blitzapi.people.waterfall-icp",
20013
+ provider: "Blitz",
20014
+ via: "Treg",
20015
+ role: "Fallback: title cascade",
20016
+ key: "title-cascade",
20017
+ cap: 1500,
20018
+ maxCalls: 1
20019
+ },
20020
+ "title-function": {
20021
+ endpoint: "blitzapi.people.waterfall-icp",
20022
+ provider: "Blitz",
20023
+ via: "Treg",
20024
+ role: "Fallback: title cascade",
20025
+ key: "title-function",
20026
+ cap: 15e3,
20027
+ maxCalls: 1
20028
+ }
20029
+ },
20030
+ reservationHeadroom: 2500,
20031
+ badges: [
20032
+ { name: "QuickEnrich", logo: "quickenrich.png" },
20033
+ { name: "Blitz", logo: "blitz.png" }
20034
+ ],
20035
+ followUp: { action: "find-emails", field: "url" }
20036
+ })
20037
+ ),
20038
+ signals: defineTool(
20039
+ { name: "Hiring signals", credits: 1, unit: "search (up to 50 companies)", limit: 50 },
20040
+ ({ limit, maxResults }) => toolDefinition({
20041
+ description: "Companies hiring for a role in the past 30 days, with website, industry and size; recruiters left out. A tool's name as the role finds companies using it.",
20042
+ input: external_exports.object({
20043
+ role: text(200),
20044
+ location: optionalText(100),
20045
+ company: optionalText(100),
20046
+ ...companyFilters,
20047
+ page: pageField,
20048
+ limit
20049
+ }).strict(),
20050
+ row: external_exports.object({ company: s, role: s, location: s, posted: s, domain: s, industry: s, employees: s, url: s }),
20051
+ preview: ["company", "domain", "role", "posted"],
20052
+ noun: "signals",
20053
+ free: "Empty results are free.",
20054
+ example: { role: "Sales Development Representative", location: "United States" },
20055
+ toolRequest: (input2) => directoryRequest(input2, {
20056
+ tool: "signals",
20057
+ query: input2.role,
20058
+ location: input2.location ?? "",
20059
+ company: input2.company ?? "",
20060
+ limit: input2.limit ?? maxResults
20061
+ }),
20062
+ web: {
20063
+ route: "hiring-signals",
20064
+ description: "Find companies hiring for a role you sell into, from recent public job posts.",
20065
+ group: "social-lead-generation",
20066
+ section: "Lead lists",
20067
+ order: 3
20068
+ },
20069
+ columns: {
20070
+ company: { label: "Company", kind: "entity", sample: ["Vanta", "Otter.ai"], demo: "main" },
20071
+ domain: { label: "Website", kind: "text" },
20072
+ role: {
20073
+ label: "Role",
20074
+ kind: "text",
20075
+ sample: ["Sales Development Representative, Enterprise", "Sales Development Representative"],
20076
+ demo: "sub"
20077
+ },
20078
+ location: { label: "Location", kind: "text", sample: ["New York, NY", "Phoenix, AZ"] },
20079
+ posted: { label: "Posted", kind: "date", sample: ["2026-10-16", "2026-10-15"], demo: "end" },
20080
+ industry: { label: "Industry", kind: "text" },
20081
+ employees: { label: "Employees", kind: "text" },
20082
+ url: { label: "Job post", kind: "text" }
20083
+ },
20084
+ output: ["company", "role", "location", "posted", "url"],
20085
+ form: {
20086
+ inputMode: "text",
20087
+ mono: false,
20088
+ normalize: "trim",
20089
+ validation: "text",
20090
+ fields: [
20091
+ { key: "location", label: "Location (optional)", placeholder: "United States", maxLength: 100 },
20092
+ { key: "company", label: "Only this company (optional)", placeholder: "Vercel", maxLength: 100 }
20093
+ ],
20094
+ grid: true,
20095
+ gate: "tools",
20096
+ example: "catalog",
20097
+ exampleLabel: "Try SDR hiring in the US",
20098
+ exampleValues: { location: "United States" },
20099
+ exampleMono: false,
20100
+ progress: "",
20101
+ limitNoun: "companies",
20102
+ recentDays: 30
20103
+ },
20104
+ presentation: {
20105
+ description: "Find companies hiring for a role you sell into. A new SDR or RevOps opening is a timely reason to reach out.",
20106
+ label: "Role being hired",
20107
+ example: "Sales Development Representative",
20108
+ action: "Find hiring companies",
20109
+ icon: "search",
20110
+ demo: "SDR \xB7 United States"
20111
+ },
20112
+ suppliers: {
20113
+ jobs: {
20114
+ endpoint: "crawl4ai.linkedin.search.jobs",
20115
+ provider: "Crawl4AI",
20116
+ via: "Treg",
20117
+ role: "Public LinkedIn job posts",
20118
+ key: "jobs",
20119
+ cap: 1e3,
20120
+ maxCalls: 1
20121
+ },
20122
+ "jobs-fallback": {
20123
+ endpoint: "harvestapi.linkedin.search.jobs",
20124
+ provider: "HarvestAPI",
20125
+ via: "Treg",
20126
+ role: "Backup when LinkedIn blocks the first source",
20127
+ key: "jobs-fallback-",
20128
+ cap: 1500,
20129
+ maxCalls: 2,
20130
+ method: "GET"
20131
+ },
20132
+ company: {
20133
+ endpoint: "quickenrich.people.search",
20134
+ provider: "QuickEnrich",
20135
+ via: "Treg",
20136
+ role: "Free company website, industry and size by exact name",
20137
+ key: "company:",
20138
+ cap: 0,
20139
+ maxCalls: 150
20140
+ }
20141
+ },
20142
+ reservationHeadroom: 0,
20143
+ badges: [{ name: "LinkedIn", logo: "linkedin.png" }],
20144
+ followUp: null
20145
+ })
20146
+ ),
20147
+ "verify-email": defineTool(
20148
+ { name: "Email verification", credits: 2, unit: "definitive verification", limit: 1 },
20149
+ () => toolDefinition({
20150
+ description: "Mailbox check for one email address.",
20151
+ input: external_exports.object({ email: text(254) }).strict(),
20152
+ row: external_exports.object({ email: s, verdict: s, score: n, checkedAt: s }),
20153
+ preview: ["email", "verdict", "score"],
20154
+ noun: "verifications",
20155
+ free: "Unknown, webmail and disposable results are free.",
20156
+ example: { email: "jane@example.com" },
20157
+ toolRequest: (input2) => ({ tool: "verify-email", query: input2.email }),
20158
+ web: {
20159
+ route: "lead-verification",
20160
+ description: "Check a mailbox before you reach out. Accept-all and unknown results stay marked as uncertain.",
20161
+ group: "lead-verification",
20162
+ section: "Enrichment",
20163
+ order: 2
20164
+ },
20165
+ columns: {
20166
+ email: { label: "Email", kind: "mono", sample: ["n\u2022\u2022\u2022@company.com", "s\u2022\u2022\u2022@company.com"], demo: "main" },
20167
+ verdict: { label: "Verdict", kind: "status", sample: ["Deliverable", "Accept-all \xB7 uncertain"], demo: "sub" },
20168
+ score: { label: "Score", kind: "score", sample: ["98", "50"], demo: "end" },
20169
+ checkedAt: { label: "Checked at", kind: "date", sample: ["2026-10-20 09:41", "2026-10-20 09:41"] }
20170
+ },
20171
+ output: ["email", "verdict", "score", "checkedAt"],
20172
+ form: {
20173
+ inputMode: "email",
20174
+ mono: true,
20175
+ normalize: "trim",
20176
+ validation: "email",
20177
+ fields: [],
20178
+ grid: false,
20179
+ gate: "tools",
20180
+ example: "email",
20181
+ exampleLabel: "Use my email",
20182
+ exampleValues: {},
20183
+ exampleMono: true,
20184
+ progress: ""
20185
+ },
20186
+ presentation: {
20187
+ description: "Check a mailbox before you reach out. Accept-all and unknown results stay marked as uncertain.",
20188
+ label: "Email address",
20189
+ example: "name@company.com",
20190
+ action: "Verify email",
20191
+ icon: "verify",
20192
+ demo: "name@company.com"
20193
+ },
20194
+ suppliers: {
20195
+ verification: {
20196
+ endpoint: "treg.people.email.verify",
20197
+ provider: "Routed",
20198
+ via: "Treg",
20199
+ role: "Mailbox verification",
20200
+ key: "verification",
20201
+ cap: 5e3,
20202
+ maxCalls: 1,
20203
+ method: "POST",
20204
+ routeHeaders: { "X-Treg-Route-Exclude": "contactout" }
20205
+ }
20206
+ },
20207
+ reservationHeadroom: 0,
20208
+ badges: [],
20209
+ followUp: null
20210
+ })
20211
+ ),
20212
+ "phone-pilot": defineTool(
20213
+ { name: "Mobile enrichment", credits: 5, unit: "returned number", limit: 1 },
20214
+ () => toolDefinition({
20215
+ description: "Mobile number for one LinkedIn profile you have permission to enrich.",
20216
+ input: external_exports.object({ profile: text(300) }).strict(),
20217
+ row: external_exports.object({ phone: s, type: s, country: s, url: s }),
20218
+ preview: ["phone", "type", "country"],
20219
+ noun: "phones",
20220
+ free: "No number found is free.",
20221
+ example: { profile: "https://www.linkedin.com/in/satyanadella" },
20222
+ toolRequest: (input2) => ({ tool: "phone-pilot", query: linkedinProfileUrl(input2.profile) }),
20223
+ web: {
20224
+ route: "phone-enrichment",
20225
+ description: "Find a mobile number for a LinkedIn profile you have permission to enrich. Searches 15 phone data providers; coverage varies by country.",
20226
+ group: "phone-enrichment",
20227
+ section: "Enrichment",
20228
+ order: 3
20229
+ },
20230
+ columns: {
20231
+ phone: { label: "Phone number", kind: "mono", sample: ["+1 415 \u2022\u2022\u2022 \u2022\u202242", "+44 7\u2022\u2022\u2022 \u2022\u2022\u2022903"], demo: "main" },
20232
+ type: { label: "Line type", kind: "pill", sample: ["Mobile", "Mobile"], demo: "sub" },
20233
+ country: { label: "Country", kind: "text", sample: ["United States", "United Kingdom"] },
20234
+ url: { label: "Profile", kind: "mono", sample: ["linkedin.com/in/\u2022\u2022\u2022", "linkedin.com/in/\u2022\u2022\u2022"], demo: "end" }
20235
+ },
20236
+ output: ["phone", "type", "country", "url"],
20237
+ form: {
20238
+ inputMode: "url",
20239
+ mono: true,
20240
+ normalize: "trim",
20241
+ validation: "linkedin-profile",
20242
+ fields: [],
20243
+ grid: false,
20244
+ gate: "phone",
20245
+ example: "none",
20246
+ exampleLabel: "Try an example",
20247
+ exampleValues: {},
20248
+ exampleMono: true,
20249
+ progress: ""
20250
+ },
20251
+ presentation: {
20252
+ description: "Find a mobile number for a profile you have permission to enrich. We search 15 phone data providers in turn; coverage and line types vary by country.",
20253
+ label: "LinkedIn profile URL",
20254
+ example: "https://www.linkedin.com/in/your-profile",
20255
+ action: "Find number",
20256
+ icon: "phone",
20257
+ demo: "linkedin.com/in/\u2026"
20258
+ },
20259
+ suppliers: {
20260
+ phone: {
20261
+ endpoint: "treg.people.phone.find",
20262
+ provider: "Treg phone waterfall (15 providers, cheapest first)",
20263
+ via: "Treg",
20264
+ role: "Mobile number",
20265
+ key: "phone",
20266
+ cap: 5e4,
20267
+ maxCalls: 1
20268
+ }
20269
+ },
20270
+ reservationHeadroom: 0,
20271
+ badges: [],
20272
+ followUp: null
20273
+ })
20274
+ ),
20275
+ "people-search": defineTool(
20276
+ { name: "People search", credits: 2, unit: "search (up to 100 people)", limit: 100 },
20277
+ ({ limit, maxResults }) => toolDefinition({
20278
+ description: "People by job titles, where they live, and company industry, size or description. Up to 100 per page.",
20279
+ input: external_exports.object({
20280
+ titles: external_exports.array(text(60)).min(1).max(5),
20281
+ location: optionalText(100),
20282
+ ...companyFilters,
20283
+ keywords: keywordsField,
20284
+ page: pageField,
20285
+ limit
20286
+ }).strict(),
20287
+ row: external_exports.object({ name: s, title: s, company: s, domain: s, industry: s, employees: s, location: s, url: s }),
20288
+ preview: ["name", "title", "company", "location"],
20289
+ noun: "people",
20290
+ free: "Empty results are free.",
20291
+ example: { titles: ["VP Sales"], location: "United States", industries: ["SaaS"], company_sizes: ["20-99"] },
20292
+ toolRequest: (input2) => directoryRequest(input2, {
20293
+ tool: "people-search",
20294
+ query: input2.titles.join(", "),
20295
+ location: input2.location ?? "",
20296
+ limit: input2.limit ?? maxResults
20297
+ }),
20298
+ web: {
20299
+ route: "people-search",
20300
+ description: "Build a lead list by job title and location, then find emails for the people you select.",
20301
+ group: "social-lead-generation",
20302
+ section: "Lead lists",
20303
+ order: 0
20304
+ },
20305
+ columns: {
20306
+ name: { label: "Name", kind: "entity", sample: ["A\u2022\u2022\u2022 L\u2022\u2022\u2022", "M\u2022\u2022\u2022 K\u2022\u2022\u2022"], demo: "main" },
20307
+ title: { label: "Title", kind: "pill", sample: ["VP Sales", "Head of Sales"], demo: "sub" },
20308
+ company: { label: "Company", kind: "text", sample: ["Stripe", "Ramp"] },
20309
+ domain: { label: "Domain", kind: "mono", sample: ["stripe.com", "ramp.com"], demo: "end" },
20310
+ industry: { label: "Industry", kind: "text" },
20311
+ employees: { label: "Employees", kind: "text" },
20312
+ location: { label: "Location", kind: "text" },
20313
+ url: { label: "LinkedIn profile", kind: "text" }
20314
+ },
20315
+ output: ["name", "title", "company", "domain", "industry", "employees", "location", "url"],
20316
+ form: {
20317
+ inputMode: "text",
20318
+ mono: false,
20319
+ normalize: "trim",
20320
+ validation: "text",
20321
+ fields: [
20322
+ { key: "location", label: "Country or city (optional)", placeholder: "United States", maxLength: 100 }
20323
+ ],
20324
+ grid: false,
20325
+ gate: "tools",
20326
+ example: "catalog",
20327
+ exampleLabel: "Try sales leaders in the US",
20328
+ exampleValues: { location: "United States" },
20329
+ exampleMono: false,
20330
+ progress: "",
20331
+ limitNoun: "people"
20332
+ },
20333
+ presentation: {
20334
+ description: "Build a lead list by job title and location. Select the people you want, then find their emails.",
20335
+ label: "Job titles (comma separated)",
20336
+ example: "VP Sales, Head of Sales",
20337
+ action: "Find people",
20338
+ icon: "social",
20339
+ demo: "VP Sales \xB7 United States"
20340
+ },
20341
+ suppliers: {
20342
+ people: {
20343
+ endpoint: "quickenrich.people.search",
20344
+ provider: "QuickEnrich",
20345
+ via: "Treg",
20346
+ role: "Free people discovery by title and location",
20347
+ key: "people",
20348
+ cap: 0,
20349
+ maxCalls: 1
20350
+ }
20351
+ },
20352
+ reservationHeadroom: 1e3,
20353
+ badges: [{ name: "QuickEnrich", logo: "quickenrich.png" }],
20354
+ followUp: { action: "find-emails", field: "url" }
20355
+ })
20356
+ ),
20357
+ "google-search": defineTool(
20358
+ { name: "Google search", credits: 1, unit: "search (up to 20 results)", limit: 20 },
20359
+ ({ limit }) => toolDefinition({
20360
+ description: "Top Google organic results for a query (United States, English).",
20361
+ input: external_exports.object({ query: text(500), limit }).strict(),
20362
+ row: external_exports.object({ position: n, title: s, domain: s, snippet: s, url: s }),
20363
+ preview: ["position", "title", "domain"],
20364
+ noun: "results",
20365
+ free: "Empty results are free.",
20366
+ example: { query: "best crm for startups" },
20367
+ toolRequest: (input2) => ({
20368
+ tool: "google-search",
20369
+ query: input2.query,
20370
+ ...input2.limit ? { limit: input2.limit } : {}
20371
+ }),
20372
+ web: {
20373
+ route: "google-search-scraper",
20374
+ description: "Turn a search query into Google's top results: titles, sites, snippets and links.",
20375
+ group: "social-lead-generation",
20376
+ section: "Web research",
20377
+ order: 0
20378
+ },
20379
+ columns: {
20380
+ position: { label: "Position", kind: "text", sample: ["1", "2"], demo: "main" },
20381
+ title: {
20382
+ label: "Title",
20383
+ kind: "entity",
20384
+ sample: ["The best CRM software for startups", "Top CRM tools compared"],
20385
+ demo: "sub"
20386
+ },
20387
+ domain: { label: "Domain", kind: "mono", sample: ["zapier.com", "g2.com"] },
20388
+ snippet: {
20389
+ label: "Snippet",
20390
+ kind: "text",
20391
+ sample: ["We tested dozens of CRMs\u2026", "Compare features and pricing\u2026"],
20392
+ demo: "end"
20393
+ },
20394
+ url: { label: "Link", kind: "text" }
20395
+ },
20396
+ output: ["position", "title", "domain", "snippet", "url"],
20397
+ form: {
20398
+ inputMode: "text",
20399
+ mono: false,
20400
+ normalize: "trim",
20401
+ validation: "text",
20402
+ fields: [],
20403
+ grid: false,
20404
+ gate: "tools",
20405
+ example: "catalog",
20406
+ exampleLabel: "Try an example",
20407
+ exampleValues: {},
20408
+ exampleMono: false,
20409
+ progress: "",
20410
+ limitNoun: "results"
20411
+ },
20412
+ presentation: {
20413
+ description: "Turn a search query into Google's top organic results, ready to research or export.",
20414
+ label: "Search query",
20415
+ example: "best crm for startups",
20416
+ action: "Search Google",
20417
+ icon: "search",
20418
+ demo: "best crm for startups"
20419
+ },
20420
+ suppliers: {
20421
+ serp: {
20422
+ endpoint: "treg.google.serp.organic",
20423
+ provider: "Routed",
20424
+ via: "Treg",
20425
+ role: "Google organic results",
20426
+ key: "serp",
20427
+ cap: 3e3,
20428
+ maxCalls: 1,
20429
+ method: "POST"
20430
+ }
20431
+ },
20432
+ reservationHeadroom: 0,
20433
+ badges: [{ name: "Google", logo: "google.png" }],
20434
+ followUp: null
20435
+ })
20436
+ ),
20437
+ "linkedin-profile": defineTool(
20438
+ { name: "LinkedIn profile", credits: 1, unit: "profile", limit: 1 },
20439
+ () => toolDefinition({
20440
+ description: `Public LinkedIn profile: headline, current role, company, location and about. One profile or up to ${MAX_BATCH_PEOPLE} people.`,
20441
+ input: external_exports.object({ profile: text(300).optional(), people: batchPeople }).strict(),
20442
+ row: external_exports.object({
20443
+ name: s,
20444
+ headline: s,
20445
+ role: s,
20446
+ company: s,
20447
+ location: s,
20448
+ followers: n,
20449
+ about: s,
20450
+ companyPage: s,
20451
+ url: s
20452
+ }),
20453
+ preview: ["name", "role", "company", "location"],
20454
+ noun: "profiles",
20455
+ free: "Profiles not found are free.",
20456
+ searchWords: "current job title employer moved changed change changes verify bulk batch list",
20457
+ example: { profile: "https://www.linkedin.com/in/williamhgates" },
20458
+ toolRequest: (input2) => ({ tool: "linkedin-profile", query: linkedinProfileUrl(input2.profile ?? "") }),
20459
+ batch: true,
20460
+ web: {
20461
+ route: "linkedin-scraper",
20462
+ description: "Read a public LinkedIn profile: headline, current role, company, location and about.",
20463
+ group: "profile-enrichment",
20464
+ section: "Enrichment",
20465
+ order: 4
20466
+ },
20467
+ columns: {
20468
+ name: { label: "Name", kind: "entity", sample: ["Bill Gates", "Satya Nadella"], demo: "main" },
20469
+ headline: {
20470
+ label: "Headline",
20471
+ kind: "text",
20472
+ sample: ["Chair, Gates Foundation", "Chairman and CEO at Microsoft"],
20473
+ demo: "sub"
20474
+ },
20475
+ role: { label: "Role", kind: "pill", sample: ["Co-chair", "Chairman and CEO"] },
20476
+ company: { label: "Company", kind: "text", sample: ["Gates Foundation", "Microsoft"], demo: "end" },
20477
+ location: { label: "Location", kind: "text" },
20478
+ followers: { label: "Followers", kind: "text" },
20479
+ about: { label: "About", kind: "text" },
20480
+ companyPage: { label: RESULT_FIELD_LABELS.companyPage, kind: "text" },
20481
+ url: { label: "Profile", kind: "text" }
20482
+ },
20483
+ output: ["name", "headline", "role", "company", "location", "followers", "about", "companyPage", "url"],
20484
+ form: {
20485
+ inputMode: "url",
20486
+ mono: true,
20487
+ normalize: "trim",
20488
+ validation: "linkedin-profile",
20489
+ fields: [],
20490
+ grid: false,
20491
+ gate: "tools",
20492
+ example: "catalog",
20493
+ exampleLabel: "Try an example",
20494
+ exampleValues: {},
20495
+ exampleMono: true,
20496
+ progress: ""
20497
+ },
20498
+ presentation: {
20499
+ description: "Read a public LinkedIn profile: headline, current role, company, location and about.",
20500
+ label: "LinkedIn profile URL",
20501
+ example: "https://www.linkedin.com/in/williamhgates",
20502
+ action: "Get profile",
20503
+ icon: "linkedin",
20504
+ demo: "linkedin.com/in/williamhgates"
20505
+ },
20506
+ suppliers: {
20507
+ profile: {
20508
+ endpoint: "fetchinio.linkedin.user.profile",
20509
+ provider: "Fetchin",
20510
+ via: "Treg",
20511
+ role: "Public LinkedIn profile",
20512
+ key: "profile",
20513
+ cap: 5e3,
20514
+ maxCalls: 1,
20515
+ method: "GET"
20516
+ }
20517
+ },
20518
+ reservationHeadroom: 0,
20519
+ badges: [],
20520
+ followUp: null
20521
+ })
20522
+ ),
20523
+ "linkedin-activity": defineTool(
20524
+ { name: "LinkedIn activity", credits: 1, unit: "profile with posts", limit: 1 },
20525
+ () => toolDefinition({
20526
+ description: `Recent public LinkedIn posts with exact dates: last post, posts in 90 and 365 days, and posts on topics you name. One profile or up to ${MAX_BATCH_PEOPLE} people.`,
20527
+ input: external_exports.object({
20528
+ profile: text(300).optional(),
20529
+ people: batchPeople,
20530
+ topics: external_exports.array(text(40)).max(10).optional().describe("Words to look for in the past year's posts, like automation")
20531
+ }).strict(),
20532
+ row: external_exports.object({
20533
+ name: s,
20534
+ headline: s,
20535
+ lastPostAt: s,
20536
+ posts90d: external_exports.number(),
20537
+ posts365d: external_exports.number(),
20538
+ topics: s,
20539
+ topicPosts: n,
20540
+ post: s,
20541
+ postAt: s,
20542
+ postKind: s,
20543
+ postUrl: s,
20544
+ url: s
20545
+ }),
20546
+ preview: ["name", "lastPostAt", "posts90d", "topicPosts"],
20547
+ noun: "profiles",
20548
+ free: "Profiles with no public posts are free.",
20549
+ searchWords: "posting active activity talk talks talking mentions mentioned engagement social signal signals intent bulk batch list",
20550
+ example: { profile: "https://www.linkedin.com/in/williamhgates", topics: ["climate"] },
20551
+ // Commas would split a topic, so each is kept whole by dropping them.
20552
+ toolRequest: (input2) => ({
20553
+ tool: "linkedin-activity",
20554
+ query: linkedinProfileUrl(input2.profile ?? ""),
20555
+ ...input2.topics?.length ? { keywords: input2.topics.map((t) => t.replace(/,/g, " ").trim()).join(", ") } : {}
20556
+ }),
20557
+ batch: true,
20558
+ web: {
20559
+ route: "linkedin-activity",
20560
+ description: "See when someone last posted on LinkedIn and whether their recent posts mention the topics you sell into.",
20561
+ group: "profile-enrichment",
20562
+ section: "Enrichment",
20563
+ order: 5
20564
+ },
20565
+ columns: {
20566
+ name: { label: "Name", kind: "entity", sample: ["A\u2022\u2022\u2022 L\u2022\u2022\u2022", "M\u2022\u2022\u2022 R\u2022\u2022\u2022"], demo: "main" },
20567
+ headline: { label: "Headline", kind: "text" },
20568
+ lastPostAt: {
20569
+ label: RESULT_FIELD_LABELS.lastPostAt,
20570
+ kind: "date",
20571
+ sample: ["2026-10-21", "2026-10-24"],
20572
+ demo: "sub"
20573
+ },
20574
+ posts90d: { label: RESULT_FIELD_LABELS.posts90d, kind: "text", sample: ["9", "14"] },
20575
+ posts365d: { label: RESULT_FIELD_LABELS.posts365d, kind: "text" },
20576
+ topics: { label: "Topics", kind: "text" },
20577
+ topicPosts: { label: "Topic posts", kind: "text", sample: ["4", "6"], demo: "end" },
20578
+ post: { label: "Post", kind: "text" },
20579
+ postAt: { label: RESULT_FIELD_LABELS.postAt, kind: "text" },
20580
+ postKind: { label: "Post type", kind: "text" },
20581
+ postUrl: { label: "Post link", kind: "text" },
20582
+ url: { label: "Profile", kind: "text" }
20583
+ },
20584
+ output: [
20585
+ "name",
20586
+ "lastPostAt",
20587
+ "posts90d",
20588
+ "topicPosts",
20589
+ "headline",
20590
+ "posts365d",
20591
+ "topics",
20592
+ "post",
20593
+ "postAt",
20594
+ "postKind",
20595
+ "postUrl",
20596
+ "url"
20597
+ ],
20598
+ form: {
20599
+ inputMode: "url",
20600
+ mono: true,
20601
+ normalize: "trim",
20602
+ validation: "linkedin-profile",
20603
+ fields: [
20604
+ {
20605
+ key: "keywords",
20606
+ label: "Topics (optional, comma separated)",
20607
+ placeholder: "automation, robotics",
20608
+ maxLength: 300
20609
+ }
20610
+ ],
20611
+ grid: false,
20612
+ gate: "tools",
20613
+ example: "catalog",
20614
+ exampleLabel: "Try an example",
20615
+ exampleValues: {},
20616
+ exampleMono: true,
20617
+ progress: ""
20618
+ },
20619
+ presentation: {
20620
+ description: "See when someone last posted on LinkedIn, how often they post, and their latest post about the topics you add.",
20621
+ label: "LinkedIn profile URL",
20622
+ example: "https://www.linkedin.com/in/williamhgates",
20623
+ action: "Check activity",
20624
+ icon: "linkedin",
20625
+ demo: "automation, robotics"
20626
+ },
20627
+ suppliers: {
20628
+ posts: {
20629
+ endpoint: "fetchinio.linkedin.user.posts",
20630
+ provider: "Fetchin",
20631
+ via: "Treg",
20632
+ role: "Public LinkedIn posts with dates",
20633
+ key: "posts",
20634
+ cap: 1500,
20635
+ maxCalls: 5,
20636
+ method: "GET"
20637
+ }
20638
+ },
20639
+ reservationHeadroom: 0,
20640
+ badges: [],
20641
+ followUp: null
20642
+ })
20643
+ ),
20644
+ "profile-finder": defineTool(
20645
+ { name: "Find LinkedIn profile", credits: 1, unit: "profile found", limit: 1 },
20646
+ () => toolDefinition({
20647
+ description: `A person's LinkedIn profile from their name and company, checked against both. One person or up to ${MAX_BATCH_PEOPLE} people.`,
20648
+ input: external_exports.object({
20649
+ name: text(100).optional().describe("Full name, like Pedro Reis"),
20650
+ company: text(100).optional().describe("Company name or domain, like Adyen"),
20651
+ people: external_exports.array(external_exports.object({ name: text(100), company: text(100) }).strict()).min(1).max(MAX_BATCH_PEOPLE).optional().describe(`Up to ${MAX_BATCH_PEOPLE} {name, company} pairs, instead of name and company`)
20652
+ }).strict(),
20653
+ row: external_exports.object({ name: s, title: s, company: s, location: s, url: s }),
20654
+ preview: ["name", "title", "company", "url"],
20655
+ noun: "profiles",
20656
+ free: "People not found are free.",
20657
+ example: { name: "Pedro Reis", company: "Adyen" },
20658
+ toolRequest: (input2) => ({ tool: "profile-finder", query: input2.name ?? "", company: input2.company ?? "" }),
20659
+ batch: true,
20660
+ searchWords: "linkedin url name names person lookup resolve match who bulk batch list",
20661
+ web: {
20662
+ route: "linkedin-profile-finder",
20663
+ description: "Start with a name and a company. Get the person's LinkedIn profile, then find their email.",
20664
+ group: "profile-enrichment",
20665
+ section: "Enrichment",
20666
+ order: 1
20667
+ },
20668
+ columns: {
20669
+ name: { label: "Name", kind: "entity", sample: ["P\u2022\u2022\u2022 R\u2022\u2022\u2022", "W\u2022\u2022\u2022 P\u2022\u2022\u2022"], demo: "main" },
20670
+ title: { label: "Title", kind: "text", sample: ["Software Engineer", "Director of Product"], demo: "sub" },
20671
+ company: { label: "Company", kind: "text", sample: ["Adyen", "Cloudflare"] },
20672
+ location: { label: "Location", kind: "text" },
20673
+ url: { label: "Profile", kind: "mono", sample: ["linkedin.com/in/\u2022\u2022\u2022", "linkedin.com/in/\u2022\u2022\u2022"], demo: "end" }
20674
+ },
20675
+ output: ["name", "title", "company", "url", "location"],
20676
+ form: {
20677
+ inputMode: "text",
20678
+ mono: false,
20679
+ normalize: "trim",
20680
+ validation: "text",
20681
+ fields: [
20682
+ {
20683
+ key: "company",
20684
+ label: "Company",
20685
+ placeholder: "Adyen",
20686
+ maxLength: 100,
20687
+ required: true,
20688
+ requiredMessage: "Add the person's company."
20689
+ }
20690
+ ],
20691
+ grid: false,
20692
+ gate: "tools",
20693
+ example: "catalog",
20694
+ exampleLabel: "Try an example",
20695
+ exampleValues: { company: "Adyen" },
20696
+ exampleMono: true,
20697
+ progress: ""
20698
+ },
20699
+ presentation: {
20700
+ description: "Start with a name and a company. Get the person's LinkedIn profile, then select it to find their email.",
20701
+ label: "Full name",
20702
+ example: "Pedro Reis",
20703
+ action: "Find profile",
20704
+ icon: "linkedin",
20705
+ demo: "Pedro Reis, Adyen"
20706
+ },
20707
+ suppliers: {
20708
+ search: {
20709
+ endpoint: "harvestapi.linkedin.profile.search",
20710
+ provider: "HarvestAPI",
20711
+ via: "Treg",
20712
+ role: "LinkedIn people search by name and company",
20713
+ key: "search",
20714
+ cap: 6e3,
20715
+ maxCalls: 3,
20716
+ method: "GET"
20717
+ },
20718
+ fallback: {
20719
+ endpoint: "icypeas.people.profile.url",
20720
+ provider: "Icypeas",
20721
+ via: "Treg",
20722
+ role: "Fallback: profile URL from name and company",
20723
+ key: "fallback",
20724
+ cap: 25e3,
20725
+ maxCalls: 1
20726
+ }
20727
+ },
20728
+ reservationHeadroom: 0,
20729
+ badges: [],
20730
+ followUp: { action: "find-emails", field: "url" }
20731
+ })
20732
+ ),
20733
+ "page-content": defineTool(
20734
+ { name: "Web page content", credits: 1, unit: "page", limit: 1 },
20735
+ () => toolDefinition({
20736
+ description: "Readable text of one public web page.",
20737
+ input: external_exports.object({ url: text(300) }).strict(),
20738
+ row: external_exports.object({ title: s, url: s, words: external_exports.number(), content: s }),
20739
+ preview: ["title", "url", "words"],
20740
+ noun: "pages",
20741
+ free: "Empty results are free.",
20742
+ example: { url: "vercel.com/pricing" },
20743
+ toolRequest: (input2) => ({ tool: "page-content", query: input2.url }),
20744
+ web: {
20745
+ route: "web-page-content",
20746
+ description: "Turn any public web page into clean, readable text you can research, quote or export.",
20747
+ group: "social-lead-generation",
20748
+ section: "Web research",
20749
+ order: 1
20750
+ },
20751
+ columns: {
20752
+ title: { label: "Title", kind: "entity", sample: ["Vercel Pricing", "Linear Pricing"], demo: "main" },
20753
+ url: { label: "URL", kind: "mono", sample: ["vercel.com/pricing", "linear.app/pricing"], demo: "sub" },
20754
+ words: { label: "Words", kind: "text", sample: ["1,240", "860"] },
20755
+ content: {
20756
+ label: "Content",
20757
+ kind: "text",
20758
+ sample: ["Find a plan to power your apps\u2026", "Free for small teams. Upgrade\u2026"],
20759
+ demo: "end"
20760
+ }
20761
+ },
20762
+ output: ["title", "url", "words", "content"],
20763
+ form: {
20764
+ inputMode: "url",
20765
+ mono: true,
20766
+ normalize: "trim",
20767
+ validation: "website",
20768
+ fields: [],
20769
+ grid: false,
20770
+ gate: "tools",
20771
+ example: "catalog",
20772
+ exampleLabel: "Try an example",
20773
+ exampleValues: {},
20774
+ exampleMono: true,
20775
+ progress: ""
20776
+ },
20777
+ presentation: {
20778
+ description: "Turn any public web page into clean, readable text: pricing pages, case studies, job posts or docs.",
20779
+ label: "Page URL",
20780
+ example: "vercel.com/pricing",
20781
+ action: "Read page",
20782
+ icon: "globe",
20783
+ demo: "vercel.com/pricing"
20784
+ },
20785
+ suppliers: {
20786
+ page: {
20787
+ endpoint: "treg.web.extract",
20788
+ provider: "Treg extract waterfall (15 providers, Crawl4AI first)",
20789
+ via: "Treg",
20790
+ role: "Readable page content",
20791
+ key: "page",
20792
+ cap: 1e4,
20793
+ maxCalls: 1
20794
+ }
20795
+ },
20796
+ reservationHeadroom: 5e3,
20797
+ badges: [],
20798
+ followUp: null
20799
+ })
20800
+ ),
20801
+ "instagram-profile": defineTool(
20802
+ { name: "Instagram profile", credits: 1, unit: "profile", limit: 1 },
20803
+ () => toolDefinition({
20804
+ description: "Public Instagram profile with followers, bio, website and the business email or phone it shows.",
20805
+ input: external_exports.object({ profile: text(200).describe("Instagram username, @handle or profile URL") }).strict(),
20806
+ row: external_exports.object({
20807
+ handle: s,
20808
+ name: s,
20809
+ bio: s,
20810
+ followers: n,
20811
+ following: n,
20812
+ business: external_exports.boolean(),
20813
+ verified: external_exports.boolean(),
20814
+ website: s,
20815
+ email: s,
20816
+ phone: s,
20817
+ url: s
20818
+ }),
20819
+ preview: ["handle", "followers", "email", "website"],
20820
+ noun: "profiles",
20821
+ free: "Private and missing accounts are free.",
20822
+ searchWords: "insta ig creator creators influencer influencers brand social contact email phone followers",
20823
+ example: { profile: "gymshark" },
20824
+ toolRequest: (input2) => ({ tool: "instagram-profile", query: instagramHandle(input2.profile) }),
20825
+ web: {
20826
+ route: "instagram-profile-scraper",
20827
+ description: "Read a public Instagram profile: followers, bio, website and the business email or phone it shows.",
20828
+ group: "social-lead-generation",
20829
+ section: "Social listening",
20830
+ order: 2
20831
+ },
20832
+ columns: {
20833
+ handle: { label: "Handle", kind: "mono", sample: ["gymshark", "bluetokaicoffee"], demo: "main" },
20834
+ name: { label: "Name", kind: "entity", sample: ["Gymshark", "Blue Tokai Coffee Roasters"], demo: "sub" },
20835
+ bio: { label: "Bio", kind: "text", sample: ["We Do Gym.", "Roasting India's best coffee."] },
20836
+ followers: { label: "Followers", kind: "text", sample: ["8,724,897", "151,537"], demo: "end" },
20837
+ following: { label: "Following", kind: "text" },
20838
+ business: { label: "Business account", kind: "text" },
20839
+ verified: { label: "Verified", kind: "text" },
20840
+ website: { label: "Website", kind: "text" },
20841
+ email: { label: "Email", kind: "text" },
20842
+ phone: { label: "Phone", kind: "text" },
20843
+ url: { label: "Profile", kind: "text" }
20844
+ },
20845
+ output: [
20846
+ "handle",
20847
+ "name",
20848
+ "bio",
20849
+ "followers",
20850
+ "following",
20851
+ "business",
20852
+ "verified",
20853
+ "website",
20854
+ "email",
20855
+ "phone",
20856
+ "url"
20857
+ ],
20858
+ form: {
20859
+ inputMode: "url",
20860
+ mono: true,
20861
+ normalize: "instagram",
20862
+ validation: "instagram",
20863
+ fields: [],
20864
+ grid: false,
20865
+ gate: "tools",
20866
+ example: "catalog",
20867
+ exampleLabel: "Try an example",
20868
+ exampleValues: {},
20869
+ exampleMono: true,
20870
+ progress: ""
20871
+ },
20872
+ presentation: {
20873
+ description: "Read a public Instagram profile: followers, bio, website and the business email or phone the account shows.",
20874
+ label: "Instagram username or profile URL",
20875
+ example: "gymshark",
20876
+ action: "Get profile",
20877
+ icon: "instagram",
20878
+ demo: "gymshark"
20879
+ },
20880
+ suppliers: {
20881
+ profile: {
20882
+ endpoint: "anyapi.instagram.profile",
20883
+ provider: "AnyAPI",
20884
+ via: "Treg",
20885
+ role: "Public Instagram profile",
20886
+ key: "profile",
20887
+ cap: 5e3,
20888
+ maxCalls: 1
20889
+ },
20890
+ contact: {
20891
+ endpoint: "anyapi.instagram.profile_contact",
20892
+ provider: "AnyAPI",
20893
+ via: "Treg",
20894
+ role: "Business email and phone the account shows",
20895
+ key: "contact",
20896
+ cap: 1e4,
20897
+ maxCalls: 1
20898
+ }
20899
+ },
20900
+ reservationHeadroom: 0,
20901
+ badges: [{ name: "Instagram", logo: "instagram.png" }],
20902
+ followUp: null
20903
+ })
20904
+ ),
20905
+ "x-search": defineTool(
20906
+ { name: "X post search", credits: 1, unit: "search (up to 20 posts)", limit: 20 },
20907
+ ({ limit }) => toolDefinition({
20908
+ description: "Recent public X (Twitter) posts matching a phrase, newest first, with author and engagement. Every bare word must appear; quote a phrase or use OR.",
20909
+ input: external_exports.object({
20910
+ query: text(300).describe('Phrase or X search syntax, like "looking for a CRM"'),
20911
+ within: external_exports.enum(SEARCH_WINDOWS).optional(),
20912
+ limit
20913
+ }).strict(),
20914
+ row: external_exports.object({
20915
+ author: s,
20916
+ name: s,
20917
+ followers: n,
20918
+ text: s,
20919
+ postedAt: s,
20920
+ likes: n,
20921
+ replies: n,
20922
+ reposts: n,
20923
+ views: n,
20924
+ reply: external_exports.boolean(),
20925
+ url: s
20926
+ }),
20927
+ preview: ["author", "text", "postedAt"],
20928
+ noun: "posts",
20929
+ free: "Empty results are free.",
20930
+ searchWords: "twitter tweets tweet social listening intent buyer buyers asking recommendation mentions",
20931
+ example: { query: '"looking for a CRM"', within: "week" },
20932
+ toolRequest: (input2) => ({
20933
+ tool: "x-search",
20934
+ query: input2.query,
20935
+ ...input2.within ? { within: input2.within } : {},
20936
+ ...input2.limit ? { limit: input2.limit } : {}
20937
+ }),
20938
+ web: {
20939
+ route: "x-post-search",
20940
+ description: "Find recent X posts where people ask for a tool, compare vendors or complain about one.",
20941
+ group: "social-lead-generation",
20942
+ section: "Social listening",
20943
+ order: 0
20944
+ },
20945
+ columns: {
20946
+ author: { label: "Author", kind: "mono", sample: ["@r\u2022\u2022\u2022", "@m\u2022\u2022\u2022"], demo: "main" },
20947
+ name: { label: "Name", kind: "entity", sample: ["R\u2022\u2022\u2022 G\u2022\u2022\u2022", "M\u2022\u2022\u2022 K\u2022\u2022\u2022"], demo: "sub" },
20948
+ followers: { label: "Followers", kind: "text", sample: ["763", "2,140"] },
20949
+ text: {
20950
+ label: "Post",
20951
+ kind: "text",
20952
+ sample: ["Looking for a CRM with automation\u2026", "Any CRM that isn't a pain to set up?"],
20953
+ demo: "end"
20954
+ },
20955
+ postedAt: { label: "Posted", kind: "text" },
20956
+ likes: { label: "Likes", kind: "text" },
20957
+ replies: { label: "Replies", kind: "text" },
20958
+ reposts: { label: "Reposts", kind: "text" },
20959
+ views: { label: "Views", kind: "text" },
20960
+ reply: { label: "Reply", kind: "text" },
20961
+ url: { label: "Post link", kind: "text" }
20962
+ },
20963
+ output: [
20964
+ "author",
20965
+ "name",
20966
+ "followers",
20967
+ "text",
20968
+ "postedAt",
20969
+ "likes",
20970
+ "replies",
20971
+ "reposts",
20972
+ "views",
20973
+ "reply",
20974
+ "url"
20975
+ ],
20976
+ form: {
20977
+ inputMode: "text",
20978
+ mono: false,
20979
+ normalize: "trim",
20980
+ validation: "text",
20981
+ fields: [
20982
+ {
20983
+ key: "within",
20984
+ label: "Posted in",
20985
+ placeholder: "",
20986
+ maxLength: 0,
20987
+ options: [
20988
+ { value: "", label: "Any time" },
20989
+ { value: "month", label: "Past month" },
20990
+ { value: "week", label: "Past week" },
20991
+ { value: "day", label: "Past day" }
20992
+ ]
20993
+ }
20994
+ ],
20995
+ grid: false,
20996
+ gate: "tools",
20997
+ example: "catalog",
20998
+ exampleLabel: "Try an example",
20999
+ exampleValues: {},
21000
+ exampleMono: true,
21001
+ progress: ""
21002
+ },
21003
+ presentation: {
21004
+ description: "Find recent X posts where people ask for a tool, compare vendors or complain about one. Quote a phrase so every word matches together.",
21005
+ label: "Phrase or X search",
21006
+ example: '"looking for a CRM"',
21007
+ action: "Search X",
21008
+ icon: "search",
21009
+ demo: '"looking for a CRM"'
21010
+ },
21011
+ suppliers: {
21012
+ search: {
21013
+ endpoint: "anyapi.x.search.posts",
21014
+ provider: "AnyAPI",
21015
+ via: "Treg",
21016
+ role: "Recent public X posts",
21017
+ key: "search",
21018
+ cap: 5e3,
21019
+ maxCalls: 1
21020
+ }
21021
+ },
21022
+ reservationHeadroom: 0,
21023
+ badges: [{ name: "X", logo: "twitter.png" }],
21024
+ followUp: null
21025
+ })
21026
+ ),
21027
+ "reddit-search": defineTool(
21028
+ { name: "Reddit post search", credits: 1, unit: "search (up to 20 posts)", limit: 20 },
21029
+ ({ limit }) => toolDefinition({
21030
+ description: "Public Reddit posts most relevant to a query, from the past year unless a window is given, with subreddit, score and comments.",
21031
+ input: external_exports.object({ query: text(300), within: external_exports.enum(SEARCH_WINDOWS).optional(), limit }).strict(),
21032
+ row: external_exports.object({ subreddit: s, title: s, text: s, author: s, postedAt: s, score: n, comments: n, url: s }),
21033
+ preview: ["subreddit", "title", "comments"],
21034
+ noun: "posts",
21035
+ free: "Empty results are free.",
21036
+ searchWords: "subreddit subreddits threads social listening intent buyer buyers asking recommendation alternatives",
21037
+ example: { query: "best cold email tool", within: "month" },
21038
+ toolRequest: (input2) => ({
21039
+ tool: "reddit-search",
21040
+ query: input2.query,
21041
+ ...input2.within ? { within: input2.within } : {},
21042
+ ...input2.limit ? { limit: input2.limit } : {}
21043
+ }),
21044
+ web: {
21045
+ route: "reddit-post-search",
21046
+ description: "Find Reddit threads where buyers ask for recommendations or alternatives.",
21047
+ group: "social-lead-generation",
21048
+ section: "Social listening",
21049
+ order: 1
21050
+ },
21051
+ columns: {
21052
+ subreddit: {
21053
+ label: "Subreddit",
21054
+ kind: "pill",
21055
+ sample: ["r/Coldemailing", "r/EmailProspecting"],
21056
+ demo: "main"
21057
+ },
21058
+ title: {
21059
+ label: "Title",
21060
+ kind: "text",
21061
+ sample: ["Which is the best tool for cold emailing?", "What email verification tools are you using?"],
21062
+ demo: "sub"
21063
+ },
21064
+ text: { label: "Post", kind: "text", sample: ["I am using Zoho right now\u2026", "For cold outreach\u2026"] },
21065
+ author: { label: "Author", kind: "mono", sample: ["u/T\u2022\u2022\u2022", "u/C\u2022\u2022\u2022"], demo: "end" },
21066
+ postedAt: { label: "Posted", kind: "text" },
21067
+ score: { label: "Score", kind: "text" },
21068
+ comments: { label: "Comments", kind: "text" },
21069
+ url: { label: "Thread", kind: "text" }
21070
+ },
21071
+ output: ["subreddit", "title", "text", "author", "postedAt", "score", "comments", "url"],
21072
+ form: {
21073
+ inputMode: "text",
21074
+ mono: false,
21075
+ normalize: "trim",
21076
+ validation: "text",
21077
+ fields: [
21078
+ {
21079
+ key: "within",
21080
+ label: "Posted in",
21081
+ placeholder: "",
21082
+ maxLength: 0,
21083
+ options: [
21084
+ { value: "", label: "Past year" },
21085
+ { value: "month", label: "Past month" },
21086
+ { value: "week", label: "Past week" },
21087
+ { value: "day", label: "Past day" }
21088
+ ]
21089
+ }
21090
+ ],
21091
+ grid: false,
21092
+ gate: "tools",
21093
+ example: "catalog",
21094
+ exampleLabel: "Try an example",
21095
+ exampleValues: {},
21096
+ exampleMono: true,
21097
+ progress: ""
21098
+ },
21099
+ presentation: {
21100
+ description: "Find Reddit threads where buyers ask for recommendations or alternatives, ranked by relevance.",
21101
+ label: "Search query",
21102
+ example: "best cold email tool",
21103
+ action: "Search Reddit",
21104
+ icon: "search",
21105
+ demo: "best cold email tool"
21106
+ },
21107
+ suppliers: {
21108
+ search: {
21109
+ endpoint: "scrapecreators.reddit.search.posts",
21110
+ provider: "Scrape Creators",
21111
+ via: "Treg",
21112
+ role: "Public Reddit posts by relevance",
21113
+ key: "search",
21114
+ cap: 5e3,
21115
+ maxCalls: 1,
21116
+ method: "GET"
21117
+ }
21118
+ },
21119
+ reservationHeadroom: 0,
21120
+ badges: [{ name: "Reddit", logo: "reddit.png" }],
21121
+ followUp: null
21122
+ })
21123
+ ),
21124
+ "funding-signals": defineTool(
21125
+ { name: "Funding signals", credits: 1, unit: "search (up to 50 companies)", limit: 50 },
21126
+ ({ limit, maxResults }) => toolDefinition({
21127
+ description: "Companies that announced a funding round recently, from news feeds, with amount, date and source.",
21128
+ input: external_exports.object({
21129
+ region: external_exports.enum(["US", "EU", "GLOBAL"]).optional(),
21130
+ since: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe("YYYY-MM-DD"),
21131
+ ...companyFilters,
21132
+ limit
21133
+ }).strict(),
21134
+ row: external_exports.object({
21135
+ company: s,
21136
+ amount: n,
21137
+ currency: s,
21138
+ round: s,
21139
+ announced: s,
21140
+ domain: s,
21141
+ industry: s,
21142
+ employees: s,
21143
+ source: s
21144
+ }),
21145
+ preview: ["company", "domain", "amount", "announced"],
21146
+ noun: "companies",
21147
+ free: "Empty results are free.",
21148
+ example: { region: "US" },
21149
+ toolRequest: (input2) => directoryRequest(input2, {
21150
+ tool: "funding-signals",
21151
+ query: `funding ${input2.region ?? "GLOBAL"}`,
21152
+ location: input2.region ?? "",
21153
+ ...input2.since ? { since: input2.since } : {},
21154
+ limit: input2.limit ?? maxResults
21155
+ }),
21156
+ searchWords: "raised round series seed investors recently funded startup",
21157
+ web: null,
21158
+ columns: {
21159
+ company: { label: "Company", kind: "entity", sample: ["Acme", "Globex"], demo: "main" },
21160
+ amount: { label: "Amount", kind: "text", sample: ["$12M", "$40M"], demo: "sub" },
21161
+ currency: { label: "Currency", kind: "text" },
21162
+ round: { label: "Round", kind: "text" },
21163
+ announced: { label: "Announced", kind: "text", sample: ["2026-11-01", "2026-10-30"] },
21164
+ domain: { label: "Website", kind: "pill", sample: ["acme.com", "globex.com"], demo: "end" },
21165
+ industry: { label: "Industry", kind: "text" },
21166
+ employees: { label: "Employees", kind: "text" },
21167
+ source: { label: "Source", kind: "text" }
21168
+ },
21169
+ output: ["company", "amount", "announced", "domain", "industry", "employees", "source"],
21170
+ form: {
21171
+ inputMode: "url",
21172
+ mono: true,
21173
+ normalize: "trim",
21174
+ validation: "text",
21175
+ fields: [],
21176
+ grid: false,
21177
+ gate: "tools",
21178
+ example: "catalog",
21179
+ exampleLabel: "Try an example",
21180
+ exampleValues: {},
21181
+ exampleMono: true,
21182
+ progress: ""
21183
+ },
21184
+ presentation: {
21185
+ description: "Companies that announced a funding round recently, with amount, date, website and size.",
21186
+ label: "Region",
21187
+ example: "US",
21188
+ action: "Find companies",
21189
+ icon: "search",
21190
+ demo: "US"
21191
+ },
21192
+ suppliers: {
21193
+ funding: {
21194
+ endpoint: "getleadsio.companies.funding.feed",
21195
+ provider: "GetLeads",
21196
+ via: "Treg",
21197
+ role: "Funding announcements from news feeds",
21198
+ key: "funding",
21199
+ cap: 1e3,
21200
+ maxCalls: 1,
21201
+ method: "GET"
21202
+ },
21203
+ company: {
21204
+ endpoint: "quickenrich.people.search",
21205
+ provider: "QuickEnrich",
21206
+ via: "Treg",
21207
+ role: "Free company website, industry and size by exact name",
21208
+ key: "company:",
21209
+ cap: 0,
21210
+ maxCalls: 150
21211
+ }
21212
+ },
21213
+ reservationHeadroom: 0,
21214
+ badges: [],
21215
+ followUp: null
21216
+ })
21217
+ ),
21218
+ "lookalike-companies": defineTool(
21219
+ { name: "Lookalike companies", credits: 2, unit: "search", limit: 50 },
21220
+ ({ limit, maxResults }) => toolDefinition({
21221
+ description: "Companies similar to one you name, from its domain, for finding more accounts like your best customers.",
21222
+ input: external_exports.object({ company: text(100).describe("Company domain, like vercel.com"), limit }).strict(),
21223
+ row: external_exports.object({ company: s, domain: s, industry: s }),
21224
+ preview: ["company", "domain", "industry"],
21225
+ noun: "companies",
21226
+ free: "Empty results are free.",
21227
+ example: { company: "vercel.com" },
21228
+ toolRequest: (input2) => ({
21229
+ tool: "lookalike-companies",
21230
+ query: input2.company,
21231
+ limit: input2.limit ?? maxResults
21232
+ }),
21233
+ searchWords: "similar competitors like customers accounts",
21234
+ web: null,
21235
+ columns: {
21236
+ company: { label: "Company", kind: "entity", sample: ["Acme", "Globex"], demo: "main" },
21237
+ domain: { label: "Website", kind: "pill", sample: ["acme.com", "globex.com"], demo: "sub" },
21238
+ industry: { label: "Industry", kind: "text", sample: ["Software", "Software"] }
21239
+ },
21240
+ output: ["company", "domain", "industry"],
21241
+ form: {
21242
+ inputMode: "url",
21243
+ mono: true,
21244
+ normalize: "trim",
21245
+ validation: "domain",
21246
+ fields: [],
21247
+ grid: false,
21248
+ gate: "tools",
21249
+ example: "catalog",
21250
+ exampleLabel: "Try an example",
21251
+ exampleValues: {},
21252
+ exampleMono: true,
21253
+ progress: ""
21254
+ },
21255
+ presentation: {
21256
+ description: "Companies similar to one you name, for finding more accounts like your best customers.",
21257
+ label: "Company domain",
21258
+ example: "vercel.com",
21259
+ action: "Find similar companies",
21260
+ icon: "search",
21261
+ demo: "vercel.com"
21262
+ },
21263
+ suppliers: {
21264
+ similar: {
21265
+ endpoint: "tomba.companies.similar",
21266
+ provider: "Tomba",
21267
+ via: "Treg",
21268
+ role: "Similar companies from a seed domain",
21269
+ key: "similar",
21270
+ cap: 1e4,
21271
+ maxCalls: 1,
21272
+ method: "GET"
21273
+ }
21274
+ },
21275
+ reservationHeadroom: 0,
21276
+ badges: [],
21277
+ followUp: null
21278
+ })
21279
+ ),
21280
+ "post-engagers": defineTool(
21281
+ { name: "LinkedIn post engagers", credits: 1, unit: "post (up to 100 people)", limit: 100 },
21282
+ ({ limit, maxResults }) => toolDefinition({
21283
+ title: "Post engagers",
21284
+ description: "Who commented on or reacted to one post URL; a competitor's post finds warm leads.",
21285
+ input: external_exports.object({ post: text(500).describe("LinkedIn post URL"), page: pageField, limit }).strict(),
21286
+ row: external_exports.object({ name: s, headline: s, engagement: s, comment: s, url: s }),
21287
+ preview: ["name", "headline", "engagement"],
21288
+ noun: "people",
21289
+ free: "Empty results are free.",
21290
+ example: { post: "https://www.linkedin.com/posts/williamhgates_example-activity-7503320303024926720-1t50" },
21291
+ toolRequest: (input2) => ({
21292
+ tool: "post-engagers",
21293
+ query: input2.post,
21294
+ ...input2.page ? { page: input2.page } : {},
21295
+ limit: input2.limit ?? maxResults
21296
+ }),
21297
+ searchWords: "commented reacted liked warm competitor influencer",
21298
+ web: null,
21299
+ columns: {
21300
+ name: { label: "Name", kind: "entity", sample: ["A\u2022\u2022\u2022 L\u2022\u2022\u2022", "M\u2022\u2022\u2022 K\u2022\u2022\u2022"], demo: "main" },
21301
+ headline: { label: "Headline", kind: "text", sample: ["VP Sales at Stripe", "Founder"], demo: "sub" },
21302
+ engagement: { label: "Engagement", kind: "pill", sample: ["commented", "like"] },
21303
+ comment: { label: "Comment", kind: "text", sample: ["", ""], demo: "end" },
21304
+ url: { label: "LinkedIn profile", kind: "text" }
21305
+ },
21306
+ output: ["name", "headline", "engagement", "comment", "url"],
21307
+ form: {
21308
+ inputMode: "url",
21309
+ mono: true,
21310
+ normalize: "trim",
21311
+ validation: "linkedin-post",
21312
+ fields: [],
21313
+ grid: false,
21314
+ gate: "tools",
21315
+ example: "catalog",
21316
+ exampleLabel: "Try an example",
21317
+ exampleValues: {},
21318
+ exampleMono: true,
21319
+ progress: ""
21320
+ },
21321
+ presentation: {
21322
+ description: "People who commented on or reacted to a public LinkedIn post, with headline and profile.",
21323
+ label: "LinkedIn post URL",
21324
+ example: "https://www.linkedin.com/posts/example-activity-1",
21325
+ action: "Find people",
21326
+ icon: "social",
21327
+ demo: "https://www.linkedin.com/posts/example-activity-1"
21328
+ },
21329
+ suppliers: {
21330
+ engagers: {
21331
+ endpoint: "fetchinio.linkedin.post.engagement",
21332
+ provider: "Fetchin",
21333
+ via: "Treg",
21334
+ role: "Comments and reactions on a LinkedIn post",
21335
+ key: "engagers",
21336
+ cap: 3e3,
21337
+ maxCalls: 1,
21338
+ method: "GET"
21339
+ }
21340
+ },
21341
+ reservationHeadroom: 0,
21342
+ badges: [],
21343
+ followUp: null
21344
+ })
21345
+ )
21346
+ };
21347
+
21348
+ // ../contracts/src/tools.ts
21349
+ var TOOL_CATALOG = Object.fromEntries(Object.entries(TOOL_DEFINITIONS).map(([id, { name, credits, unit, limit }]) => [id, { name, credits, unit, limit }]));
21350
+ var toolIdSchema = external_exports.enum(Object.keys(TOOL_CATALOG));
21351
+ var toolRequestSchema = external_exports.object({
21352
+ tool: toolIdSchema,
21353
+ ...toolRequestFields.shape
21354
+ }).strict().superRefine((v, c) => {
21355
+ const reject = (message) => c.addIssue({ code: "custom", path: ["query"], message });
21356
+ if (v.careerBoard && !/^https:\/\/(boards\.greenhouse\.io|jobs\.lever\.co)\/[a-zA-Z0-9_-]+\/?$/.test(v.careerBoard)) reject("Use a public Greenhouse or Lever company board URL.");
21357
+ const form2 = TOOL_DEFINITIONS[v.tool].form;
21358
+ const validators = {
21359
+ text: () => true,
21360
+ website: () => publicWebsite(websiteUrl(v.query)),
21361
+ domain: () => publicWebsite(`https://${v.query.replace(/^https?:\/\//, "").replace(/\/$/, "")}`),
21362
+ email: () => external_exports.string().email().safeParse(v.query).success,
21363
+ instagram: () => INSTAGRAM_HANDLE.test(v.query),
21364
+ "linkedin-post": () => /^https:\/\/([a-z]{2,3}\.)?linkedin\.com\/(posts|feed\/update)\//.test(v.query),
21365
+ "linkedin-profile": () => isToolProfileUrl(v.query)
21366
+ };
21367
+ const messages = {
21368
+ text: "Check your input.",
21369
+ website: "Enter a company website, like vercel.com.",
21370
+ domain: "Enter a public company domain.",
21371
+ email: "Enter an email address.",
21372
+ instagram: "Enter an Instagram username, like gymshark.",
21373
+ "linkedin-post": "Enter a LinkedIn post URL.",
21374
+ "linkedin-profile": "Enter a LinkedIn profile URL."
21375
+ };
21376
+ const afterWindow = form2.validation === "linkedin-profile" || form2.validation === "linkedin-post";
21377
+ if (!afterWindow && !validators[form2.validation]()) reject(messages[form2.validation]);
21378
+ for (const field of form2.fields) if (field.required && !v[field.key]) c.addIssue({ code: "custom", path: [field.key === "location" ? "query" : field.key], message: field.requiredMessage });
21379
+ if (v.within && !form2.fields.some((field) => field.key === "within")) c.addIssue({ code: "custom", path: ["within"], message: "Only post searches take a time window." });
21380
+ if (afterWindow && !validators[form2.validation]()) reject(messages[form2.validation]);
19524
21381
  });
19525
- function canonicalProfileSlug(slug) {
19526
- return /^AC[ow]AA/.test(slug) ? slug : slug.toLowerCase();
19527
- }
19528
- function linkedinProfileUrl(value) {
19529
- const trimmed = value.trim();
19530
- if (/^[A-Za-z0-9][A-Za-z0-9_%-]{0,99}$/.test(trimmed)) return `https://www.linkedin.com/in/${canonicalProfileSlug(trimmed)}`;
19531
- const match = /^(?:https?:\/\/)?(?:www\.)?linkedin\.com\/in\/([A-Za-z0-9_%-]{1,100})\/?(?:[?#].*)?$/i.exec(trimmed);
19532
- return match ? `https://www.linkedin.com/in/${canonicalProfileSlug(match[1])}` : trimmed;
19533
- }
19534
- function capability(definition) {
19535
- return definition;
19536
- }
19537
- var CAPABILITIES = {
19538
- "seo-aeo-audit": capability({
19539
- title: "SEO/AEO audit",
19540
- description: "RankAI website audit for search engine and answer engine optimization, with a report URL when complete.",
19541
- input: external_exports.object({ url: text(300) }).strict(),
19542
- row: external_exports.object({ url: s, auditId: s, status: s, reportUrl: s }),
19543
- preview: ["url", "status", "reportUrl"],
19544
- noun: "audits",
19545
- price: toolPrice("seo-aeo-audit", "Failed audits and empty results are free."),
19546
- example: { url: "example.com" },
19547
- toolRequest: (input2) => ({ tool: "seo-aeo-audit", query: input2.url })
19548
- }),
19549
- "email-finder": capability({
19550
- title: "Email finder",
19551
- description: "Work email for each LinkedIn profile, checked before it is returned.",
19552
- input: external_exports.object({ people: external_exports.array(text(300)).min(1).max(100) }).strict(),
19553
- row: external_exports.object({ name: s.nullable(), title: s.nullable(), email: s.nullable(), verdict: s.nullable(), url: s, status: s }),
19554
- preview: ["name", "email", "verdict"],
19555
- noun: "contacts",
19556
- price: { credits: 1, unit: "email found", basis: "result", free: "Misses and profiles you already paid for are free." },
19557
- searchWords: "emails bulk batch list csv contact contacts enrich enrichment",
19558
- example: { people: ["https://www.linkedin.com/in/satyanadella"] }
19559
- }),
19560
- company: capability({
19561
- title: "Company enrichment",
19562
- description: "Company details from a domain: industry, size, country and about.",
19563
- input: external_exports.object({ domain: text(100) }).strict(),
19564
- row: external_exports.object({ name: s, domain: s, industry: s, employees: s, country: s, about: s, url: s }),
19565
- preview: ["name", "industry", "employees", "country"],
19566
- noun: "companies",
19567
- price: toolPrice("company"),
19568
- example: { domain: "vercel.com" },
19569
- toolRequest: (input2) => ({ tool: "company", query: input2.domain })
19570
- }),
19571
- "local-leads": capability({
19572
- title: "Local business leads",
19573
- description: "Local businesses by type and city, with address, website and listed phone.",
19574
- input: external_exports.object({ business_type: text(100), location: text(100), limit: limit("local-leads") }).strict(),
19575
- row: external_exports.object({ name: s, address: s, phone: s, website: s, rating: n, url: s }),
19576
- preview: ["name", "address", "phone", "website"],
19577
- noun: "businesses",
19578
- price: toolPrice("local-leads"),
19579
- example: { business_type: "Dentists", location: "Austin" },
19580
- toolRequest: (input2) => ({ tool: "local-leads", query: input2.business_type, location: input2.location, ...input2.limit ? { limit: input2.limit } : {} })
19581
- }),
19582
- website: capability({
19583
- title: "Website brief",
19584
- description: "Sales brief from a company website: what they do, who they sell to, products and pricing.",
19585
- input: external_exports.object({ url: text(300) }).strict(),
19586
- row: external_exports.object({ company: s, whatTheyDo: s, sellsTo: s, products: s, customers: s, pricing: s, mainCta: s, url: s, fetchedAt: s }),
19587
- preview: ["company", "whatTheyDo", "sellsTo", "pricing"],
19588
- noun: "briefs",
19589
- price: toolPrice("website"),
19590
- example: { url: "vercel.com" },
19591
- toolRequest: (input2) => ({ tool: "website", query: input2.url })
19592
- }),
19593
- icp: capability({
19594
- title: "Decision-maker finder",
19595
- description: "People at one company domain, optionally narrowed to job titles.",
19596
- input: external_exports.object({ company: text(100), titles: external_exports.array(text(60)).max(5).optional(), limit: limit("icp") }).strict(),
19597
- row: external_exports.object({ name: s, title: s, company: s, domain: s, country: s.optional(), url: s }),
19598
- preview: ["name", "title", "company"],
19599
- noun: "people",
19600
- price: toolPrice("icp"),
19601
- example: { company: "vercel.com", titles: ["CEO"] },
19602
- toolRequest: (input2) => ({ tool: "icp", query: input2.company, titles: (input2.titles ?? []).join(", "), ...input2.limit ? { limit: input2.limit } : {} })
19603
- }),
19604
- signals: capability({
19605
- title: "Hiring signals",
19606
- description: "Companies hiring for a role in the past 30 days, with website, industry and size; recruiters left out. A tool's name as the role finds companies using it.",
19607
- input: external_exports.object({ role: text(200), location: optionalText(100), company: optionalText(100), ...companyFilters, page: pageField, limit: limit("signals") }).strict(),
19608
- row: external_exports.object({ company: s, role: s, location: s, posted: s, domain: s, industry: s, employees: s, url: s }),
19609
- preview: ["company", "domain", "role", "posted"],
19610
- noun: "signals",
19611
- price: toolPrice("signals"),
19612
- example: { role: "Sales Development Representative", location: "United States" },
19613
- toolRequest: (input2) => ({ tool: "signals", query: input2.role, location: input2.location ?? "", company: input2.company ?? "", ...directoryRequest(input2), limit: input2.limit ?? TOOL_CATALOG.signals.limit })
19614
- }),
19615
- "verify-email": capability({
19616
- title: "Email verification",
19617
- description: "Mailbox check for one email address.",
19618
- input: external_exports.object({ email: text(254) }).strict(),
19619
- row: external_exports.object({ email: s, verdict: s, score: n, checkedAt: s }),
19620
- preview: ["email", "verdict", "score"],
19621
- noun: "verifications",
19622
- price: toolPrice("verify-email", "Unknown, webmail and disposable results are free."),
19623
- example: { email: "jane@example.com" },
19624
- toolRequest: (input2) => ({ tool: "verify-email", query: input2.email })
19625
- }),
19626
- "phone-pilot": capability({
19627
- title: "Mobile enrichment",
19628
- description: "Mobile number for one LinkedIn profile you have permission to enrich.",
19629
- input: external_exports.object({ profile: text(300) }).strict(),
19630
- row: external_exports.object({ phone: s, type: s, country: s, url: s }),
19631
- preview: ["phone", "type", "country"],
19632
- noun: "phones",
19633
- price: toolPrice("phone-pilot", "No number found is free."),
19634
- example: { profile: "https://www.linkedin.com/in/satyanadella" },
19635
- toolRequest: (input2) => ({ tool: "phone-pilot", query: linkedinProfileUrl(input2.profile) })
19636
- }),
19637
- "people-search": capability({
19638
- title: "People search",
19639
- description: "People by job titles, where they live, and company industry, size or description. Up to 100 per page.",
19640
- input: external_exports.object({ titles: external_exports.array(text(60)).min(1).max(5), location: optionalText(100), ...companyFilters, keywords: keywordsField, page: pageField, limit: limit("people-search") }).strict(),
19641
- row: external_exports.object({ name: s, title: s, company: s, domain: s, industry: s, employees: s, location: s, url: s }),
19642
- preview: ["name", "title", "company", "location"],
19643
- noun: "people",
19644
- price: toolPrice("people-search"),
19645
- example: { titles: ["VP Sales"], location: "United States", industries: ["SaaS"], company_sizes: ["20-99"] },
19646
- toolRequest: (input2) => ({ tool: "people-search", query: input2.titles.join(", "), location: input2.location ?? "", ...directoryRequest(input2), limit: input2.limit ?? TOOL_CATALOG["people-search"].limit })
19647
- }),
19648
- "funding-signals": capability({
19649
- title: "Funding signals",
19650
- description: "Companies that announced a funding round recently, from news feeds, with amount, date and source.",
19651
- input: external_exports.object({ region: external_exports.enum(["US", "EU", "GLOBAL"]).optional(), since: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe("YYYY-MM-DD"), ...companyFilters, limit: limit("funding-signals") }).strict(),
19652
- row: external_exports.object({ company: s, amount: n, currency: s, round: s, announced: s, domain: s, industry: s, employees: s, source: s }),
19653
- preview: ["company", "domain", "amount", "announced"],
19654
- noun: "companies",
19655
- price: toolPrice("funding-signals"),
19656
- example: { region: "US" },
19657
- toolRequest: (input2) => ({ tool: "funding-signals", query: `funding ${input2.region ?? "GLOBAL"}`, location: input2.region ?? "", ...input2.since ? { since: input2.since } : {}, ...directoryRequest(input2), limit: input2.limit ?? TOOL_CATALOG["funding-signals"].limit }),
19658
- searchWords: "raised round series seed investors recently funded startup"
19659
- }),
19660
- "lookalike-companies": capability({
19661
- title: "Lookalike companies",
19662
- description: "Companies similar to one you name, from its domain, for finding more accounts like your best customers.",
19663
- input: external_exports.object({ company: text(100).describe("Company domain, like vercel.com"), limit: limit("lookalike-companies") }).strict(),
19664
- row: external_exports.object({ company: s, domain: s, industry: s }),
19665
- preview: ["company", "domain", "industry"],
19666
- noun: "companies",
19667
- price: toolPrice("lookalike-companies"),
19668
- example: { company: "vercel.com" },
19669
- toolRequest: (input2) => ({ tool: "lookalike-companies", query: input2.company, limit: input2.limit ?? TOOL_CATALOG["lookalike-companies"].limit }),
19670
- searchWords: "similar competitors like customers accounts"
19671
- }),
19672
- "post-engagers": capability({
19673
- title: "Post engagers",
19674
- description: "Who commented on or reacted to one post URL; a competitor's post finds warm leads.",
19675
- input: external_exports.object({ post: text(500).describe("LinkedIn post URL"), page: pageField, limit: limit("post-engagers") }).strict(),
19676
- row: external_exports.object({ name: s, headline: s, engagement: s, comment: s, url: s }),
19677
- preview: ["name", "headline", "engagement"],
19678
- noun: "people",
19679
- price: toolPrice("post-engagers"),
19680
- example: { post: "https://www.linkedin.com/posts/williamhgates_example-activity-7503320303024926720-1t50" },
19681
- toolRequest: (input2) => ({ tool: "post-engagers", query: input2.post, ...input2.page ? { page: input2.page } : {}, limit: input2.limit ?? TOOL_CATALOG["post-engagers"].limit }),
19682
- searchWords: "commented reacted liked warm competitor influencer"
19683
- }),
19684
- "google-search": capability({
19685
- title: "Google search",
19686
- description: "Top Google organic results for a query (United States, English).",
19687
- input: external_exports.object({ query: text(500), limit: limit("google-search") }).strict(),
19688
- row: external_exports.object({ position: n, title: s, domain: s, snippet: s, url: s }),
19689
- preview: ["position", "title", "domain"],
19690
- noun: "results",
19691
- price: toolPrice("google-search"),
19692
- example: { query: "best crm for startups" },
19693
- toolRequest: (input2) => ({ tool: "google-search", query: input2.query, ...input2.limit ? { limit: input2.limit } : {} })
19694
- }),
19695
- "linkedin-profile": capability({
19696
- title: "LinkedIn profile",
19697
- description: "Public LinkedIn profile: headline, current role, company, location and about. One profile or up to 100 people.",
19698
- input: external_exports.object({ profile: text(300).optional(), people: batchPeople }).strict(),
19699
- row: external_exports.object({ name: s, headline: s, role: s, company: s, location: s, followers: n, about: s, companyPage: s, url: s }),
19700
- preview: ["name", "role", "company", "location"],
19701
- noun: "profiles",
19702
- price: toolPrice("linkedin-profile", "Profiles not found are free."),
19703
- searchWords: "current job title employer moved changed change changes verify bulk batch list",
19704
- example: { profile: "https://www.linkedin.com/in/williamhgates" },
19705
- toolRequest: (input2) => ({ tool: "linkedin-profile", query: linkedinProfileUrl(input2.profile ?? "") }),
19706
- batch: true
19707
- }),
19708
- "linkedin-activity": capability({
19709
- title: "LinkedIn activity",
19710
- description: "Recent public LinkedIn posts with exact dates: last post, posts in 90 and 365 days, and posts on topics you name. One profile or up to 100 people.",
19711
- input: external_exports.object({ profile: text(300).optional(), people: batchPeople, topics: external_exports.array(text(40)).max(10).optional().describe("Words to look for in the past year's posts, like automation") }).strict(),
19712
- row: external_exports.object({ name: s, headline: s, lastPostAt: s, posts90d: external_exports.number(), posts365d: external_exports.number(), topics: s, topicPosts: n, post: s, postAt: s, postKind: s, postUrl: s, url: s }),
19713
- preview: ["name", "lastPostAt", "posts90d", "topicPosts"],
19714
- noun: "profiles",
19715
- price: toolPrice("linkedin-activity", "Profiles with no public posts are free."),
19716
- searchWords: "posting active activity talk talks talking mentions mentioned engagement social signal signals intent bulk batch list",
19717
- example: { profile: "https://www.linkedin.com/in/williamhgates", topics: ["climate"] },
19718
- // Commas would split a topic, so each is kept whole by dropping them.
19719
- toolRequest: (input2) => ({ tool: "linkedin-activity", query: linkedinProfileUrl(input2.profile ?? ""), ...input2.topics?.length ? { keywords: input2.topics.map((t) => t.replace(/,/g, " ").trim()).join(", ") } : {} }),
19720
- batch: true
19721
- }),
19722
- "profile-finder": capability({
19723
- title: "Find LinkedIn profile",
19724
- description: "A person's LinkedIn profile from their name and company, checked against both. One person or up to 100 people.",
19725
- input: external_exports.object({
19726
- name: text(100).optional().describe("Full name, like Pedro Reis"),
19727
- company: text(100).optional().describe("Company name or domain, like Adyen"),
19728
- people: external_exports.array(external_exports.object({ name: text(100), company: text(100) }).strict()).min(1).max(MAX_BATCH_PEOPLE).optional().describe(`Up to ${MAX_BATCH_PEOPLE} {name, company} pairs, instead of name and company`)
19729
- }).strict(),
19730
- row: external_exports.object({ name: s, title: s, company: s, location: s, url: s }),
19731
- preview: ["name", "title", "company", "url"],
19732
- noun: "profiles",
19733
- price: toolPrice("profile-finder", "People not found are free."),
19734
- example: { name: "Pedro Reis", company: "Adyen" },
19735
- toolRequest: (input2) => ({ tool: "profile-finder", query: input2.name ?? "", company: input2.company ?? "" }),
19736
- batch: true,
19737
- searchWords: "linkedin url name names person lookup resolve match who bulk batch list"
19738
- }),
19739
- "page-content": capability({
19740
- title: "Web page content",
19741
- description: "Readable text of one public web page.",
19742
- input: external_exports.object({ url: text(300) }).strict(),
19743
- row: external_exports.object({ title: s, url: s, words: external_exports.number(), content: s }),
19744
- preview: ["title", "url", "words"],
19745
- noun: "pages",
19746
- price: toolPrice("page-content"),
19747
- example: { url: "vercel.com/pricing" },
19748
- toolRequest: (input2) => ({ tool: "page-content", query: input2.url })
19749
- }),
19750
- "instagram-profile": capability({
19751
- title: "Instagram profile",
19752
- description: "Public Instagram profile with followers, bio, website and the business email or phone it shows.",
19753
- input: external_exports.object({ profile: text(200).describe("Instagram username, @handle or profile URL") }).strict(),
19754
- row: external_exports.object({ handle: s, name: s, bio: s, followers: n, following: n, business: external_exports.boolean(), verified: external_exports.boolean(), website: s, email: s, phone: s, url: s }),
19755
- preview: ["handle", "followers", "email", "website"],
19756
- noun: "profiles",
19757
- price: toolPrice("instagram-profile", "Private and missing accounts are free."),
19758
- searchWords: "insta ig creator creators influencer influencers brand social contact email phone followers",
19759
- example: { profile: "gymshark" },
19760
- toolRequest: (input2) => ({ tool: "instagram-profile", query: instagramHandle(input2.profile) })
19761
- }),
19762
- "x-search": capability({
19763
- title: "X post search",
19764
- description: "Recent public X (Twitter) posts matching a phrase, newest first, with author and engagement. Every bare word must appear; quote a phrase or use OR.",
19765
- input: external_exports.object({ query: text(300).describe('Phrase or X search syntax, like "looking for a CRM"'), within: external_exports.enum(SEARCH_WINDOWS).optional(), limit: limit("x-search") }).strict(),
19766
- row: external_exports.object({ author: s, name: s, followers: n, text: s, postedAt: s, likes: n, replies: n, reposts: n, views: n, reply: external_exports.boolean(), url: s }),
19767
- preview: ["author", "text", "postedAt"],
19768
- noun: "posts",
19769
- price: toolPrice("x-search"),
19770
- searchWords: "twitter tweets tweet social listening intent buyer buyers asking recommendation mentions",
19771
- example: { query: '"looking for a CRM"', within: "week" },
19772
- toolRequest: (input2) => ({ tool: "x-search", query: input2.query, ...input2.within ? { within: input2.within } : {}, ...input2.limit ? { limit: input2.limit } : {} })
21382
+ var toolResultSchema = external_exports.object({
21383
+ rows: external_exports.array(external_exports.record(external_exports.string(), external_exports.union([external_exports.string().max(1e5), external_exports.number(), external_exports.boolean(), external_exports.null()]))).max(100),
21384
+ notes: external_exports.array(external_exports.string().max(500)).max(10),
21385
+ /** There are more results: the next page and, when the source says, how many match in all. */
21386
+ more: external_exports.object({ page: external_exports.number().int().positive(), total: external_exports.number().int().nonnegative().optional() }).optional(),
21387
+ /** Companies dropped before the rows, by why. */
21388
+ left: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).optional()
21389
+ });
21390
+ var TOOL_RUN_STATUSES = ["queued", "running", "completed", "not_found", "error", "reconciliation_needed"];
21391
+ var TOOL_RUN_TRANSITIONS = {
21392
+ queued: ["running", "completed", "not_found", "error", "reconciliation_needed"],
21393
+ running: ["completed", "not_found", "error", "reconciliation_needed"],
21394
+ completed: [],
21395
+ not_found: [],
21396
+ error: [],
21397
+ reconciliation_needed: ["error"]
21398
+ };
21399
+ var toolRunLifecycle = defineLifecycle({ states: TOOL_RUN_STATUSES, transitions: TOOL_RUN_TRANSITIONS });
21400
+ var TOOL_CALL_STATUSES = ["submitted", "completed", "expired"];
21401
+ var TOOL_CALL_TRANSITIONS = {
21402
+ submitted: ["completed", "expired"],
21403
+ completed: [],
21404
+ expired: []
21405
+ };
21406
+ var toolCallLifecycle = defineLifecycle({ states: TOOL_CALL_STATUSES, transitions: TOOL_CALL_TRANSITIONS });
21407
+ var toolRunSchema = external_exports.object({
21408
+ id: external_exports.string(),
21409
+ tool: toolIdSchema,
21410
+ status: external_exports.enum(TOOL_RUN_STATUSES),
21411
+ input: toolRequestSchema,
21412
+ result: toolResultSchema.nullable(),
21413
+ creditsCharged: external_exports.number().int().nonnegative(),
21414
+ creditsReserved: external_exports.number().int().nonnegative(),
21415
+ createdAt: external_exports.number(),
21416
+ updatedAt: external_exports.number()
21417
+ });
21418
+ var toolRunResponseSchema = external_exports.object({ run: toolRunSchema, credits: external_exports.number().int().nonnegative() });
21419
+ var toolRunsResponseSchema = external_exports.object({ runs: external_exports.array(toolRunSchema), credits: external_exports.number().int().nonnegative() });
21420
+
21421
+ // ../contracts/src/stored-tool-request.ts
21422
+ var storedToolRequestV1Schema = external_exports.looseObject({
21423
+ tool: toolIdSchema,
21424
+ query: external_exports.string().catch("").default(""),
21425
+ company: external_exports.string().catch("").default(""),
21426
+ location: external_exports.string().catch("").default(""),
21427
+ titles: external_exports.string().catch("").default(""),
21428
+ keywords: external_exports.string().optional().catch(void 0)
21429
+ });
21430
+
21431
+ // ../contracts/src/plans.ts
21432
+ var CREDIT_PLANS = [
21433
+ {
21434
+ id: "starter",
21435
+ name: "Starter",
21436
+ monthlyCredits: 2e3,
21437
+ unlimited: false,
21438
+ prices: {
21439
+ monthly: { usd: 30, url: "https://buy.stripe.com/8x214o9aobNr7Tx85v5gc02", linkId: "plink_1UVzDYLFFDNJNkHJJ4fWmieL" },
21440
+ annual: { usd: 300, url: "https://buy.stripe.com/00w5kE4U84kZflZfxX5gc03", linkId: "plink_1UVzFmLFFDNJNkHJbQW9Dy7X" }
21441
+ }
21442
+ },
21443
+ {
21444
+ id: "growth",
21445
+ name: "Growth",
21446
+ monthlyCredits: 4500,
21447
+ unlimited: false,
21448
+ prices: {
21449
+ monthly: { usd: 60, url: "https://buy.stripe.com/3cI28s4U818N6PtbhH5gc04", linkId: "plink_1UVzGELFFDNJNkHJnlfjOxwk" },
21450
+ annual: { usd: 600, url: "https://buy.stripe.com/14A4gAbiw6t78XBadD5gc05", linkId: "plink_1UVzGgLFFDNJNkHJtvftWZKw" }
21451
+ }
21452
+ },
21453
+ {
21454
+ id: "unlimited",
21455
+ name: "Unlimited",
21456
+ monthlyCredits: 1e4,
21457
+ unlimited: true,
21458
+ prices: {
21459
+ monthly: { usd: 129, url: "https://buy.stripe.com/3cI5kEbiw4kZddRetT5gc08", linkId: "plink_1UVzxYLFFDNJNkHJoG37CnPv" },
21460
+ annual: { usd: 1290, url: "https://buy.stripe.com/00w14o3Q4eZDehV4Tj5gc09", linkId: "plink_1UVzyVLFFDNJNkHJbNAsT6il" }
21461
+ }
21462
+ }
21463
+ ];
21464
+
21465
+ // ../contracts/src/campaigns.ts
21466
+ var CAMPAIGN_STATUSES = ["open", "ended", "full"];
21467
+ var campaignStatusSchema = external_exports.enum(CAMPAIGN_STATUSES);
21468
+ var CAMPAIGN_LIMITS = {
21469
+ code: { min: 2, max: 24 },
21470
+ name: { min: 2, max: 80 },
21471
+ credits: { min: 1, max: 1e4 },
21472
+ maxClaims: { min: 1, max: 1e6 }
21473
+ };
21474
+ var MAX_CAMPAIGN_CREDITS = CAMPAIGN_LIMITS.credits.max;
21475
+ var codePattern = `[A-Z0-9][A-Z0-9-]{${CAMPAIGN_LIMITS.code.min - 1},${CAMPAIGN_LIMITS.code.max - 1}}`;
21476
+ var CAMPAIGN_CODE_INPUT_PATTERN = codePattern.replaceAll("A-Z", "A-Za-z");
21477
+ var campaignCodeSchema = external_exports.string().regex(new RegExp(`^${codePattern}$`));
21478
+ function normalizeCampaignCode(raw) {
21479
+ const parsed = campaignCodeSchema.safeParse((raw ?? "").trim().toUpperCase());
21480
+ return parsed.success ? parsed.data : null;
21481
+ }
21482
+ var newCampaignSchema = external_exports.object({
21483
+ code: external_exports.string(),
21484
+ name: external_exports.string().trim().min(CAMPAIGN_LIMITS.name.min).max(CAMPAIGN_LIMITS.name.max),
21485
+ credits: external_exports.number().int().min(CAMPAIGN_LIMITS.credits.min).max(CAMPAIGN_LIMITS.credits.max),
21486
+ maxClaims: external_exports.number().int().min(CAMPAIGN_LIMITS.maxClaims.min).max(CAMPAIGN_LIMITS.maxClaims.max).nullable().optional(),
21487
+ endsAt: external_exports.iso.datetime({ offset: true }).nullable().optional()
21488
+ }).transform((value, ctx) => {
21489
+ const code = normalizeCampaignCode(value.code);
21490
+ if (!code) {
21491
+ ctx.addIssue({ code: "custom", path: ["code"], message: "Invalid campaign code" });
21492
+ return external_exports.NEVER;
21493
+ }
21494
+ return { ...value, code };
21495
+ });
21496
+ var campaignClaimSchema = external_exports.object({ credits: external_exports.number(), claimedAt: external_exports.string() });
21497
+ var eventOfferSchema = external_exports.object({
21498
+ campaign: external_exports.object({ code: campaignCodeSchema, name: external_exports.string(), credits: external_exports.number(), status: campaignStatusSchema }),
21499
+ claim: campaignClaimSchema.nullable()
21500
+ });
21501
+ var claimOutcomeSchema = external_exports.object({
21502
+ status: external_exports.enum(["claimed", "already_claimed"]),
21503
+ claim: campaignClaimSchema,
21504
+ credits: external_exports.object({ remaining: external_exports.number() })
21505
+ });
21506
+ var leaderboardSchema = external_exports.object({
21507
+ entries: external_exports.array(external_exports.object({ rank: external_exports.number(), name: external_exports.string(), credits: external_exports.number(), you: external_exports.boolean() })),
21508
+ /** Null without a claim; rank null until the claimant spends credits. */
21509
+ you: external_exports.object({ rank: external_exports.number().nullable(), credits: external_exports.number() }).nullable()
21510
+ });
21511
+
21512
+ // ../contracts/src/product-policy.ts
21513
+ var CREDIT_ATOMIC = 1e4;
21514
+ var EMAIL_LOOKUP_CREDITS = 1;
21515
+ var EMAIL_LOOKUP_ATOMIC = EMAIL_LOOKUP_CREDITS * CREDIT_ATOMIC;
21516
+
21517
+ // ../contracts/src/email-finder.ts
21518
+ var text2 = (max) => external_exports.string().trim().min(1).max(max);
21519
+ var s2 = external_exports.string();
21520
+ var EMAIL_SUPPLIER_STEPS = [
21521
+ {
21522
+ service: { endpoint: "treg_quickenrich", provider: "QuickEnrich", via: "Treg", role: "Work email, first try" },
21523
+ marketplace: "quickenrich",
21524
+ endpoint: "quickenrich.people.email.find",
21525
+ cap: 4834,
21526
+ method: "GET"
21527
+ },
21528
+ {
21529
+ service: { endpoint: "treg_blitz", provider: "Blitz", via: "Treg", role: "Work email" },
21530
+ marketplace: "blitz",
21531
+ endpoint: "blitzapi.people.email.find",
21532
+ cap: 495,
21533
+ method: "POST"
21534
+ },
21535
+ {
21536
+ service: { endpoint: "treg_aiark", provider: "AI Ark", via: "Treg", role: "Work email" },
21537
+ marketplace: "aiark",
21538
+ endpoint: "aiark.people.email.find",
21539
+ cap: 5267,
21540
+ method: "POST"
21541
+ },
21542
+ {
21543
+ service: { endpoint: "apollo_x402", provider: "Apollo (Orthogonal)", via: "Direct", role: "Work email over x402" }
21544
+ },
21545
+ {
21546
+ service: { endpoint: "treg_findymail", provider: "Findymail", via: "Treg", role: "Work email, last try" },
21547
+ marketplace: "findymail",
21548
+ endpoint: "findymail.search.business-profile",
21549
+ cap: 19800,
21550
+ method: "POST"
21551
+ }
21552
+ ];
21553
+ var EMAIL_VERIFICATION_STEP = {
21554
+ ...TOOL_DEFINITIONS["verify-email"].suppliers.verification,
21555
+ service: {
21556
+ endpoint: "treg_verify",
21557
+ provider: "Treg verify waterfall (cheapest verifier first)",
21558
+ via: "Treg",
21559
+ role: "Mailbox check for each new hit"
21560
+ }
21561
+ };
21562
+ var EMAIL_FINDER_DEFINITION = {
21563
+ title: "Email finder",
21564
+ description: "Work email for each LinkedIn profile, checked before it is returned.",
21565
+ input: external_exports.object({ people: external_exports.array(text2(300)).min(1).max(MAX_BATCH_PEOPLE) }).strict(),
21566
+ row: external_exports.object({
21567
+ name: s2.nullable(),
21568
+ title: s2.nullable(),
21569
+ email: s2.nullable(),
21570
+ verdict: s2.nullable(),
21571
+ url: s2,
21572
+ status: s2
19773
21573
  }),
19774
- "reddit-search": capability({
19775
- title: "Reddit post search",
19776
- description: "Public Reddit posts most relevant to a query, from the past year unless a window is given, with subreddit, score and comments.",
19777
- input: external_exports.object({ query: text(300), within: external_exports.enum(SEARCH_WINDOWS).optional(), limit: limit("reddit-search") }).strict(),
19778
- row: external_exports.object({ subreddit: s, title: s, text: s, author: s, postedAt: s, score: n, comments: n, url: s }),
19779
- preview: ["subreddit", "title", "comments"],
19780
- noun: "posts",
19781
- price: toolPrice("reddit-search"),
19782
- searchWords: "subreddit subreddits threads social listening intent buyer buyers asking recommendation alternatives",
19783
- example: { query: "best cold email tool", within: "month" },
19784
- toolRequest: (input2) => ({ tool: "reddit-search", query: input2.query, ...input2.within ? { within: input2.within } : {}, ...input2.limit ? { limit: input2.limit } : {} })
19785
- })
21574
+ preview: ["name", "email", "verdict"],
21575
+ noun: "contacts",
21576
+ price: {
21577
+ credits: EMAIL_LOOKUP_CREDITS,
21578
+ unit: "email found",
21579
+ basis: "result",
21580
+ free: "Misses and profiles you already paid for are free."
21581
+ },
21582
+ searchWords: "emails bulk batch list csv contact contacts enrich enrichment",
21583
+ example: { people: ["https://www.linkedin.com/in/satyanadella"] },
21584
+ steps: EMAIL_SUPPLIER_STEPS,
21585
+ verification: EMAIL_VERIFICATION_STEP,
21586
+ services: [...EMAIL_SUPPLIER_STEPS.map((step) => step.service), EMAIL_VERIFICATION_STEP.service],
21587
+ badges: [
21588
+ { name: "QuickEnrich", logo: "quickenrich.png" },
21589
+ { name: "Blitz", logo: "blitz.png" },
21590
+ { name: "Apollo", logo: "apollo.svg" },
21591
+ { name: "Findymail", logo: "findymail.png" }
21592
+ ]
21593
+ };
21594
+
21595
+ // ../contracts/src/capabilities.ts
21596
+ var text3 = (max) => external_exports.string().trim().min(1).max(max);
21597
+ var companyFilters2 = {
21598
+ industries: external_exports.array(text3(100)).min(1).max(10).optional().describe("Like SaaS"),
21599
+ company_sizes: external_exports.array(text3(20)).min(1).max(9).optional().describe("Like 20-99")
21600
+ };
21601
+ var keywordsField2 = external_exports.array(text3(60)).min(1).max(10).optional().describe("In company description");
21602
+ var pageField2 = external_exports.number().int().min(1).max(100).optional();
21603
+ var CAPABILITIES = {
21604
+ "seo-aeo-audit": TOOL_DEFINITIONS["seo-aeo-audit"],
21605
+ "email-finder": EMAIL_FINDER_DEFINITION,
21606
+ company: TOOL_DEFINITIONS["company"],
21607
+ "local-leads": TOOL_DEFINITIONS["local-leads"],
21608
+ website: TOOL_DEFINITIONS["website"],
21609
+ icp: TOOL_DEFINITIONS["icp"],
21610
+ signals: TOOL_DEFINITIONS["signals"],
21611
+ "verify-email": TOOL_DEFINITIONS["verify-email"],
21612
+ "phone-pilot": TOOL_DEFINITIONS["phone-pilot"],
21613
+ "people-search": TOOL_DEFINITIONS["people-search"],
21614
+ "funding-signals": TOOL_DEFINITIONS["funding-signals"],
21615
+ "lookalike-companies": TOOL_DEFINITIONS["lookalike-companies"],
21616
+ "post-engagers": TOOL_DEFINITIONS["post-engagers"],
21617
+ "google-search": TOOL_DEFINITIONS["google-search"],
21618
+ "linkedin-profile": TOOL_DEFINITIONS["linkedin-profile"],
21619
+ "linkedin-activity": TOOL_DEFINITIONS["linkedin-activity"],
21620
+ "profile-finder": TOOL_DEFINITIONS["profile-finder"],
21621
+ "page-content": TOOL_DEFINITIONS["page-content"],
21622
+ "instagram-profile": TOOL_DEFINITIONS["instagram-profile"],
21623
+ "x-search": TOOL_DEFINITIONS["x-search"],
21624
+ "reddit-search": TOOL_DEFINITIONS["reddit-search"]
19786
21625
  };
19787
21626
  var CAPABILITY_IDS = Object.keys(CAPABILITIES);
19788
21627
  var capabilityIdSchema = external_exports.enum(CAPABILITY_IDS);
@@ -19794,47 +21633,47 @@ var paidArgs = {
19794
21633
  };
19795
21634
  var price = (id) => TOOL_CATALOG[id].credits;
19796
21635
  var findContactsInput = external_exports.object({
19797
- people: external_exports.array(text(300)).min(1).max(100).optional().describe("LinkedIn profile URLs or handles"),
21636
+ people: external_exports.array(text3(300)).min(1).max(MAX_BATCH_PEOPLE).optional().describe("LinkedIn profile URLs or handles"),
19798
21637
  run_id: external_exports.string().max(64).optional().describe("Use the people from a gtm_build_list run"),
19799
- named: external_exports.array(external_exports.object({ name: external_exports.string().pipe(text(100)), company: external_exports.string().pipe(text(100)) }).strict()).min(1).max(100).optional().describe("{name, company} pairs, instead of people"),
21638
+ named: external_exports.array(external_exports.object({ name: external_exports.string().pipe(text3(100)), company: external_exports.string().pipe(text3(100)) }).strict()).min(1).max(MAX_BATCH_PEOPLE).optional().describe("{name, company} pairs, instead of people"),
19800
21639
  find: external_exports.array(external_exports.enum(["email", "phone"])).min(1).max(2).optional().describe('Default ["email"]'),
19801
21640
  verify: external_exports.boolean().optional().describe("Mailbox-check found emails"),
19802
21641
  ...paidArgs
19803
21642
  }).strict();
19804
21643
  var buildListInput = external_exports.object({
19805
- titles: external_exports.array(text(60)).min(1).max(5).optional(),
19806
- company: text(100).optional().describe("Company domain: decision-makers there"),
19807
- companies: external_exports.array(text(100)).min(1).max(100).optional().describe("Many domains"),
19808
- location: text(100).optional().describe("Country or city"),
19809
- ...companyFilters,
19810
- keywords: keywordsField,
19811
- business_type: text(100).optional().describe("Local businesses, with location"),
19812
- page: pageField,
21644
+ titles: external_exports.array(text3(60)).min(1).max(5).optional(),
21645
+ company: text3(100).optional().describe("Company domain: decision-makers there"),
21646
+ companies: external_exports.array(text3(100)).min(1).max(100).optional().describe("Many domains"),
21647
+ location: text3(100).optional().describe("Country or city"),
21648
+ ...companyFilters2,
21649
+ keywords: keywordsField2,
21650
+ business_type: text3(100).optional().describe("Local businesses, with location"),
21651
+ page: pageField2,
19813
21652
  limit: external_exports.number().int().min(1).max(100).optional(),
19814
21653
  ...paidArgs
19815
21654
  }).strict();
19816
- var researchCompanyInput = external_exports.object({ company: text(100).describe("Company domain, like vercel.com"), ...paidArgs }).strict();
21655
+ var researchCompanyInput = external_exports.object({ company: text3(100).describe("Company domain, like vercel.com"), ...paidArgs }).strict();
19817
21656
  var findSignalsInput = external_exports.object({
19818
- role: text(200).describe("Role being hired"),
19819
- location: text(100).optional(),
19820
- company: text(100).optional().describe("Watch one company"),
19821
- ...companyFilters,
19822
- page: pageField,
21657
+ role: text3(200).describe("Role being hired"),
21658
+ location: text3(100).optional(),
21659
+ company: text3(100).optional().describe("Watch one company"),
21660
+ ...companyFilters2,
21661
+ page: pageField2,
19823
21662
  limit: external_exports.number().int().min(1).max(50).optional(),
19824
21663
  ...paidArgs
19825
21664
  }).strict();
19826
21665
  var icpFields = {
19827
- titles: external_exports.array(text(60)).min(1).max(5).optional(),
19828
- location: text(100).optional(),
19829
- ...companyFilters,
19830
- keywords: keywordsField
21666
+ titles: external_exports.array(text3(60)).min(1).max(5).optional(),
21667
+ location: text3(100).optional(),
21668
+ ...companyFilters2,
21669
+ keywords: keywordsField2
19831
21670
  };
19832
21671
  var findLeadsInput = external_exports.object({
19833
21672
  ...icpFields,
19834
- hiring_roles: external_exports.array(text(100)).min(1).max(5).optional().describe("Signal; a tool's name finds its users"),
21673
+ hiring_roles: external_exports.array(text3(100)).min(1).max(5).optional().describe("Signal; a tool's name finds its users"),
19835
21674
  recently_funded: external_exports.boolean().optional().describe("Signal"),
19836
- like_companies: external_exports.array(text(100)).min(1).max(5).optional().describe("Signal: domains"),
19837
- post_urls: external_exports.array(text(500)).min(1).max(5).optional().describe("Signal: LinkedIn posts"),
21675
+ like_companies: external_exports.array(text3(100)).min(1).max(5).optional().describe("Signal: domains"),
21676
+ post_urls: external_exports.array(text3(500)).min(1).max(5).optional().describe("Signal: LinkedIn posts"),
19838
21677
  target: external_exports.number().int().min(1).max(500).optional().describe("Default 25"),
19839
21678
  max_per_company: external_exports.number().int().min(1).max(5).optional().describe("Default 2"),
19840
21679
  ...paidArgs
@@ -19843,8 +21682,8 @@ var workspaceIcpInput = external_exports.object({ ...icpFields, notes: external_
19843
21682
  var workspaceInput = external_exports.object({
19844
21683
  action: external_exports.enum(["get", "set_icp", "exclude", "forget_seen"]),
19845
21684
  icp: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Fields of gtm_find_leads, plus notes"),
19846
- domains: external_exports.array(text(100)).min(1).max(500).optional(),
19847
- profiles: external_exports.array(text(300)).min(1).max(500).optional()
21685
+ domains: external_exports.array(text3(100)).min(1).max(500).optional(),
21686
+ profiles: external_exports.array(text3(300)).min(1).max(500).optional()
19848
21687
  }).strict();
19849
21688
  var resultsInput = external_exports.object({
19850
21689
  run_id: external_exports.string().min(1).max(64),
@@ -19854,12 +21693,12 @@ var resultsInput = external_exports.object({
19854
21693
  var toolsInput = external_exports.object({
19855
21694
  action: external_exports.enum(["search", "describe", "run"]),
19856
21695
  query: external_exports.string().trim().max(200).optional(),
19857
- capability: capabilityIdSchema.optional(),
21696
+ capability: capabilityIdSchema.describe("From catalog search").meta({ "x-gtm-catalog": true }).optional(),
19858
21697
  input: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
19859
21698
  ...paidArgs
19860
21699
  }).strict();
19861
21700
  var accountInput = external_exports.object({
19862
- quote: external_exports.object({ capability: external_exports.string().pipe(capabilityIdSchema).describe("A gtm_tools capability"), count: external_exports.number().int().min(1).max(1e5) }).strict().optional().describe("Price a planned batch")
21701
+ quote: external_exports.object({ capability: external_exports.string().pipe(capabilityIdSchema.describe("From catalog search").meta({ "x-gtm-catalog": true })).describe("A gtm_tools capability"), count: external_exports.number().int().min(1).max(1e5) }).strict().optional().describe("Price a planned batch")
19863
21702
  }).strict();
19864
21703
  var OUTCOME_TOOLS = {
19865
21704
  gtm_find_contacts: {
@@ -20032,7 +21871,7 @@ function toonCell(value) {
20032
21871
  if (typeof value !== "string") return String(value);
20033
21872
  return NEEDS_QUOTES.test(value) ? JSON.stringify(value) : value;
20034
21873
  }
20035
- function answerText(answer) {
21874
+ function answerLines(answer) {
20036
21875
  const lines = [`summary: ${answer.summary}`, `status: ${answer.status}`];
20037
21876
  if (answer.reason) lines.push(`reason: ${answer.reason}`);
20038
21877
  if (answer.run_id) lines.push(`run_id: ${answer.run_id}`);
@@ -20050,10 +21889,31 @@ function answerText(answer) {
20050
21889
  if (answer.fields?.length) lines.push(`fields[${answer.fields.length}]: ${answer.fields.join(",")}`);
20051
21890
  if (answer.link) lines.push(`link: ${answer.link}`);
20052
21891
  if (answer.top_up) lines.push(`top_up: ${answer.top_up.credits} credits at ${answer.top_up.url}`);
21892
+ return lines;
21893
+ }
21894
+ function answerText(answer) {
21895
+ const lines = answerLines(answer);
20053
21896
  if (answer.next) lines.push(`next: ${answer.next.tool}(${JSON.stringify(answer.next.args)})`);
20054
21897
  return lines.join("\n");
20055
21898
  }
20056
21899
 
21900
+ // ../contracts/src/device-code.ts
21901
+ var USER_CODE_LENGTH = 8;
21902
+ var DEVICE_CODE_INPUT_MIN = 4;
21903
+ var DEVICE_CODE_INPUT_MAX = 16;
21904
+ var DEVICE_RETURN_CODE_PATTERN = `[A-Za-z0-9-]{${DEVICE_CODE_INPUT_MIN},${DEVICE_CODE_INPUT_MAX}}`;
21905
+ var deviceUserCodeInputSchema = external_exports.string().trim().min(DEVICE_CODE_INPUT_MIN).max(DEVICE_CODE_INPUT_MAX);
21906
+ var USER_CODE_GROUP_LENGTH = USER_CODE_LENGTH / 2;
21907
+
21908
+ // ../contracts/src/identifiers.ts
21909
+ var CONNECTION_REQUEST = { bytes: 24, minLength: 16, maxLength: 64 };
21910
+ var APPROVAL = { prefix: "apr_", bytes: 12 };
21911
+ var TOKEN_ALPHABET = "[A-Za-z0-9_-]";
21912
+ var CONNECTION_REQUEST_ID_PATTERN = `${TOKEN_ALPHABET}{${CONNECTION_REQUEST.minLength},${CONNECTION_REQUEST.maxLength}}`;
21913
+ var APPROVAL_ID_PATTERN = `${APPROVAL.prefix}${TOKEN_ALPHABET}{${Math.ceil(APPROVAL.bytes * 4 / 3)}}`;
21914
+ var connectionRequestIdSchema = external_exports.string().regex(new RegExp(`^${CONNECTION_REQUEST_ID_PATTERN}$`));
21915
+ var approvalIdSchema = external_exports.string().regex(new RegExp(`^${APPROVAL_ID_PATTERN}$`));
21916
+
20057
21917
  // ../contracts/src/agents.ts
20058
21918
  var emailVerdictSchema = external_exports.enum(["deliverable", "risky", "invalid"]);
20059
21919
  var AGENT_SCOPES = ["gtm:read", "gtm:run"];
@@ -20104,7 +21964,7 @@ var agentUpdateSchema = external_exports.object({
20104
21964
  allow_topup: external_exports.boolean().optional()
20105
21965
  }).strict().refine((value) => Object.keys(value).length > 0, "Nothing to update");
20106
21966
  var connectorConsentSchema = external_exports.object({
20107
- id: external_exports.string(),
21967
+ id: connectionRequestIdSchema,
20108
21968
  client: external_exports.object({
20109
21969
  id: external_exports.string(),
20110
21970
  name: external_exports.string(),
@@ -20129,7 +21989,7 @@ var deviceLoginSchema = external_exports.object({
20129
21989
  expires_at: external_exports.number().int()
20130
21990
  });
20131
21991
  var deviceDecisionSchema = external_exports.object({
20132
- user_code: external_exports.string().trim().min(4).max(16),
21992
+ user_code: deviceUserCodeInputSchema,
20133
21993
  credit_cap: creditCapSchema.optional(),
20134
21994
  cap_period: capPeriodSchema.optional()
20135
21995
  }).strict();
@@ -20165,7 +22025,7 @@ var worldVerifyFailureSchema = external_exports.enum([
20165
22025
  "unknown_attempt"
20166
22026
  ]);
20167
22027
  var agentApprovalSchema = external_exports.object({
20168
- id: external_exports.string(),
22028
+ id: approvalIdSchema,
20169
22029
  agent: external_exports.object({ id: external_exports.string(), name: external_exports.string() }),
20170
22030
  tool: external_exports.string(),
20171
22031
  description: external_exports.string(),
@@ -20225,7 +22085,7 @@ var tableRowsInput = external_exports.object({
20225
22085
  }).strict();
20226
22086
  var tableRowsPageSchema = external_exports.object({
20227
22087
  run_id: external_exports.string(),
20228
- status: external_exports.enum(["running", "completed", "not_found", "error"]),
22088
+ status: external_exports.enum(AGENT_RUN_STATUSES),
20229
22089
  label: external_exports.string(),
20230
22090
  /** The run's preview columns first, then every other field its rows carry. */
20231
22091
  columns: external_exports.array(external_exports.string()),
@@ -20239,6 +22099,11 @@ var tableRowsPageSchema = external_exports.object({
20239
22099
  }).strict();
20240
22100
 
20241
22101
  // ../contracts/src/topups.ts
22102
+ var BASE_CHAIN_ID = 8453;
22103
+ var BASE_USDC = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
22104
+ var NATIVE_TOKEN = "0x0000000000000000000000000000000000000000";
22105
+ var TOPUP_SIGNATURE_LIFETIME_MS = 60 * 6e4;
22106
+ var TOPUP_SIGNATURE_REUSE_MARGIN_MS = 10 * 6e4;
20242
22107
  var address = external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/);
20243
22108
  var txHashSchema = external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/);
20244
22109
  var topupRailSchema = external_exports.enum(["usdc", "swap", "jar"]);
@@ -20342,47 +22207,114 @@ var arcPaymentSchema = external_exports.object({
20342
22207
  });
20343
22208
  var arcPaymentResponseSchema = external_exports.object({ payment: arcPaymentSchema });
20344
22209
 
20345
- // ../contracts/src/index.ts
20346
- var lookupStatusSchema = external_exports.enum(["found", "not_found", "error"]);
20347
- var deliverabilitySchema = external_exports.enum(["verified", "unverified"]).nullable().transform((value) => value === "verified" ? value : null);
20348
- var lookupRequestSchema = external_exports.object({
20349
- // Individual entries remain unknown here because the API's forgiving
20350
- // normalizer drops invalid entries while preserving valid ones in a mixed
20351
- // paste. The max length is configuration-owned by the API route.
20352
- urls: external_exports.array(external_exports.unknown()).min(1)
20353
- });
20354
- var lookupResultSchema = external_exports.object({
20355
- /** Canonical request identity echoed for exact client-side row matching. */
20356
- key: external_exports.string(),
20357
- url: external_exports.string(),
20358
- status: lookupStatusSchema,
20359
- name: external_exports.string().nullable(),
20360
- title: external_exports.string().nullable(),
20361
- email: external_exports.string().nullable(),
20362
- deliverability: deliverabilitySchema
20363
- });
20364
- var lookupSummarySchema = external_exports.object({
20365
- type: external_exports.literal("summary"),
20366
- total: external_exports.number().int().nonnegative(),
20367
- found: external_exports.number().int().nonnegative(),
20368
- credits: external_exports.number().int().nonnegative().optional()
20369
- });
20370
- var lookupErrorSchema = external_exports.object({
20371
- error: external_exports.string(),
20372
- detail: external_exports.string().optional(),
20373
- credits: external_exports.object({ remaining: external_exports.number().int().nonnegative() }).optional()
20374
- });
20375
- var lookupEventSchema = external_exports.union([lookupResultSchema, lookupSummarySchema]);
20376
- var historySourceSchema = external_exports.enum(["web", "agent"]);
20377
- var historyEntrySchema = external_exports.object({
20378
- url: external_exports.string(),
20379
- status: lookupStatusSchema,
20380
- name: external_exports.string().nullable(),
20381
- title: external_exports.string().nullable(),
20382
- email: external_exports.string().nullable(),
20383
- deliverability: deliverabilitySchema,
20384
- lookedUpAt: external_exports.number().int().nonnegative()
22210
+ // ../contracts/src/session.ts
22211
+ var CONSENT_PATH = "/connect/";
22212
+ var DEVICE_PATH = "/device/";
22213
+ var escapeRegex2 = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
22214
+ var planChoices = CREDIT_PLANS.flatMap((plan) => Object.keys(plan.prices).map((billing) => escapeRegex2(`${plan.id}-${billing}`)));
22215
+ var returnPath = new RegExp([
22216
+ "^/admin/$",
22217
+ `^${CONSENT_PATH}\\?request=${CONNECTION_REQUEST_ID_PATTERN}$`,
22218
+ `^/approve/\\?request=${APPROVAL_ID_PATTERN}$`,
22219
+ `^${DEVICE_PATH}(?:\\?code=${DEVICE_RETURN_CODE_PATTERN})?$`,
22220
+ `^/outboundmaxing/(?:\\?plan=(?:${planChoices.join("|")}))?$`
22221
+ ].join("|"));
22222
+
22223
+ // ../contracts/src/agent-permissions.ts
22224
+ var CAP_PERIODS = capPeriodSchema.options;
22225
+ var MIN_CAP = creditCapSchema.minValue;
22226
+ var MAX_CAP = creditCapSchema.maxValue;
22227
+
22228
+ // ../contracts/src/external.ts
22229
+ var MAX_V1_BODY_BYTES = 128 * 1024;
22230
+ var IDEMPOTENCY_LEASE_MS = 10 * 60 * 1e3;
22231
+ var IDEMPOTENCY_RENEW_INTERVAL_MS = 60 * 1e3;
22232
+ var IDEMPOTENCY_RETENTION_MS = 24 * 60 * 60 * 1e3;
22233
+ var externalRequestIdSchema = external_exports.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/);
22234
+ var externalIdempotencyKeySchema = external_exports.string().min(1).max(255).regex(/^[!-~]{1,255}$/);
22235
+ var externalLookupRequestSchema = lookupRequestSchema.strict();
22236
+ var lookupJobPendingSchema = external_exports.object({ status: external_exports.literal("in_progress"), job_id: external_exports.string(), request_id: external_exports.string() });
22237
+
22238
+ // ../contracts/src/contact-pricing.ts
22239
+ function contactCredits(options) {
22240
+ const find = options.find ?? ["email"];
22241
+ return (find.includes("email") ? CAPABILITIES["email-finder"].price.credits : 0) + (options.verify ? CAPABILITIES["verify-email"].price.credits : 0) + (find.includes("phone") ? CAPABILITIES["phone-pilot"].price.credits : 0) + (options.named ? CAPABILITIES["profile-finder"].price.credits : 0);
22242
+ }
22243
+
22244
+ // ../contracts/src/topup-chains.ts
22245
+ var native = (symbol2) => ({ symbol: symbol2, address: NATIVE_TOKEN, decimals: 18 });
22246
+ var usdc = (address2, decimals = 6) => ({ symbol: "USDC", address: address2, decimals });
22247
+ var TOPUP_CHAINS = [
22248
+ { id: BASE_CHAIN_ID, name: "Base", tokens: [
22249
+ { ...native("ETH"), jar: true },
22250
+ usdc(BASE_USDC),
22251
+ { symbol: "WETH", address: "0x4200000000000000000000000000000000000006", decimals: 18, jar: true },
22252
+ { symbol: "cbBTC", address: "0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf", decimals: 8, jar: true },
22253
+ { symbol: "AERO", address: "0x940181a94A35A4569E4529A3CDfB74e38FD98631", decimals: 18, jar: true }
22254
+ ] },
22255
+ { id: 42161, name: "Arbitrum", tokens: [
22256
+ native("ETH"),
22257
+ usdc("0xaf88d065e77c8cC2239327C5EDb3A432268e5831"),
22258
+ { symbol: "USDT", address: "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9", decimals: 6 },
22259
+ { symbol: "ARB", address: "0x912CE59144191C1204E64559FE8253a0e49E6548", decimals: 18 }
22260
+ ] },
22261
+ { id: 1, name: "Ethereum", tokens: [
22262
+ native("ETH"),
22263
+ usdc("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"),
22264
+ { symbol: "USDT", address: "0xdAC17F958D2ee523a2206206994597C13D831ec7", decimals: 6 },
22265
+ { symbol: "UNI", address: "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984", decimals: 18 }
22266
+ ] },
22267
+ { id: 10, name: "Optimism", tokens: [
22268
+ native("ETH"),
22269
+ usdc("0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85"),
22270
+ { symbol: "OP", address: "0x4200000000000000000000000000000000000042", decimals: 18 }
22271
+ ] },
22272
+ { id: 137, name: "Polygon", tokens: [
22273
+ native("POL"),
22274
+ usdc("0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"),
22275
+ { symbol: "USDT", address: "0xc2132D05D31c914a87C6611C10748AEb04B58e8F", decimals: 6 }
22276
+ ] },
22277
+ { id: 56, name: "BNB Chain", tokens: [
22278
+ native("BNB"),
22279
+ usdc("0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d", 18),
22280
+ { symbol: "USDT", address: "0x55d398326f99059fF775485246999027B3197955", decimals: 18 }
22281
+ ] },
22282
+ { id: 130, name: "Unichain", tokens: [native("ETH"), usdc("0x078D782b760474a361dDA0AF3839290b0EF57AD6")] },
22283
+ { id: 43114, name: "Avalanche", tokens: [native("AVAX"), usdc("0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E")] }
22284
+ ];
22285
+
22286
+ // ../contracts/src/tool-navigation.ts
22287
+ var WEB_TOOLS = Object.entries(TOOL_DEFINITIONS).flatMap(
22288
+ ([id, definition]) => definition.web ? [
22289
+ {
22290
+ id,
22291
+ ...definition.web,
22292
+ name: definition.name,
22293
+ icon: definition.presentation.icon,
22294
+ badges: definition.badges
22295
+ }
22296
+ ] : []
22297
+ );
22298
+ var TOOL_NAV_GROUPS = [
22299
+ { title: "Enrichment", icon: "contact" },
22300
+ { title: "Lead lists", icon: "social" },
22301
+ { title: "Web research", icon: "globe" },
22302
+ { title: "Social listening", icon: "social" }
22303
+ ].map((group) => {
22304
+ const tools = WEB_TOOLS.filter((tool2) => tool2.section === group.title).sort((a, b) => a.order - b.order);
22305
+ const marks = [
22306
+ ...group.title === "Enrichment" ? EMAIL_FINDER_DEFINITION.badges : [],
22307
+ ...tools.flatMap((tool2) => tool2.badges)
22308
+ ];
22309
+ return {
22310
+ ...group,
22311
+ tools: [...group.title === "Enrichment" ? ["email-finder"] : [], ...tools.map((tool2) => tool2.id)],
22312
+ providers: [...new Map(marks.map((mark) => [mark.name, mark])).values()]
22313
+ };
20385
22314
  });
22315
+
22316
+ // ../contracts/src/index.ts
22317
+ var historySourceSchema = external_exports.enum(["web", "agent"]);
20386
22318
  var lookupRunItemSchema = external_exports.object({
20387
22319
  position: external_exports.number().int().nonnegative(),
20388
22320
  url: external_exports.string(),
@@ -20414,7 +22346,7 @@ var historyItemSchema = external_exports.discriminatedUnion("kind", [
20414
22346
  id: external_exports.string(),
20415
22347
  tool: toolIdSchema,
20416
22348
  status: toolRunSchema.shape.status,
20417
- input: toolRequestSchema,
22349
+ input: storedToolRequestV1Schema,
20418
22350
  rowCount: external_exports.number().int().nonnegative(),
20419
22351
  credits: external_exports.number().int().nonnegative(),
20420
22352
  source: historySourceSchema,
@@ -20456,10 +22388,22 @@ var usageResponseSchema = external_exports.object({
20456
22388
  errors: external_exports.number().int().nonnegative()
20457
22389
  })
20458
22390
  });
20459
- var externalErrorSchema = external_exports.object({
20460
- error: external_exports.string(),
20461
- request_id: external_exports.string(),
20462
- detail: external_exports.string().optional()
22391
+ var planIdSchema = external_exports.enum(CREDIT_PLANS.map((plan) => plan.id));
22392
+ var billingSchema = external_exports.enum(["monthly", "annual"]);
22393
+ var checkoutPurchaseQuerySchema = external_exports.object({
22394
+ plan: planIdSchema,
22395
+ billing: billingSchema,
22396
+ since: external_exports.coerce.number().int().nonnegative(),
22397
+ /** The browser's clock when it asked, so the API can read `since` on its own clock. */
22398
+ now: external_exports.coerce.number().int().nonnegative()
22399
+ });
22400
+ var checkoutPurchaseResponseSchema = external_exports.object({
22401
+ purchase: external_exports.object({
22402
+ plan: planIdSchema,
22403
+ billing: billingSchema,
22404
+ credits: external_exports.number().int().positive(),
22405
+ creditedAt: external_exports.number().int().nonnegative()
22406
+ }).nullable()
20463
22407
  });
20464
22408
 
20465
22409
  // src/commands.ts
@@ -20556,8 +22500,21 @@ function paid(values, topic) {
20556
22500
  ...key !== void 0 ? { idempotency_key: key } : {}
20557
22501
  };
20558
22502
  }
22503
+ var ARGUMENT_NAMES = {
22504
+ "business-type": "business_type",
22505
+ industry: "industries",
22506
+ size: "company_sizes",
22507
+ "hiring-role": "hiring_roles",
22508
+ like: "like_companies",
22509
+ post: "post_urls",
22510
+ domain: "domains",
22511
+ profile: "profiles"
22512
+ };
22513
+ function argumentFlag(key) {
22514
+ return Object.entries(ARGUMENT_NAMES).find(([, argument]) => argument === key)?.[0] ?? key.replace(/_/g, "-");
22515
+ }
20559
22516
  function pick2(values, flags) {
20560
- return Object.fromEntries(Object.entries(flags).flatMap(([flag, key]) => values[flag] === void 0 ? [] : [[key, values[flag]]]));
22517
+ return Object.fromEntries(flags.flatMap((flag) => values[flag] === void 0 ? [] : [[ARGUMENT_NAMES[flag] ?? flag, values[flag]]]));
20561
22518
  }
20562
22519
  function build2(name, values, positionals) {
20563
22520
  const none = (message) => {
@@ -20596,31 +22553,31 @@ function build2(name, values, positionals) {
20596
22553
  }
20597
22554
  case "list": {
20598
22555
  none("gtm list takes flags only, like --titles 'VP Sales'.");
20599
- const limit2 = int2(values, "limit", name);
22556
+ const limit = int2(values, "limit", name);
20600
22557
  const page = int2(values, "page", name);
20601
22558
  const companies = Array.isArray(values.company) ? values.company : [];
20602
- return { kind: "tool", tool: "gtm_build_list", args: { ...pick2(values, { titles: "titles", location: "location", "business-type": "business_type", industry: "industries", size: "company_sizes", keywords: "keywords" }), ...companies.length === 1 ? { company: companies[0] } : companies.length ? { companies } : {}, ...page !== void 0 ? { page } : {}, ...limit2 !== void 0 ? { limit: limit2 } : {}, ...paid(values, name) } };
22559
+ return { kind: "tool", tool: "gtm_build_list", args: { ...pick2(values, ["titles", "location", "business-type", "industry", "size", "keywords"]), ...companies.length === 1 ? { company: companies[0] } : companies.length ? { companies } : {}, ...page !== void 0 ? { page } : {}, ...limit !== void 0 ? { limit } : {}, ...paid(values, name) } };
20603
22560
  }
20604
22561
  case "leads": {
20605
22562
  none("gtm leads takes flags only, like --titles 'Head of Sales' --target 25.");
20606
22563
  const target = int2(values, "target", name);
20607
22564
  const perCompany = int2(values, "max-per-company", name);
20608
- return { kind: "tool", tool: "gtm_find_leads", args: { ...pick2(values, { titles: "titles", location: "location", industry: "industries", size: "company_sizes", keywords: "keywords", "hiring-role": "hiring_roles", like: "like_companies", post: "post_urls" }), ...values.funded ? { recently_funded: true } : {}, ...target !== void 0 ? { target } : {}, ...perCompany !== void 0 ? { max_per_company: perCompany } : {}, ...paid(values, name) } };
22565
+ return { kind: "tool", tool: "gtm_find_leads", args: { ...pick2(values, ["titles", "location", "industry", "size", "keywords", "hiring-role", "like", "post"]), ...values.funded ? { recently_funded: true } : {}, ...target !== void 0 ? { target } : {}, ...perCompany !== void 0 ? { max_per_company: perCompany } : {}, ...paid(values, name) } };
20609
22566
  }
20610
22567
  case "workspace": {
20611
22568
  const action = positionals[0] ?? "get";
20612
22569
  if (!["get", "set-icp", "exclude", "forget-seen"].includes(action) || positionals.length > 1) throw new UsageError("Use gtm workspace, gtm workspace set-icp, gtm workspace exclude or gtm workspace forget-seen.", name);
20613
- const icp = pick2(values, { titles: "titles", location: "location", industry: "industries", size: "company_sizes", keywords: "keywords", notes: "notes" });
20614
- return { kind: "tool", tool: "gtm_workspace", args: { action: action.replace("-", "_"), ...action === "set-icp" ? { icp } : {}, ...pick2(values, { domain: "domains", profile: "profiles" }) } };
22570
+ const icp = pick2(values, ["titles", "location", "industry", "size", "keywords", "notes"]);
22571
+ return { kind: "tool", tool: "gtm_workspace", args: { action: action.replace("-", "_"), ...action === "set-icp" ? { icp } : {}, ...pick2(values, ["domain", "profile"]) } };
20615
22572
  }
20616
22573
  case "research":
20617
22574
  if (positionals.length !== 1) throw new UsageError("Give one company domain, like vercel.com.", name);
20618
22575
  return { kind: "tool", tool: "gtm_research_company", args: { company: positionals[0], ...paid(values, name) } };
20619
22576
  case "signals": {
20620
22577
  if (!positionals.length) throw new UsageError("Give the role being hired, like 'Account Executive'.", name);
20621
- const limit2 = int2(values, "limit", name);
22578
+ const limit = int2(values, "limit", name);
20622
22579
  const page = int2(values, "page", name);
20623
- return { kind: "tool", tool: "gtm_find_signals", args: { role: positionals.join(" "), ...pick2(values, { location: "location", company: "company", industry: "industries", size: "company_sizes" }), ...page !== void 0 ? { page } : {}, ...limit2 !== void 0 ? { limit: limit2 } : {}, ...paid(values, name) } };
22580
+ return { kind: "tool", tool: "gtm_find_signals", args: { role: positionals.join(" "), ...pick2(values, ["location", "company", "industry", "size"]), ...page !== void 0 ? { page } : {}, ...limit !== void 0 ? { limit } : {}, ...paid(values, name) } };
20624
22581
  }
20625
22582
  case "results": {
20626
22583
  if (!positionals.length) throw new UsageError("Give a run id, like gtm results run_abc.", name);
@@ -20664,7 +22621,7 @@ function build2(name, values, positionals) {
20664
22621
  throw new UsageError("Use gtm tools search <words>, gtm tools describe <capability> or gtm tools run <capability>.", name);
20665
22622
  }
20666
22623
  case "account": {
20667
- const [sub, capability2, ...extra] = positionals;
22624
+ const [sub, capability, ...extra] = positionals;
20668
22625
  const count = int2(values, "count", name);
20669
22626
  const file2 = str(values, "file");
20670
22627
  const column = str(values, "column");
@@ -20675,11 +22632,11 @@ function build2(name, values, positionals) {
20675
22632
  if (sub !== "quote" || extra.length) throw new UsageError("Use gtm account, or gtm account quote <capability> --count N, or gtm account quote --file leads.csv.", name);
20676
22633
  if (file2 !== void 0) {
20677
22634
  if (count !== void 0) throw new UsageError("Give --count or --file, not both.", name);
20678
- return { kind: "quote-file", capability: capability2 ?? "email-finder", file: file2, ...column !== void 0 ? { column } : {} };
22635
+ return { kind: "quote-file", capability: capability ?? "email-finder", file: file2, ...column !== void 0 ? { column } : {} };
20679
22636
  }
20680
22637
  if (column !== void 0) throw new UsageError("--column needs --file.", name);
20681
- if (!capability2 || count === void 0) throw new UsageError("Give a capability and --count, like gtm account quote email-finder --count 500.", name);
20682
- return { kind: "tool", tool: "gtm_account", args: { quote: { capability: capability2, count } } };
22638
+ if (!capability || count === void 0) throw new UsageError("Give a capability and --count, like gtm account quote email-finder --count 500.", name);
22639
+ return { kind: "tool", tool: "gtm_account", args: { quote: { capability, count } } };
20683
22640
  }
20684
22641
  default:
20685
22642
  throw new UsageError(`Unknown command "${name}"; run gtm --help.`);
@@ -20731,7 +22688,7 @@ function commandArgv(next) {
20731
22688
  break;
20732
22689
  }
20733
22690
  for (const [key, value] of Object.entries(args)) {
20734
- const flag = `--${key.replace(/_/g, "-")}`;
22691
+ const flag = `--${argumentFlag(key)}`;
20735
22692
  if (value === true) words.push(flag);
20736
22693
  else if (value === false || value === void 0 || value === null) continue;
20737
22694
  else if (key === "find" && Array.isArray(value)) words.push(flag, value.join(","));
@@ -20745,20 +22702,17 @@ function commandFor(next) {
20745
22702
  return commandArgv(next).map(shellQuote).join(" ");
20746
22703
  }
20747
22704
 
20748
- // src/contacts.ts
20749
- import { createHash } from "node:crypto";
20750
-
20751
22705
  // src/csv.ts
20752
22706
  var FileInputError = class extends Error {
20753
22707
  name = "FileInputError";
20754
22708
  };
20755
- function parseCsv(text2) {
22709
+ function parseCsv(text4) {
20756
22710
  const rows = [];
20757
22711
  let row = [];
20758
22712
  let cell2 = "";
20759
22713
  let quoted = false;
20760
22714
  let started = false;
20761
- const source = text2.charCodeAt(0) === 65279 ? text2.slice(1) : text2;
22715
+ const source = text4.charCodeAt(0) === 65279 ? text4.slice(1) : text4;
20762
22716
  const endRow = () => {
20763
22717
  row.push(cell2);
20764
22718
  rows.push(row);
@@ -20799,14 +22753,12 @@ function toCsv(rows) {
20799
22753
  return rows.map((row) => row.map(escape).join(",")).join("\r\n") + "\r\n";
20800
22754
  }
20801
22755
  var PROFILE_URL = /linkedin\.com\/in\//i;
20802
- var CANONICAL = /^https:\/\/www\.linkedin\.com\/in\/[A-Za-z0-9_%-]{1,100}$/;
20803
22756
  var HEADER_WORDS = /^(linkedin|linkedin[ _-]?(url|profile|profile[ _-]?url|handle)|profile([ _-]?url)?|url|handle|person|people)$/i;
20804
22757
  function profileOf(value) {
20805
- const url2 = linkedinProfileUrl(value);
20806
- return CANONICAL.test(url2) ? url2 : null;
22758
+ return cliProfileUrl(value);
20807
22759
  }
20808
- function profilesFromCsv(text2, column) {
20809
- const table = parseCsv(text2).filter((row) => row.some((cell2) => cell2.trim() !== ""));
22760
+ function profilesFromCsv(text4, column) {
22761
+ const table = parseCsv(text4).filter((row) => row.some((cell2) => cell2.trim() !== ""));
20810
22762
  if (!table.length) throw new FileInputError("The file has no rows.");
20811
22763
  const first = table[0];
20812
22764
  const width = Math.max(...table.map((row) => row.length));
@@ -20845,13 +22797,13 @@ function profilesFromCsv(text2, column) {
20845
22797
  }
20846
22798
  return list;
20847
22799
  }
20848
- function peopleFromCsv(text2, column, names) {
20849
- if (names === "only") return { ...nameListAsProfiles(namesFromCsv(text2)), named: true };
22800
+ function peopleFromCsv(text4, column, names) {
22801
+ if (names === "only") return { ...nameListAsProfiles(namesFromCsv(text4)), named: true };
20850
22802
  try {
20851
- return { ...profilesFromCsv(text2, column), named: false };
22803
+ return { ...profilesFromCsv(text4, column), named: false };
20852
22804
  } catch (error61) {
20853
22805
  if (names === "never" || column !== void 0 || !(error61 instanceof FileInputError)) throw error61;
20854
- return { ...nameListAsProfiles(namesFromCsv(text2)), named: true };
22806
+ return { ...nameListAsProfiles(namesFromCsv(text4)), named: true };
20855
22807
  }
20856
22808
  }
20857
22809
  function nameListAsProfiles(list) {
@@ -20862,12 +22814,12 @@ var FIRST_HEADER = /^first[ _-]?name$/i;
20862
22814
  var LAST_HEADER = /^last[ _-]?name$/i;
20863
22815
  var COMPANY_HEADER = /^(company|company[ _-]?name|organi[sz]ation|account|account[ _-]?name|employer|company[ _-]?domain|domain|website)$/i;
20864
22816
  var SEPARATOR = "";
20865
- function namePair(key) {
20866
- const [name = "", company = ""] = key.split(SEPARATOR);
20867
- return { name, company };
22817
+ function namePair(person) {
22818
+ if (typeof person === "string") throw new TypeError("Expected a name and company pair");
22819
+ return person;
20868
22820
  }
20869
- function namesFromCsv(text2) {
20870
- const table = parseCsv(text2).filter((row) => row.some((cell2) => cell2.trim() !== ""));
22821
+ function namesFromCsv(text4) {
22822
+ const table = parseCsv(text4).filter((row) => row.some((cell2) => cell2.trim() !== ""));
20871
22823
  if (!table.length) throw new FileInputError("The file has no rows.");
20872
22824
  const header = table[0].map((cell2) => cell2.trim());
20873
22825
  const find = (pattern) => header.findIndex((cell2) => pattern.test(cell2));
@@ -20893,11 +22845,140 @@ function namesFromCsv(text2) {
20893
22845
  continue;
20894
22846
  }
20895
22847
  seen.add(key.toLowerCase());
20896
- list.people.push(key);
22848
+ list.people.push({ name, company });
20897
22849
  }
20898
22850
  return list;
20899
22851
  }
20900
22852
 
22853
+ // src/file-rows.ts
22854
+ var FILE_ROW_FALLBACK = {
22855
+ columns: ["name", "title", "email", "verdict", "url", "status"],
22856
+ identity(person) {
22857
+ return typeof person === "string" ? profileOf(person) ? { url: person } : { name: person, company: "" } : person;
22858
+ }
22859
+ };
22860
+
22861
+ // src/file-batches.ts
22862
+ import { createHash } from "node:crypto";
22863
+ async function quote(session, profiles, perCall, tool2) {
22864
+ let total = 0;
22865
+ let balance = null;
22866
+ for (let at = 0; at < profiles.length; at += perCall) {
22867
+ const answer = await session.gateway.call(tool2.tool, { ...tool2.args(profiles.slice(at, at + perCall)), dry_run: true });
22868
+ if (answer.status !== "quote") return { refusal: answer };
22869
+ total += answer.quote ?? 0;
22870
+ balance = answer.balance;
22871
+ }
22872
+ return { quote: total, balance };
22873
+ }
22874
+ function batchKey(base, args) {
22875
+ const hash2 = createHash("sha256").update(JSON.stringify(args)).digest("hex");
22876
+ if (!base) return `gtm-file-${hash2.slice(0, 32)}`;
22877
+ const key = `${base}-${hash2.slice(0, 16)}`;
22878
+ return key.length <= 128 ? key : `gtm-${createHash("sha256").update(key).digest("hex").slice(0, 40)}`;
22879
+ }
22880
+ function runIdsOf(run) {
22881
+ return [run, ...run.recovery ? [run.recovery] : []].flatMap((part) => part.batches.map((batch) => batch.answer.run_id).filter((id) => !!id));
22882
+ }
22883
+ function retryKey(key, runId) {
22884
+ return `gtm-retry-${createHash("sha256").update(`${key}|${runId}`).digest("hex").slice(0, 40)}`;
22885
+ }
22886
+ async function runBatches(session, profiles, perCall, budget, tool2, baseKey) {
22887
+ const perPerson = tool2.perPerson;
22888
+ const batches = [];
22889
+ let remaining = budget ?? 0;
22890
+ let sent = 0;
22891
+ let failedCost = 0;
22892
+ let failedRunCost = 0;
22893
+ const done = (stop, refusal = null, running = false) => ({ batches, stop, refusal, running, failedCost, failedRunCost });
22894
+ const retried = /* @__PURE__ */ new Set();
22895
+ while (sent < profiles.length) {
22896
+ const size = Math.min(perCall, profiles.length - sent, budget === null ? perCall : Math.floor(remaining / perPerson));
22897
+ if (size <= 0) return done({ reason: "over_max_credits", refusal: null });
22898
+ const people = profiles.slice(sent, sent + size);
22899
+ let key = batchKey(baseKey, tool2.args(people));
22900
+ for (; ; ) {
22901
+ const first = await session.gateway.call(tool2.tool, {
22902
+ ...tool2.args(people),
22903
+ ...budget === null ? {} : { max_credits: Math.max(0, remaining) },
22904
+ idempotency_key: key
22905
+ });
22906
+ const answer = await session.settle(first);
22907
+ const stopped = (stop) => batches.length || stop.status === "error" ? done({ reason: stop.reason ?? stop.status, refusal: stop }) : done(null, stop);
22908
+ if (answer.status === "refused") return stopped(answer);
22909
+ const runCost = answer.run_cost ?? answer.cost;
22910
+ if (answer.status === "error") {
22911
+ failedRunCost += runCost;
22912
+ remaining -= runCost;
22913
+ if (!first.replayed || !answer.run_id) {
22914
+ failedCost += runCost;
22915
+ return stopped(answer);
22916
+ }
22917
+ key = retryKey(key, answer.run_id);
22918
+ continue;
22919
+ }
22920
+ if (answer.reason === "partial_failure" && first.replayed && answer.run_id && !retried.has(key)) {
22921
+ retried.add(key);
22922
+ failedRunCost += runCost;
22923
+ remaining -= runCost;
22924
+ key = retryKey(key, answer.run_id);
22925
+ continue;
22926
+ }
22927
+ batches.push({ people, answer, replayed: first.replayed === true, runCost, cost: first.replayed ? 0 : runCost });
22928
+ if (answer.status === "running") return done({ reason: "running", refusal: null }, null, true);
22929
+ remaining -= runCost;
22930
+ break;
22931
+ }
22932
+ sent += size;
22933
+ }
22934
+ return done(null);
22935
+ }
22936
+ async function collectRows(session, batches, fallback) {
22937
+ let columns = null;
22938
+ const perBatch = [];
22939
+ for (const batch of batches) {
22940
+ const runId = batch.answer.run_id;
22941
+ if (!runId) return null;
22942
+ const link = await session.gateway.call("gtm_results", { run_id: runId, format: "csv" });
22943
+ if (!link.link) return null;
22944
+ const [header = [], ...data] = parseCsv(await session.gateway.download(link.link));
22945
+ const named = header.filter(Boolean);
22946
+ if (named.length) columns = [.../* @__PURE__ */ new Set([...columns ?? [], ...named])];
22947
+ perBatch.push(data.map((cells) => Object.fromEntries(named.map((name, i) => [name, cells[i] ? cells[i] : null]))));
22948
+ }
22949
+ const all = columns ?? fallback.columns;
22950
+ const rows = batches.flatMap((batch, i) => perBatch[i].length ? perBatch[i] : batch.people.map((person) => ({ ...Object.fromEntries(all.map((name) => [name, null])), ...fallback.identity(person), status: batch.answer.status === "error" ? "error" : "not_found" })));
22951
+ return { columns: all, rows: rows.map((row) => Object.fromEntries(all.map((name) => [name, row[name] ?? null]))) };
22952
+ }
22953
+ async function recoverErroredRows(session, run, table, perCall, tool2, budgetLeft) {
22954
+ const errored = table.rows.filter((row) => row.status === "error" && row.url).map((row) => row.url);
22955
+ if (!errored.length || run.stop) return;
22956
+ const keyBase = `gtm-retry-${createHash("sha256").update(runIdsOf(run).join(",")).digest("hex").slice(0, 32)}`;
22957
+ const retry = await runBatches(session, errored, perCall, budgetLeft, tool2, keyBase);
22958
+ run.recovery = retry;
22959
+ const again = retry.batches.length && !retry.running ? await collectRows(session, retry.batches, FILE_ROW_FALLBACK) : null;
22960
+ const byUrl = new Map(again?.rows.map((row) => [row.url, row]) ?? []);
22961
+ table.rows = table.rows.map((row) => row.status === "error" && byUrl.has(row.url) ? { ...row, ...byUrl.get(row.url) } : row);
22962
+ }
22963
+ async function writeOut(session, path, table) {
22964
+ await session.io.writeFile(path, toCsv([table.columns, ...table.rows.map((row) => table.columns.map((name) => row[name] ?? ""))]));
22965
+ }
22966
+
22967
+ // src/batch-outcome.ts
22968
+ function batchOutcome(run, found, hasTable) {
22969
+ const failed2 = run.stop?.refusal?.status === "error" ? run.stop.refusal : null;
22970
+ return {
22971
+ failed: failed2,
22972
+ status: failed2 ? "error" : run.running ? "running" : found || !hasTable ? "completed" : "not_found",
22973
+ reason: run.stop && !run.running ? { reason: run.stop.reason } : {},
22974
+ emitOptions: run.stop && !run.running && !failed2 ? { exit: 3 } : {},
22975
+ cost: spent(run, (batch) => batch.cost, run.failedCost) + (run.recovery ? spent(run.recovery, (batch) => batch.cost, run.recovery.failedCost) : 0),
22976
+ runCost: spent(run, (batch) => batch.runCost, run.failedRunCost) + (run.recovery ? spent(run.recovery, (batch) => batch.runCost, run.recovery.failedRunCost) : 0),
22977
+ balance: (failed2 ?? run.batches.at(-1)?.answer)?.balance ?? null
22978
+ };
22979
+ }
22980
+ var spent = (run, charge, failed2) => run.batches.reduce((sum, batch) => sum + charge(batch), failed2);
22981
+
20901
22982
  // src/output.ts
20902
22983
  var LOGIN_NEXT = { tool: "login", args: {} };
20903
22984
  var ACCOUNT_NEXT = { tool: "gtm_account", args: {} };
@@ -20909,8 +22990,7 @@ function exitCode(answer) {
20909
22990
  return answer.status === "error" ? 1 : answer.status === "refused" ? 3 : 0;
20910
22991
  }
20911
22992
  function renderText(answer, fields = {}) {
20912
- const text2 = answerText(answer);
20913
- const lines = [text2.slice(0, text2.lastIndexOf("\nnext: "))];
22993
+ const lines = answerLines(answer);
20914
22994
  for (const [key, value] of Object.entries(fields)) {
20915
22995
  if (value === void 0) continue;
20916
22996
  lines.push(Array.isArray(value) ? `${key}[${value.length}]: ${value.join(",")}` : `${key}: ${String(value)}`);
@@ -20931,7 +23011,6 @@ function errorAnswer(error61) {
20931
23011
  }
20932
23012
 
20933
23013
  // src/contacts.ts
20934
- var DEFAULT_COLUMNS = ["name", "title", "email", "verdict", "url", "status"];
20935
23014
  var NOT_WRITTEN_RUNNING = "not written: still running";
20936
23015
  var plural = (n2, one, many = `${one}s`) => `${n2} ${n2 === 1 ? one : many}`;
20937
23016
  async function contacts(session, command) {
@@ -20953,7 +23032,7 @@ async function contacts(session, command) {
20953
23032
  skipped: list.invalid + list.empty
20954
23033
  };
20955
23034
  const options = { ...args.find ? { find: args.find } : {}, ...args.verify ? { verify: true } : {} };
20956
- const tool2 = list.named ? { tool: "gtm_find_contacts", args: (people) => ({ named: people.map(namePair), ...options }), perPerson: perPersonCredits(options) + CAPABILITIES["profile-finder"].price.credits } : { tool: "gtm_find_contacts", args: (people) => ({ people, ...options }), perPerson: perPersonCredits(options) };
23035
+ const tool2 = list.named ? { tool: "gtm_find_contacts", args: (people) => ({ named: people.map(namePair), ...options }), perPerson: contactCredits({ ...options, named: true }) } : { tool: "gtm_find_contacts", args: (people) => ({ people, ...options }), perPerson: contactCredits(options) };
20957
23036
  const rerun = (flags) => fileNext(command, options, flags);
20958
23037
  const perCall = await session.gateway.peoplePerCall();
20959
23038
  const maxCredits = args.max_credits;
@@ -21012,111 +23091,17 @@ function fileNext(command, options, flags) {
21012
23091
  }
21013
23092
  };
21014
23093
  }
21015
- function perPersonCredits(options) {
21016
- const find = options.find ?? ["email"];
21017
- return (find.includes("email") ? CAPABILITIES["email-finder"].price.credits : 0) + (options.verify ? CAPABILITIES["verify-email"].price.credits : 0) + (find.includes("phone") ? CAPABILITIES["phone-pilot"].price.credits : 0);
21018
- }
21019
- async function quote(session, profiles, perCall, tool2) {
21020
- let total = 0;
21021
- let balance = null;
21022
- for (let at = 0; at < profiles.length; at += perCall) {
21023
- const answer = await session.gateway.call(tool2.tool, { ...tool2.args(profiles.slice(at, at + perCall)), dry_run: true });
21024
- if (answer.status !== "quote") return { refusal: answer };
21025
- total += answer.quote ?? 0;
21026
- balance = answer.balance;
21027
- }
21028
- return { quote: total, balance };
21029
- }
21030
- function batchKey(base, args) {
21031
- const hash2 = createHash("sha256").update(JSON.stringify(args)).digest("hex");
21032
- if (!base) return `gtm-file-${hash2.slice(0, 32)}`;
21033
- const key = `${base}-${hash2.slice(0, 16)}`;
21034
- return key.length <= 128 ? key : `gtm-${createHash("sha256").update(key).digest("hex").slice(0, 40)}`;
21035
- }
21036
- function retryKey(key, runId) {
21037
- return `gtm-retry-${createHash("sha256").update(`${key}|${runId}`).digest("hex").slice(0, 40)}`;
21038
- }
21039
- async function runBatches(session, profiles, perCall, budget, tool2, baseKey) {
21040
- const perPerson = tool2.perPerson;
21041
- const batches = [];
21042
- let remaining = budget ?? 0;
21043
- let sent = 0;
21044
- let failedCost = 0;
21045
- let failedRunCost = 0;
21046
- const done = (stop, refusal = null, running = false) => ({ batches, stop, refusal, running, failedCost, failedRunCost });
21047
- const retried = /* @__PURE__ */ new Set();
21048
- while (sent < profiles.length) {
21049
- const size = Math.min(perCall, profiles.length - sent, budget === null ? perCall : Math.floor(remaining / perPerson));
21050
- if (size <= 0) return done({ reason: "over_max_credits", refusal: null });
21051
- const people = profiles.slice(sent, sent + size);
21052
- let key = batchKey(baseKey, tool2.args(people));
21053
- for (; ; ) {
21054
- const first = await session.gateway.call(tool2.tool, {
21055
- ...tool2.args(people),
21056
- ...budget === null ? {} : { max_credits: Math.max(0, remaining) },
21057
- idempotency_key: key
21058
- });
21059
- const answer = await session.settle(first);
21060
- const stopped = (stop) => batches.length || stop.status === "error" ? done({ reason: stop.reason ?? stop.status, refusal: stop }) : done(null, stop);
21061
- if (answer.status === "refused") return stopped(answer);
21062
- const runCost = answer.run_cost ?? answer.cost;
21063
- if (answer.status === "error") {
21064
- failedRunCost += runCost;
21065
- remaining -= runCost;
21066
- if (!first.replayed || !answer.run_id) {
21067
- failedCost += runCost;
21068
- return stopped(answer);
21069
- }
21070
- key = retryKey(key, answer.run_id);
21071
- continue;
21072
- }
21073
- if (answer.reason === "partial_failure" && first.replayed && answer.run_id && !retried.has(key)) {
21074
- retried.add(key);
21075
- failedRunCost += runCost;
21076
- remaining -= runCost;
21077
- key = retryKey(key, answer.run_id);
21078
- continue;
21079
- }
21080
- batches.push({ people, answer, replayed: first.replayed === true, runCost, cost: first.replayed ? 0 : runCost });
21081
- if (answer.status === "running") return done({ reason: "running", refusal: null }, null, true);
21082
- remaining -= runCost;
21083
- break;
21084
- }
21085
- sent += size;
21086
- }
21087
- return done(null);
21088
- }
21089
- async function collectRows(session, batches) {
21090
- let columns = null;
21091
- const perBatch = [];
21092
- for (const batch of batches) {
21093
- const runId = batch.answer.run_id;
21094
- if (!runId) return null;
21095
- const link = await session.gateway.call("gtm_results", { run_id: runId, format: "csv" });
21096
- if (!link.link) return null;
21097
- const [header = [], ...data] = parseCsv(await session.gateway.download(link.link));
21098
- const named = header.filter(Boolean);
21099
- if (named.length) columns = [.../* @__PURE__ */ new Set([...columns ?? [], ...named])];
21100
- perBatch.push(data.map((cells) => Object.fromEntries(named.map((name, i) => [name, cells[i] ? cells[i] : null]))));
21101
- }
21102
- const all = columns ?? DEFAULT_COLUMNS;
21103
- const rows = batches.flatMap((batch, i) => perBatch[i].length ? perBatch[i] : batch.people.map((person) => ({ ...Object.fromEntries(all.map((name) => [name, null])), ...profileOf(person) ? { url: person } : namePair(person), status: batch.answer.status === "error" ? "error" : "not_found" })));
21104
- return { columns: all, rows: rows.map((row) => Object.fromEntries(all.map((name) => [name, row[name] ?? null]))) };
21105
- }
21106
- async function writeOut(session, path, table) {
21107
- await session.io.writeFile(path, toCsv([table.columns, ...table.rows.map((row) => table.columns.map((name) => row[name] ?? ""))]));
21108
- }
21109
23094
  async function finish(session, command, answer, batches, fields) {
21110
23095
  if (command.out && answer.status === "running") return session.emit(answer, { ...fields, out: NOT_WRITTEN_RUNNING });
21111
23096
  if (!command.out || answer.status === "refused" || answer.status === "error" || answer.status === "quote") return session.emit(answer, fields);
21112
- const table = batches ? await collectRows(session, batches) : await runRows(session, answer);
23097
+ const table = batches ? await collectRows(session, batches, FILE_ROW_FALLBACK) : await runRows(session, answer);
21113
23098
  if (!table) return session.emit(answer, { ...fields, out: "not written: CSV links are unavailable" });
21114
23099
  await writeOut(session, command.out, table);
21115
23100
  return session.emit({ ...answer, next: ACCOUNT_NEXT }, { ...fields, out: command.out });
21116
23101
  }
21117
23102
  async function runRows(session, answer) {
21118
23103
  if (!answer.run_id) return null;
21119
- return collectRows(session, [{ people: [], answer, replayed: false, runCost: 0, cost: 0 }]);
23104
+ return collectRows(session, [{ people: [], answer, replayed: false, runCost: 0, cost: 0 }], FILE_ROW_FALLBACK);
21120
23105
  }
21121
23106
  var STOP_WORDS = {
21122
23107
  over_agent_cap: "this agent's cap",
@@ -21126,18 +23111,16 @@ var STOP_WORDS = {
21126
23111
  };
21127
23112
  async function combined(session, command, run, total, budget, rerun, fileFields) {
21128
23113
  const { batches, stop } = run;
21129
- const failed2 = stop?.refusal?.status === "error" ? stop.refusal : null;
21130
23114
  const sent = batches.reduce((sum, batch) => sum + batch.people.length, 0);
21131
- const cost = batches.reduce((sum, batch) => sum + batch.cost, run.failedCost);
21132
- const runCost = batches.reduce((sum, batch) => sum + batch.runCost, run.failedRunCost);
21133
23115
  const runIds = batches.map((batch) => batch.answer.run_id).filter((id) => !!id);
21134
- const balance = (failed2 ?? batches.at(-1)?.answer)?.balance ?? null;
21135
- const table = run.running ? null : await collectRows(session, batches);
23116
+ const table = run.running ? null : await collectRows(session, batches, FILE_ROW_FALLBACK);
21136
23117
  if (table && command.out) await writeOut(session, command.out, table);
21137
23118
  const unsent = total - sent;
21138
23119
  const emails = table?.rows.filter((row) => row.email).length ?? 0;
21139
23120
  const phones = table?.rows.filter((row) => row.phone).length ?? 0;
21140
23121
  const found = table?.rows.filter((row) => row.status === "found").length ?? 0;
23122
+ const outcome = batchOutcome(run, found, table !== null);
23123
+ const { failed: failed2, status, cost, runCost, balance } = outcome;
21141
23124
  const find = command.args.find ?? ["email"];
21142
23125
  const wantsEmail = find.includes("email");
21143
23126
  const wantsPhone = find.includes("phone");
@@ -21159,7 +23142,6 @@ async function combined(session, command, run, total, budget, rerun, fileFields)
21159
23142
  }
21160
23143
  const previewColumns = batches.find((batch) => batch.answer.columns.length)?.answer.columns ?? ["name", "email", "verdict"];
21161
23144
  const rows = table?.rows ?? batches.flatMap((batch) => batch.answer.rows.map((cells) => Object.fromEntries(batch.answer.columns.map((name, i) => [name, cells[i] ?? null]))));
21162
- const status = failed2 ? "error" : run.running ? "running" : found || !table ? "completed" : "not_found";
21163
23145
  const budgetFlag = budget === null ? {} : { max_credits: budget };
21164
23146
  const next = failed2 || run.running ? rerun(budgetFlag) : command.out && table ? ACCOUNT_NEXT : table ? rerun({ ...budgetFlag, out: `${command.file.replace(/\.csv$/i, "")}-contacts.csv` }) : { tool: "gtm_results", args: { run_id: runIds.at(-1) } };
21165
23147
  const answer = shapeAnswer({
@@ -21174,7 +23156,7 @@ async function combined(session, command, run, total, budget, rerun, fileFields)
21174
23156
  columns: previewColumns,
21175
23157
  rows,
21176
23158
  next,
21177
- ...stop && !run.running ? { reason: stop.reason } : {},
23159
+ ...outcome.reason,
21178
23160
  ...batches.length && batches.every((batch) => batch.replayed) ? { replayed: true } : {}
21179
23161
  });
21180
23162
  const fields = {
@@ -21184,11 +23166,10 @@ async function combined(session, command, run, total, budget, rerun, fileFields)
21184
23166
  unsent: unsent || void 0,
21185
23167
  out: command.out ? table ? command.out : run.running ? NOT_WRITTEN_RUNNING : "not written: CSV links are unavailable" : void 0
21186
23168
  };
21187
- return session.emit(answer, fields, stop && !run.running && !failed2 ? { exit: 3 } : {});
23169
+ return session.emit(answer, fields, outcome.emitOptions);
21188
23170
  }
21189
23171
 
21190
23172
  // src/tools-file.ts
21191
- import { createHash as createHash2 } from "node:crypto";
21192
23173
  var plural2 = (n2, one, many = `${one}s`) => `${n2} ${n2 === 1 ? one : many}`;
21193
23174
  async function toolFile(session, command) {
21194
23175
  const definition = CAPABILITIES[command.capability];
@@ -21251,26 +23232,15 @@ async function toolFile(session, command) {
21251
23232
  }), fileFields);
21252
23233
  }
21253
23234
  const sent = run.batches.reduce((sum, batch) => sum + batch.people.length, 0);
21254
- let cost = run.batches.reduce((sum, batch) => sum + batch.cost, run.failedCost);
21255
- let runCost = run.batches.reduce((sum, batch) => sum + batch.runCost, run.failedRunCost);
21256
- const runIds = run.batches.map((batch) => batch.answer.run_id).filter((id) => !!id);
21257
- const table = run.running ? null : await collectRows(session, run.batches);
21258
- const errored = table?.rows.filter((row) => row.status === "error" && row.url).map((row) => row.url) ?? [];
21259
- if (table && errored.length && !run.stop) {
21260
- const left = maxCredits === void 0 ? null : Math.max(0, maxCredits - runCost);
21261
- const retry = await runBatches(session, errored, perCall, left, tool2, `gtm-retry-${createHash2("sha256").update(runIds.join(",")).digest("hex").slice(0, 32)}`);
21262
- const again = retry.batches.length && !retry.running ? await collectRows(session, retry.batches) : null;
21263
- const byUrl = new Map(again?.rows.map((row) => [row.url, row]) ?? []);
21264
- table.rows = table.rows.map((row) => row.status === "error" && byUrl.has(row.url) ? { ...row, ...byUrl.get(row.url) } : row);
21265
- cost += retry.batches.reduce((sum, batch) => sum + batch.cost, retry.failedCost);
21266
- runCost += retry.batches.reduce((sum, batch) => sum + batch.runCost, retry.failedRunCost);
21267
- runIds.push(...retry.batches.map((batch) => batch.answer.run_id).filter((id) => !!id));
21268
- }
23235
+ const table = run.running ? null : await collectRows(session, run.batches, FILE_ROW_FALLBACK);
23236
+ if (table) await recoverErroredRows(session, run, table, perCall, tool2, maxCredits === void 0 ? null : Math.max(0, maxCredits - batchOutcome(run, 0, false).runCost));
23237
+ const runIds = runIdsOf(run);
21269
23238
  if (table && command.out) await writeOut(session, command.out, table);
21270
23239
  const found = table?.rows.filter((row) => row.status === "found").length ?? 0;
21271
23240
  const stillFailed = table?.rows.filter((row) => row.status === "error").length ?? 0;
21272
23241
  const unsent = list.profiles.length - sent;
21273
- const failed2 = run.stop?.refusal?.status === "error" ? run.stop.refusal : null;
23242
+ const outcome = batchOutcome(run, found, table !== null);
23243
+ const { failed: failed2, cost, runCost } = outcome;
21274
23244
  const noun = definition.noun;
21275
23245
  const summary = run.running ? `Batch ${run.batches.length} is still running after ${sent} of ${people}; rerun this command to wait and continue.` : failed2 ? `Stopped after ${sent} of ${people}, ${unsent} not sent: ${failed2.summary}` : run.stop ? `Stopped after ${sent} of ${people} (${run.stop.refusal?.summary ?? "budget reached"}); found ${plural2(found, noun.replace(/s$/, ""), noun)} so far.` : `Found ${found} of ${plural2(sent, noun.replace(/s$/, ""), noun)} across ${plural2(run.batches.length, "batch", "batches")}; ${cost ? `${plural2(cost, "credit")} charged` : "nothing was charged"}${sent - found - stillFailed ? `, misses free` : ""}${stillFailed ? `; ${stillFailed} failed twice, so rerun later for them` : ""}.`;
21276
23246
  const columns = run.batches.find((batch) => batch.answer.columns.length)?.answer.columns ?? [...definition.preview, "status"];
@@ -21278,18 +23248,18 @@ async function toolFile(session, command) {
21278
23248
  const budgetFlag = maxCredits === void 0 ? {} : { max_credits: maxCredits };
21279
23249
  const next = failed2 || run.running || run.stop ? rerun(budgetFlag) : command.out && table ? ACCOUNT_NEXT : table ? rerun({ ...budgetFlag, out: `${command.file.replace(/\.csv$/i, "")}-${command.capability}.csv` }) : { tool: "gtm_results", args: { run_id: runIds.at(-1) } };
21280
23250
  const answer = shapeAnswer({
21281
- status: failed2 ? "error" : run.running ? "running" : found || !table ? "completed" : "not_found",
23251
+ status: outcome.status,
21282
23252
  summary,
21283
23253
  run_id: runIds.length === 1 ? runIds[0] : null,
21284
23254
  cost,
21285
23255
  run_cost: runCost,
21286
- balance: (failed2 ?? run.batches.at(-1)?.answer)?.balance ?? null,
23256
+ balance: outcome.balance,
21287
23257
  total: table?.rows.length ?? sent,
21288
23258
  label: noun,
21289
23259
  columns,
21290
23260
  rows,
21291
23261
  next,
21292
- ...run.stop && !run.running ? { reason: run.stop.reason } : {},
23262
+ ...outcome.reason,
21293
23263
  ...run.batches.every((batch) => batch.replayed) ? { replayed: true } : {}
21294
23264
  });
21295
23265
  return session.emit(answer, {
@@ -21298,27 +23268,49 @@ async function toolFile(session, command) {
21298
23268
  run_ids: runIds.length > 1 ? runIds : void 0,
21299
23269
  unsent: unsent || void 0,
21300
23270
  out: command.out ? table ? command.out : "not written: still running" : void 0
21301
- }, run.stop && !run.running && !failed2 ? { exit: 3 } : {});
23271
+ }, outcome.emitOptions);
21302
23272
  }
21303
23273
 
21304
23274
  // src/gateway.ts
21305
23275
  import { randomUUID } from "node:crypto";
21306
23276
 
21307
23277
  // src/version.ts
21308
- var VERSION = "0.1.5";
23278
+ var VERSION = "0.1.7";
21309
23279
 
21310
23280
  // src/gateway.ts
21311
23281
  var CliError = class extends Error {
21312
- constructor(reason, message) {
23282
+ /**
23283
+ * Whether running the same command again is safe and can succeed: true for
23284
+ * a failure of a call that changes nothing or carries an idempotency key
23285
+ * (network loss, server errors, rate limits); false when the failure is
23286
+ * the caller's to fix (sign in, scope, request size) or the call was not
23287
+ * replay-safe.
23288
+ */
23289
+ constructor(reason, message, replayable = false) {
21313
23290
  super(message);
21314
23291
  this.reason = reason;
23292
+ this.replayable = replayable;
21315
23293
  }
21316
23294
  reason;
23295
+ replayable;
21317
23296
  name = "CliError";
21318
23297
  };
23298
+ function nextStep(attempt, replay, tried) {
23299
+ if (attempt.kind === "dropped") {
23300
+ return replay === "safe" && tried.failed < TRANSIENT_RETRIES ? { kind: "wait_and_resend", seconds: 2 ** (tried.failed + 1), counter: "failed" } : { kind: "give_up" };
23301
+ }
23302
+ const { response } = attempt;
23303
+ if (response.status === 429 && tried.limited < RATE_LIMIT_RETRIES) {
23304
+ return { kind: "wait_and_resend", seconds: Math.min(60, Math.max(1, Number(response.headers.get("retry-after")) || 5)), counter: "limited" };
23305
+ }
23306
+ if (replay === "safe" && TRANSIENT_STATUSES.has(response.status) && tried.failed < TRANSIENT_RETRIES) {
23307
+ return { kind: "wait_and_resend", seconds: 2 ** (tried.failed + 1), counter: "failed" };
23308
+ }
23309
+ return { kind: "return" };
23310
+ }
21319
23311
  var CLIENT_ID = "gtm-cli";
21320
23312
  var DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
21321
- var DEFAULT_PEOPLE_PER_CALL = 100;
23313
+ var DEFAULT_PEOPLE_PER_CALL = MAX_BATCH_PEOPLE;
21322
23314
  var RATE_LIMIT_RETRIES = 3;
21323
23315
  var TRANSIENT_RETRIES = 3;
21324
23316
  var TRANSIENT_STATUSES = /* @__PURE__ */ new Set([500, 502, 503, 504]);
@@ -21340,11 +23332,13 @@ var Gateway = class {
21340
23332
  async call(tool2, args) {
21341
23333
  if (!this.token) throw new CliError("not_signed_in", "Not signed in; run gtm login.");
21342
23334
  const ownKey = args.max_credits !== void 0 && args.dry_run !== true && args.idempotency_key === void 0 ? `gtm-${randomUUID()}` : null;
23335
+ const keyed = ownKey !== null || args.idempotency_key !== void 0;
23336
+ const replay = keyed || args.dry_run === true || args.max_credits === void 0 ? "safe" : "once";
21343
23337
  const { response, resent } = await this.send(`/v1/agent/tools/${tool2}`, {
21344
23338
  method: "POST",
21345
23339
  headers: { authorization: `Bearer ${this.token}`, "content-type": "application/json", accept: "application/json" },
21346
23340
  body: JSON.stringify(ownKey ? { ...args, idempotency_key: ownKey } : args)
21347
- });
23341
+ }, replay);
21348
23342
  if (!response.ok) throw await this.failure(response);
21349
23343
  let body;
21350
23344
  try {
@@ -21363,7 +23357,7 @@ var Gateway = class {
21363
23357
  /** Most people one gtm_find_contacts call accepts, read from the gateway's tool definitions. */
21364
23358
  async peoplePerCall() {
21365
23359
  if (this.peopleLimit !== null) return this.peopleLimit;
21366
- const response = await this.request("/v1/agent/tools", { headers: { accept: "application/json" } });
23360
+ const response = await this.request("/v1/agent/tools", { headers: { accept: "application/json" } }, "safe");
21367
23361
  if (!response.ok) throw await this.failure(response);
21368
23362
  const body = await response.json().catch(() => null);
21369
23363
  const max = body?.tools?.find((tool2) => tool2.name === "gtm_find_contacts")?.inputSchema?.properties?.people?.maxItems;
@@ -21381,15 +23375,15 @@ var Gateway = class {
21381
23375
  if (url2.protocol !== "https:" && url2.protocol !== "http:") throw new CliError("export_failed", "The CSV link was not a web address.");
21382
23376
  let response;
21383
23377
  try {
21384
- ({ response } = await this.send(url2.toString(), { headers: { accept: "text/csv" } }));
23378
+ ({ response } = await this.send(url2.toString(), { headers: { accept: "text/csv" } }, "safe"));
21385
23379
  } catch {
21386
- throw new CliError("network", `Could not reach ${url2.origin} to download the CSV.`);
23380
+ throw new CliError("network", `Could not reach ${url2.origin} to download the CSV.`, true);
21387
23381
  }
21388
23382
  if (!response.ok) throw new CliError("export_failed", "The CSV download failed; ask for a fresh link with gtm results.");
21389
23383
  return response.text();
21390
23384
  }
21391
23385
  async startDevice() {
21392
- const response = await this.request("/oauth/device_authorization", form({ client_id: CLIENT_ID, scope: "gtm:read gtm:run" }));
23386
+ const response = await this.request("/oauth/device_authorization", form({ client_id: CLIENT_ID, scope: AGENT_SCOPES.join(" ") }), "safe");
21393
23387
  if (!response.ok) throw await this.failure(response);
21394
23388
  const body = await response.json().catch(() => null);
21395
23389
  if (!body || typeof body.device_code !== "string" || typeof body.user_code !== "string" || typeof body.verification_uri_complete !== "string") {
@@ -21398,49 +23392,37 @@ var Gateway = class {
21398
23392
  return { device_code: body.device_code, user_code: body.user_code, verification_uri_complete: body.verification_uri_complete, expires_in: Number(body.expires_in) || 900, interval: Number(body.interval) || 5 };
21399
23393
  }
21400
23394
  async pollDevice(deviceCode) {
21401
- const response = await this.request("/oauth/token", form({ grant_type: DEVICE_GRANT, device_code: deviceCode, client_id: CLIENT_ID }));
23395
+ const response = await this.request("/oauth/token", form({ grant_type: DEVICE_GRANT, device_code: deviceCode, client_id: CLIENT_ID }), "safe");
21402
23396
  const body = await response.json().catch(() => null);
21403
23397
  if (response.ok && typeof body?.access_token === "string") return { kind: "token", token: body.access_token, scope: typeof body.scope === "string" ? body.scope : "" };
21404
23398
  if (response.status === 404) throw await this.failure(response);
21405
23399
  return { kind: "wait", error: typeof body?.error === "string" ? body.error : "server_error" };
21406
23400
  }
21407
- async request(path, init) {
21408
- return (await this.send(path, init)).response;
23401
+ async request(path, init, replay) {
23402
+ return (await this.send(path, init, replay)).response;
21409
23403
  }
21410
23404
  /**
21411
- * Fetch with the user agent. Rate limits, which the gateway answers before
21412
- * doing any work, wait and resend; dropped connections and 5xx answers
21413
- * resend after a short backoff. `resent` says whether the answer came from
21414
- * a later attempt. A path is relative to the API; a full URL is a CSV link.
23405
+ * Fetch with the user agent, recovered by `nextStep` alone. `resent` says
23406
+ * whether the answer came from a later attempt. A path is relative to the
23407
+ * API; a full URL is a CSV link.
21415
23408
  */
21416
- async send(path, init) {
23409
+ async send(path, init, replay) {
21417
23410
  const url2 = /^https?:/.test(path) ? path : `${this.apiUrl}${path}`;
21418
- let limited = 0;
21419
- let failed2 = 0;
23411
+ const tried = { limited: 0, failed: 0 };
21420
23412
  for (; ; ) {
21421
- const resent = limited + failed2 > 0;
21422
- let response;
23413
+ const resent = tried.limited + tried.failed > 0;
23414
+ let attempt;
21423
23415
  try {
21424
- response = await this.io.fetch(url2, { ...init, headers: { ...init.headers, "user-agent": `gtmmaxing-cli/${VERSION}` } });
23416
+ attempt = { kind: "answered", response: await this.io.fetch(url2, { ...init, headers: { ...init.headers, "user-agent": `gtmmaxing-cli/${VERSION}` } }) };
21425
23417
  } catch {
21426
- if (failed2 >= TRANSIENT_RETRIES) throw new CliError("network", `Could not reach ${this.apiUrl}; check the connection or --api-url.`);
21427
- failed2 += 1;
21428
- await this.io.sleep(2 ** failed2 * 1e3);
21429
- continue;
23418
+ attempt = { kind: "dropped" };
21430
23419
  }
21431
- if (response.status === 429 && limited < RATE_LIMIT_RETRIES) {
21432
- limited += 1;
21433
- await response.body?.cancel();
21434
- await this.io.sleep(Math.min(60, Math.max(1, Number(response.headers.get("retry-after")) || 5)) * 1e3);
21435
- continue;
21436
- }
21437
- if (TRANSIENT_STATUSES.has(response.status) && failed2 < TRANSIENT_RETRIES) {
21438
- failed2 += 1;
21439
- await response.body?.cancel();
21440
- await this.io.sleep(2 ** failed2 * 1e3);
21441
- continue;
21442
- }
21443
- return { response, resent };
23420
+ const step = nextStep(attempt, replay, tried);
23421
+ if (step.kind === "give_up") throw new CliError("network", `Could not reach ${this.apiUrl}; check the connection or --api-url.`, replay === "safe");
23422
+ if (step.kind === "return") return { response: attempt.response, resent };
23423
+ tried[step.counter] += 1;
23424
+ if (attempt.kind === "answered") await attempt.response.body?.cancel();
23425
+ await this.io.sleep(step.seconds * 1e3);
21444
23426
  }
21445
23427
  }
21446
23428
  async failure(response) {
@@ -21456,9 +23438,9 @@ var Gateway = class {
21456
23438
  case 413:
21457
23439
  return new CliError("request_too_large", "That request is too large; send fewer people per call.");
21458
23440
  case 429:
21459
- return new CliError("rate_limited", "Too many requests; wait a minute and run the same command again.");
23441
+ return new CliError("rate_limited", "Too many requests; wait a minute and run the same command again.", true);
21460
23442
  default:
21461
- return new CliError("server_error", `GTMMAXING answered ${response.status}; try again shortly.`);
23443
+ return new CliError("server_error", `GTMMAXING answered ${response.status}; try again shortly.`, response.status >= 500);
21462
23444
  }
21463
23445
  }
21464
23446
  };
@@ -21466,6 +23448,63 @@ function form(fields) {
21466
23448
  return { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" }, body: new URLSearchParams(fields).toString() };
21467
23449
  }
21468
23450
 
23451
+ // ../shared/src/base-rpc.ts
23452
+ var BASE_RPC_URLS = ["https://base-rpc.publicnode.com", "https://gateway.tenderly.co/public/base"];
23453
+
23454
+ // ../shared/src/topology.ts
23455
+ var API_ORIGINS = { origin: "https://api.gtmmaxing.com", workersOrigin: "https://found-api.bhaisahbsahb.workers.dev" };
23456
+ var TELEMETRY_ROUTES = { collect: "/__client-errors", script: "/__client-errors.js" };
23457
+
23458
+ // ../shared/src/deployment.ts
23459
+ var DEPLOYMENT = {
23460
+ web: {
23461
+ origin: "https://gtmmaxing.com",
23462
+ legacyOrigins: ["https://www.gtmmaxing.com", "https://gtm.getbags.app"],
23463
+ pagesOrigin: "https://found-web.pages.dev",
23464
+ redirects: "/admin /admin/ 301\n/e/* /event/ 200\n"
23465
+ },
23466
+ api: API_ORIGINS,
23467
+ traction: { origin: "https://traction.gtmmaxing.com", pagesOrigin: "https://found-traction.pages.dev" },
23468
+ corsOrigins: ["https://gtmmaxing.com", "https://gtm.getbags.app", "https://found-web.pages.dev", "http://localhost:4321", "http://127.0.0.1:4321", "http://localhost:4322", "http://127.0.0.1:4322"],
23469
+ database: { binding: "DB", database_name: "found-lookup-db", database_id: "f8656765-79e1-4164-8c35-18108946c936" },
23470
+ telemetry: TELEMETRY_ROUTES,
23471
+ agentGateway: { webFlag: "PUBLIC_AGENT_GATEWAY", webValue: "1", runtimeFlag: "AGENT_GATEWAY_ENABLED", runtimeValue: "true" },
23472
+ cache: { productionMode: "live", namespacePrefix: "mode:", historicalLiveNamespace: "mode:live:blitz" },
23473
+ keeper: {
23474
+ crons: ["0 * * * *"],
23475
+ rpcUrls: BASE_RPC_URLS,
23476
+ scheduled: { swap: true, margin: 0n }
23477
+ },
23478
+ verification: [
23479
+ { directory: "web", name: "web", typecheck: "check", lint: "lint", test: "test" },
23480
+ { directory: "internal", name: "@found/internal", typecheck: "check", lint: "lint", test: "test" },
23481
+ { directory: "api", name: "@found/api", typecheck: "typecheck", lint: "lint", test: "test" },
23482
+ { directory: "packages/cli", name: "gtmmaxing", typecheck: "typecheck", lint: "lint", test: "test" },
23483
+ { directory: "packages/tjar-keeper", name: "@found/tjar-keeper", typecheck: "typecheck", lint: "lint", test: "test" },
23484
+ { directory: "packages/results-view", name: "@found/results-view", lint: "lint" }
23485
+ ]
23486
+ };
23487
+ function validateDeployment(model) {
23488
+ for (const origin of [model.web.origin, model.web.pagesOrigin, ...model.web.legacyOrigins, ...Object.values(model.api), ...Object.values(model.traction), ...model.corsOrigins]) {
23489
+ if (new URL(origin).origin !== origin) throw new Error(`Expected an origin: ${origin}`);
23490
+ }
23491
+ if (!model.corsOrigins.includes(model.web.origin)) throw new Error("CORS must allow the canonical web origin");
23492
+ if (!["0", "1"].includes(model.agentGateway.webValue) || !["false", "true"].includes(model.agentGateway.runtimeValue)) throw new Error("Invalid agent gateway flag value");
23493
+ if (model.agentGateway.webValue === "1" !== (model.agentGateway.runtimeValue === "true")) throw new Error("Agent gateway build/runtime flags disagree");
23494
+ if (new Set(model.verification.map(({ directory }) => directory)).size !== model.verification.length) throw new Error("Duplicate verification workspace");
23495
+ if (!/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/.test(model.database.database_id)) throw new Error("Invalid database identity");
23496
+ }
23497
+ validateDeployment(DEPLOYMENT);
23498
+
23499
+ // ../shared/src/agent-setup.ts
23500
+ var CONNECTOR_URL = `${DEPLOYMENT.web.origin}/mcp`;
23501
+ var CODEX_MCP_COMMAND = `codex mcp add gtmmaxing --url ${CONNECTOR_URL}`;
23502
+ var CLAUDE_CODE_HEADERS_HELPER = "gtm auth-header";
23503
+ var CLAUDE_CODE_COMMAND = `claude mcp add-json --scope user gtmmaxing '${JSON.stringify({ type: "http", url: CONNECTOR_URL, headersHelper: CLAUDE_CODE_HEADERS_HELPER })}'`;
23504
+ var CLAUDE_CODE_OAUTH_COMMAND = `claude mcp add --scope user --transport http gtmmaxing ${CONNECTOR_URL}`;
23505
+ var FIRST_AGENT_JOB_TEXT = "Find 5 heads of sales at companies like mine and get their verified work emails. Spend up to 25 credits.";
23506
+ var FIRST_AGENT_JOB = `Use GTMMAXING to ${FIRST_AGENT_JOB_TEXT[0].toLowerCase()}${FIRST_AGENT_JOB_TEXT.slice(1)}`;
23507
+
21469
23508
  // src/help.ts
21470
23509
  var PAID2 = [
21471
23510
  " --max-credits N Most credits this command may spend; paid commands refuse to run without it",
@@ -21476,7 +23515,7 @@ var COMMON = [
21476
23515
  " --json Print JSON instead of TOON text",
21477
23516
  " --no-wait Answer with the run id instead of waiting for a running job",
21478
23517
  " --timeout SECONDS How long to wait for a running job (default 900)",
21479
- " --api-url URL GTMMAXING API (default https://api.gtmmaxing.com, or GTM_API_URL)"
23518
+ ` --api-url URL GTMMAXING API (default ${DEPLOYMENT.api.origin}, or GTM_API_URL)`
21480
23519
  ];
21481
23520
  var tool = (name) => `${OUTCOME_TOOLS[name].description} (Agent tool: ${name}.)`;
21482
23521
  var TOPICS = {
@@ -21500,7 +23539,7 @@ var TOPICS = {
21500
23539
  "",
21501
23540
  `Prints {"Authorization":"Bearer <token>"} for an MCP client's header helper, so the GTMMAXING MCP connection`,
21502
23541
  "reuses this CLI login (same agent, same credit cap) instead of a second sign-in. For Claude Code:",
21503
- ` claude mcp add-json --scope user gtmmaxing '{"type":"http","url":"https://gtmmaxing.com/mcp","headersHelper":"gtm auth-header"}'`,
23542
+ ` ${CLAUDE_CODE_COMMAND}`,
21504
23543
  "When run as a helper, the token is printed only for a GTMMAXING server. Exits 1 when signed out."
21505
23544
  ]
21506
23545
  },
@@ -21527,7 +23566,7 @@ var TOPICS = {
21527
23566
  "A file runs in batches that share one --max-credits budget: each batch is sized so its most expensive",
21528
23567
  "outcome fits what is left, and the CLI stops before the budget would be exceeded, reporting what was not sent.",
21529
23568
  "Rerunning the same file replays batches that already ran, for free; pass --idempotency-key to start fresh.",
21530
- "Profiles on the command line go in one call; use --file for more than 100."
23569
+ `Profiles on the command line go in one call; use --file for more than ${MAX_BATCH_PEOPLE}.`
21531
23570
  ]
21532
23571
  },
21533
23572
  list: {
@@ -21786,6 +23825,102 @@ function sameService(target, apiUrl) {
21786
23825
  return url2.host === api.host || url2.hostname === site && url2.port === api.port;
21787
23826
  }
21788
23827
 
23828
+ // ../contracts/src/polling.ts
23829
+ var FOLLOW_WINDOW_MS = 10 * 6e4;
23830
+ var TOOL_POLL_POLICY = { delayMs: 2e3, maxDurationMs: FOLLOW_WINDOW_MS, errors: "pause" };
23831
+ var EVENT_POLL_POLICY = { ...TOOL_POLL_POLICY, errors: "retry", errorDelayMs: 4e3 };
23832
+ var CLI_POLL_POLICY = { delayMs: 4e3, errors: "pause", acceptLateRead: true };
23833
+ var pollDelay = (policy, attempt) => Math.min(policy.delayMs * (policy.multiplier ?? 1) ** attempt, policy.maxDelayMs ?? Infinity);
23834
+ var MAX_TIMER_MS = 2 ** 31 - 1;
23835
+ function longTimeout(callback, ms) {
23836
+ let timer;
23837
+ const arm = (remaining) => {
23838
+ timer = setTimeout(() => remaining > MAX_TIMER_MS ? arm(remaining - MAX_TIMER_MS) : callback(), Math.min(remaining, MAX_TIMER_MS));
23839
+ };
23840
+ arm(ms);
23841
+ return () => clearTimeout(timer);
23842
+ }
23843
+ async function pollUntil(options) {
23844
+ const { policy, signal, read, isDone } = options;
23845
+ if (!Number.isFinite(policy.maxDurationMs) && !Number.isFinite(policy.maxAttempts)) throw new Error("Polling requires a finite limit.");
23846
+ const now = options.now ?? Date.now;
23847
+ const deadline = now() + (policy.maxDurationMs ?? Infinity);
23848
+ let value = options.initial;
23849
+ let error61;
23850
+ let attempts = 0;
23851
+ let delayIndex = 0;
23852
+ let immediate = options.immediate ?? value === void 0;
23853
+ let failed2 = false;
23854
+ let stop;
23855
+ let cancelDeadline;
23856
+ let sleepTimer;
23857
+ let interrupt;
23858
+ const interrupted = new Promise((resolve) => {
23859
+ interrupt = () => resolve({ interrupted: true });
23860
+ });
23861
+ const abort = () => {
23862
+ stop = "cancelled";
23863
+ interrupt();
23864
+ };
23865
+ signal?.addEventListener("abort", abort, { once: true });
23866
+ if (signal?.aborted) abort();
23867
+ const acceptLate = policy.acceptLateRead === true;
23868
+ if (policy.maxDurationMs !== void 0 && !acceptLate) cancelDeadline = longTimeout(() => {
23869
+ stop = "limit";
23870
+ interrupt();
23871
+ }, policy.maxDurationMs);
23872
+ const result = (reason) => ({ reason, value, ...error61 === void 0 ? {} : { error: error61 } });
23873
+ try {
23874
+ for (; ; ) {
23875
+ if (stop) return result(stop);
23876
+ if (value !== void 0 && isDone(value)) return result("settled");
23877
+ if (policy.maxDurationMs !== void 0 && policy.maxDurationMs <= 0) return result("limit");
23878
+ if (attempts >= (policy.maxAttempts ?? Infinity)) return result("limit");
23879
+ if (!immediate) {
23880
+ const delay = failed2 && policy.errorDelayMs !== void 0 ? policy.errorDelayMs : pollDelay(policy, delayIndex);
23881
+ if (now() + delay > deadline) return result("limit");
23882
+ delayIndex += 1;
23883
+ const sleeping = options.sleep ? options.sleep(delay) : new Promise((resolve) => {
23884
+ sleepTimer = setTimeout(resolve, delay);
23885
+ });
23886
+ await Promise.race([sleeping, interrupted]);
23887
+ if (stop) return result(stop);
23888
+ }
23889
+ immediate = false;
23890
+ if (now() > deadline) return result("limit");
23891
+ attempts += 1;
23892
+ const readResult = await Promise.race([
23893
+ Promise.resolve().then(async () => {
23894
+ if (stop) return { kind: "interrupted" };
23895
+ try {
23896
+ return { kind: "value", value: await read() };
23897
+ } catch (error62) {
23898
+ return { kind: "error", error: error62 };
23899
+ }
23900
+ }),
23901
+ interrupted.then(() => ({ kind: "interrupted" }))
23902
+ ]);
23903
+ if (stop) return result(stop);
23904
+ if (!acceptLate && now() > deadline) return result("limit");
23905
+ if (readResult.kind === "interrupted") return result(stop ?? "cancelled");
23906
+ if (readResult.kind === "error") {
23907
+ error61 = readResult.error;
23908
+ failed2 = true;
23909
+ if (policy.errors === "pause" || options.retryError?.(error61, value) === false) return result("error");
23910
+ } else {
23911
+ value = readResult.value;
23912
+ error61 = void 0;
23913
+ failed2 = false;
23914
+ options.onValue?.(value);
23915
+ }
23916
+ }
23917
+ } finally {
23918
+ cancelDeadline?.();
23919
+ clearTimeout(sleepTimer);
23920
+ signal?.removeEventListener("abort", abort);
23921
+ }
23922
+ }
23923
+
21789
23924
  // src/credentials.ts
21790
23925
  import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
21791
23926
  import { join } from "node:path";
@@ -21819,15 +23954,21 @@ var CredentialStore = class {
21819
23954
  async clearPending() {
21820
23955
  await this.remove("pending-login.json");
21821
23956
  }
23957
+ /**
23958
+ * Absent and damaged files are ordinary "not signed in" answers (null); a
23959
+ * file that exists but cannot be read (permissions, disk) is a failure the
23960
+ * caller must see, not a silent sign-out.
23961
+ */
21822
23962
  async read(name, valid) {
21823
- let text2;
23963
+ let text4;
21824
23964
  try {
21825
- text2 = await readFile(join(this.dir, name), "utf8");
21826
- } catch {
21827
- return null;
23965
+ text4 = await readFile(join(this.dir, name), "utf8");
23966
+ } catch (error61) {
23967
+ if (isAbsent(error61)) return null;
23968
+ throw new CliError("credentials_unreadable", `Could not read ${join(this.dir, name)}: ${describe3(error61)}. Fix its permissions or remove it, then run gtm login.`);
21828
23969
  }
21829
23970
  try {
21830
- const value = JSON.parse(text2);
23971
+ const value = JSON.parse(text4);
21831
23972
  return value && typeof value === "object" && valid(value) ? value : null;
21832
23973
  } catch {
21833
23974
  return null;
@@ -21846,15 +23987,17 @@ var CredentialStore = class {
21846
23987
  try {
21847
23988
  await rm(join(this.dir, name));
21848
23989
  return true;
21849
- } catch {
21850
- return false;
23990
+ } catch (error61) {
23991
+ if (isAbsent(error61)) return false;
23992
+ throw new CliError("credentials_not_deleted", `Could not delete ${join(this.dir, name)}: ${describe3(error61)}. The saved sign-in is still there; remove the file yourself.`);
21851
23993
  }
21852
23994
  }
21853
23995
  };
23996
+ var isAbsent = (error61) => ["ENOENT", "ENOTDIR"].includes(error61.code ?? "");
23997
+ var describe3 = (error61) => error61 instanceof Error ? error61.message : String(error61);
21854
23998
 
21855
23999
  // src/session.ts
21856
- var DEFAULT_API_URL = "https://api.gtmmaxing.com";
21857
- var POLL_MS = 4e3;
24000
+ var DEFAULT_API_URL = DEPLOYMENT.api.origin;
21858
24001
  var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
21859
24002
  function resolveApiUrl(flag, env, saved) {
21860
24003
  const raw = flag ?? env ?? saved ?? DEFAULT_API_URL;
@@ -21885,10 +24028,13 @@ var Session = class _Session {
21885
24028
  gateway;
21886
24029
  store;
21887
24030
  static async open(io, options) {
21888
- const saved = await new CredentialStore(io.configDir).load();
24031
+ const envToken = io.env.GTM_TOKEN?.trim() || null;
24032
+ const saved = await new CredentialStore(io.configDir).load().catch((error61) => {
24033
+ if (envToken) return null;
24034
+ throw error61;
24035
+ });
21889
24036
  const apiUrl = resolveApiUrl(options.apiUrl, io.env.GTM_API_URL, saved?.api_url);
21890
24037
  const savedToken = saved && resolveApiUrl(void 0, void 0, saved.api_url) === apiUrl ? saved.token : null;
21891
- const envToken = io.env.GTM_TOKEN?.trim() || null;
21892
24038
  return new _Session(io, options, apiUrl, envToken ?? savedToken, envToken ? "env" : savedToken ? "saved" : null);
21893
24039
  }
21894
24040
  /** A session for the same server with a newly issued token. */
@@ -21897,8 +24043,8 @@ var Session = class _Session {
21897
24043
  }
21898
24044
  /** Prints an answer as TOON text or JSON and returns its exit code. */
21899
24045
  emit(answer, fields = {}, options = {}) {
21900
- const text2 = this.options.json ? renderJson(answer, fields) : renderText(answer, fields);
21901
- this.io[options.stream ?? "stdout"](text2);
24046
+ const text4 = this.options.json ? renderJson(answer, fields) : renderText(answer, fields);
24047
+ this.io[options.stream ?? "stdout"](text4);
21902
24048
  return options.exit ?? exitCode(answer);
21903
24049
  }
21904
24050
  async readInput(path, topic) {
@@ -21918,11 +24064,16 @@ var Session = class _Session {
21918
24064
  if (first.status !== "running" || !first.run_id) return first;
21919
24065
  let answer = first;
21920
24066
  if (this.options.wait) {
21921
- const deadline = this.io.now() + this.options.timeoutSeconds * 1e3;
21922
- while (answer.status === "running" && this.io.now() + POLL_MS <= deadline) {
21923
- await this.io.sleep(POLL_MS);
21924
- answer = await this.gateway.call("gtm_results", { run_id: first.run_id });
21925
- }
24067
+ const outcome = await pollUntil({
24068
+ policy: { ...CLI_POLL_POLICY, maxDurationMs: this.options.timeoutSeconds * 1e3 },
24069
+ initial: first,
24070
+ read: () => this.gateway.call("gtm_results", { run_id: first.run_id }),
24071
+ isDone: (value) => value.status !== "running",
24072
+ now: () => this.io.now(),
24073
+ sleep: (ms) => this.io.sleep(ms)
24074
+ });
24075
+ if (outcome.reason === "error") throw outcome.error;
24076
+ answer = outcome.value ?? first;
21926
24077
  }
21927
24078
  if (answer === first) return first;
21928
24079
  if (first.replayed) return { ...answer, replayed: true };
@@ -21956,6 +24107,11 @@ async function runCli(argv, io) {
21956
24107
  session = await Session.open(io, options);
21957
24108
  } catch (error61) {
21958
24109
  if (error61 instanceof UsageError) return usage(io, error61);
24110
+ if (error61 instanceof CliError) {
24111
+ const answer = errorAnswer(error61);
24112
+ io.stdout(options.json ? renderJson(answer, {}) : renderText(answer, {}));
24113
+ return exitCode(answer);
24114
+ }
21959
24115
  throw error61;
21960
24116
  }
21961
24117
  try {
@@ -22067,11 +24223,11 @@ function openUrl(url2) {
22067
24223
  function nodeIo() {
22068
24224
  return {
22069
24225
  env: process.env,
22070
- stdout: (text2) => {
22071
- process.stdout.write(text2);
24226
+ stdout: (text4) => {
24227
+ process.stdout.write(text4);
22072
24228
  },
22073
- stderr: (text2) => {
22074
- process.stderr.write(text2);
24229
+ stderr: (text4) => {
24230
+ process.stderr.write(text4);
22075
24231
  },
22076
24232
  fetch: (input2, init) => fetch(input2, init),
22077
24233
  readFile: (path) => readFile2(path, "utf8"),