gtmmaxing 0.1.5 → 0.1.6

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 +216 -23
  2. package/package.json +1 -1
package/dist/gtm.js CHANGED
@@ -18871,6 +18871,19 @@ function date4(params) {
18871
18871
  return _coercedDate(ZodDate, params);
18872
18872
  }
18873
18873
 
18874
+ // ../contracts/src/lifecycle.ts
18875
+ function defineLifecycle({ states, transitions }) {
18876
+ const can = (from, to) => transitions[from].includes(to);
18877
+ return {
18878
+ states,
18879
+ transitions,
18880
+ can,
18881
+ before: (to) => states.filter((from) => can(from, to)),
18882
+ isTerminal: (state) => transitions[state].length === 0
18883
+ };
18884
+ }
18885
+ var AGENT_RUN_STATUSES = ["running", "completed", "not_found", "error"];
18886
+
18874
18887
  // ../contracts/src/tools.ts
18875
18888
  var TOOL_CATALOG = {
18876
18889
  "seo-aeo-audit": { name: "SEO/AEO audit", credits: 35, unit: "completed audit", limit: 1 },
@@ -18958,10 +18971,27 @@ var toolResultSchema = external_exports.object({
18958
18971
  /** Companies dropped before the rows, by why. */
18959
18972
  left: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).optional()
18960
18973
  });
18974
+ var TOOL_RUN_STATUSES = ["queued", "running", "completed", "not_found", "error", "reconciliation_needed"];
18975
+ var TOOL_RUN_TRANSITIONS = {
18976
+ queued: ["running", "completed", "not_found", "error", "reconciliation_needed"],
18977
+ running: ["completed", "not_found", "error", "reconciliation_needed"],
18978
+ completed: [],
18979
+ not_found: [],
18980
+ error: [],
18981
+ reconciliation_needed: ["error"]
18982
+ };
18983
+ var toolRunLifecycle = defineLifecycle({ states: TOOL_RUN_STATUSES, transitions: TOOL_RUN_TRANSITIONS });
18984
+ var TOOL_CALL_STATUSES = ["submitted", "completed", "expired"];
18985
+ var TOOL_CALL_TRANSITIONS = {
18986
+ submitted: ["completed", "expired"],
18987
+ completed: [],
18988
+ expired: []
18989
+ };
18990
+ var toolCallLifecycle = defineLifecycle({ states: TOOL_CALL_STATUSES, transitions: TOOL_CALL_TRANSITIONS });
18961
18991
  var toolRunSchema = external_exports.object({
18962
18992
  id: external_exports.string(),
18963
18993
  tool: toolIdSchema,
18964
- status: external_exports.enum(["queued", "running", "completed", "not_found", "error", "reconciliation_needed"]),
18994
+ status: external_exports.enum(TOOL_RUN_STATUSES),
18965
18995
  input: toolRequestSchema,
18966
18996
  result: toolResultSchema.nullable(),
18967
18997
  creditsCharged: external_exports.number().int().nonnegative(),
@@ -18972,6 +19002,40 @@ var toolRunSchema = external_exports.object({
18972
19002
  var toolRunResponseSchema = external_exports.object({ run: toolRunSchema, credits: external_exports.number().int().nonnegative() });
18973
19003
  var toolRunsResponseSchema = external_exports.object({ runs: external_exports.array(toolRunSchema), credits: external_exports.number().int().nonnegative() });
18974
19004
 
19005
+ // ../contracts/src/plans.ts
19006
+ var CREDIT_PLANS = [
19007
+ {
19008
+ id: "starter",
19009
+ name: "Starter",
19010
+ monthlyCredits: 2e3,
19011
+ unlimited: false,
19012
+ prices: {
19013
+ monthly: { usd: 30, url: "https://buy.stripe.com/8x214o9aobNr7Tx85v5gc02", linkId: "plink_1UVzDYLFFDNJNkHJJ4fWmieL" },
19014
+ annual: { usd: 300, url: "https://buy.stripe.com/00w5kE4U84kZflZfxX5gc03", linkId: "plink_1UVzFmLFFDNJNkHJbQW9Dy7X" }
19015
+ }
19016
+ },
19017
+ {
19018
+ id: "growth",
19019
+ name: "Growth",
19020
+ monthlyCredits: 4500,
19021
+ unlimited: false,
19022
+ prices: {
19023
+ monthly: { usd: 60, url: "https://buy.stripe.com/3cI28s4U818N6PtbhH5gc04", linkId: "plink_1UVzGELFFDNJNkHJnlfjOxwk" },
19024
+ annual: { usd: 600, url: "https://buy.stripe.com/14A4gAbiw6t78XBadD5gc05", linkId: "plink_1UVzGgLFFDNJNkHJtvftWZKw" }
19025
+ }
19026
+ },
19027
+ {
19028
+ id: "unlimited",
19029
+ name: "Unlimited",
19030
+ monthlyCredits: 1e4,
19031
+ unlimited: true,
19032
+ prices: {
19033
+ monthly: { usd: 129, url: "https://buy.stripe.com/3cI5kEbiw4kZddRetT5gc08", linkId: "plink_1UVzxYLFFDNJNkHJoG37CnPv" },
19034
+ annual: { usd: 1290, url: "https://buy.stripe.com/00w14o3Q4eZDehV4Tj5gc09", linkId: "plink_1UVzyVLFFDNJNkHJbNAsT6il" }
19035
+ }
19036
+ }
19037
+ ];
19038
+
18975
19039
  // ../contracts/src/filters.ts
18976
19040
  var COMPANY_SIZES = ["< 5", "5 - 19", "20 - 99", "100 - 249", "250 - 499", "500 - 999", "1000 - 4999", "5000 - 9999", ">10000"];
18977
19041
  var INDUSTRIES = [
@@ -20225,7 +20289,7 @@ var tableRowsInput = external_exports.object({
20225
20289
  }).strict();
20226
20290
  var tableRowsPageSchema = external_exports.object({
20227
20291
  run_id: external_exports.string(),
20228
- status: external_exports.enum(["running", "completed", "not_found", "error"]),
20292
+ status: external_exports.enum(AGENT_RUN_STATUSES),
20229
20293
  label: external_exports.string(),
20230
20294
  /** The run's preview columns first, then every other field its rows carry. */
20231
20295
  columns: external_exports.array(external_exports.string()),
@@ -20456,6 +20520,23 @@ var usageResponseSchema = external_exports.object({
20456
20520
  errors: external_exports.number().int().nonnegative()
20457
20521
  })
20458
20522
  });
20523
+ var planIdSchema = external_exports.enum(CREDIT_PLANS.map((plan) => plan.id));
20524
+ var billingSchema = external_exports.enum(["monthly", "annual"]);
20525
+ var checkoutPurchaseQuerySchema = external_exports.object({
20526
+ plan: planIdSchema,
20527
+ billing: billingSchema,
20528
+ since: external_exports.coerce.number().int().nonnegative(),
20529
+ /** The browser's clock when it asked, so the API can read `since` on its own clock. */
20530
+ now: external_exports.coerce.number().int().nonnegative()
20531
+ });
20532
+ var checkoutPurchaseResponseSchema = external_exports.object({
20533
+ purchase: external_exports.object({
20534
+ plan: planIdSchema,
20535
+ billing: billingSchema,
20536
+ credits: external_exports.number().int().positive(),
20537
+ creditedAt: external_exports.number().int().nonnegative()
20538
+ }).nullable()
20539
+ });
20459
20540
  var externalErrorSchema = external_exports.object({
20460
20541
  error: external_exports.string(),
20461
20542
  request_id: external_exports.string(),
@@ -20745,6 +20826,20 @@ function commandFor(next) {
20745
20826
  return commandArgv(next).map(shellQuote).join(" ");
20746
20827
  }
20747
20828
 
20829
+ // src/batch-outcome.ts
20830
+ function batchOutcome(run, found, hasTable) {
20831
+ const failed2 = run.stop?.refusal?.status === "error" ? run.stop.refusal : null;
20832
+ return {
20833
+ failed: failed2,
20834
+ status: failed2 ? "error" : run.running ? "running" : found || !hasTable ? "completed" : "not_found",
20835
+ reason: run.stop && !run.running ? { reason: run.stop.reason } : {},
20836
+ emitOptions: run.stop && !run.running && !failed2 ? { exit: 3 } : {},
20837
+ cost: run.batches.reduce((sum, batch) => sum + batch.cost, run.failedCost),
20838
+ runCost: run.batches.reduce((sum, batch) => sum + batch.runCost, run.failedRunCost),
20839
+ balance: (failed2 ?? run.batches.at(-1)?.answer)?.balance ?? null
20840
+ };
20841
+ }
20842
+
20748
20843
  // src/contacts.ts
20749
20844
  import { createHash } from "node:crypto";
20750
20845
 
@@ -21126,18 +21221,16 @@ var STOP_WORDS = {
21126
21221
  };
21127
21222
  async function combined(session, command, run, total, budget, rerun, fileFields) {
21128
21223
  const { batches, stop } = run;
21129
- const failed2 = stop?.refusal?.status === "error" ? stop.refusal : null;
21130
21224
  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
21225
  const runIds = batches.map((batch) => batch.answer.run_id).filter((id) => !!id);
21134
- const balance = (failed2 ?? batches.at(-1)?.answer)?.balance ?? null;
21135
21226
  const table = run.running ? null : await collectRows(session, batches);
21136
21227
  if (table && command.out) await writeOut(session, command.out, table);
21137
21228
  const unsent = total - sent;
21138
21229
  const emails = table?.rows.filter((row) => row.email).length ?? 0;
21139
21230
  const phones = table?.rows.filter((row) => row.phone).length ?? 0;
21140
21231
  const found = table?.rows.filter((row) => row.status === "found").length ?? 0;
21232
+ const outcome = batchOutcome(run, found, table !== null);
21233
+ const { failed: failed2, status, cost, runCost, balance } = outcome;
21141
21234
  const find = command.args.find ?? ["email"];
21142
21235
  const wantsEmail = find.includes("email");
21143
21236
  const wantsPhone = find.includes("phone");
@@ -21159,7 +21252,6 @@ async function combined(session, command, run, total, budget, rerun, fileFields)
21159
21252
  }
21160
21253
  const previewColumns = batches.find((batch) => batch.answer.columns.length)?.answer.columns ?? ["name", "email", "verdict"];
21161
21254
  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
21255
  const budgetFlag = budget === null ? {} : { max_credits: budget };
21164
21256
  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
21257
  const answer = shapeAnswer({
@@ -21174,7 +21266,7 @@ async function combined(session, command, run, total, budget, rerun, fileFields)
21174
21266
  columns: previewColumns,
21175
21267
  rows,
21176
21268
  next,
21177
- ...stop && !run.running ? { reason: stop.reason } : {},
21269
+ ...outcome.reason,
21178
21270
  ...batches.length && batches.every((batch) => batch.replayed) ? { replayed: true } : {}
21179
21271
  });
21180
21272
  const fields = {
@@ -21184,7 +21276,7 @@ async function combined(session, command, run, total, budget, rerun, fileFields)
21184
21276
  unsent: unsent || void 0,
21185
21277
  out: command.out ? table ? command.out : run.running ? NOT_WRITTEN_RUNNING : "not written: CSV links are unavailable" : void 0
21186
21278
  };
21187
- return session.emit(answer, fields, stop && !run.running && !failed2 ? { exit: 3 } : {});
21279
+ return session.emit(answer, fields, outcome.emitOptions);
21188
21280
  }
21189
21281
 
21190
21282
  // src/tools-file.ts
@@ -21251,8 +21343,7 @@ async function toolFile(session, command) {
21251
21343
  }), fileFields);
21252
21344
  }
21253
21345
  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);
21346
+ let { cost, runCost } = batchOutcome(run, 0, false);
21256
21347
  const runIds = run.batches.map((batch) => batch.answer.run_id).filter((id) => !!id);
21257
21348
  const table = run.running ? null : await collectRows(session, run.batches);
21258
21349
  const errored = table?.rows.filter((row) => row.status === "error" && row.url).map((row) => row.url) ?? [];
@@ -21270,7 +21361,8 @@ async function toolFile(session, command) {
21270
21361
  const found = table?.rows.filter((row) => row.status === "found").length ?? 0;
21271
21362
  const stillFailed = table?.rows.filter((row) => row.status === "error").length ?? 0;
21272
21363
  const unsent = list.profiles.length - sent;
21273
- const failed2 = run.stop?.refusal?.status === "error" ? run.stop.refusal : null;
21364
+ const outcome = batchOutcome(run, found, table !== null);
21365
+ const { failed: failed2 } = outcome;
21274
21366
  const noun = definition.noun;
21275
21367
  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
21368
  const columns = run.batches.find((batch) => batch.answer.columns.length)?.answer.columns ?? [...definition.preview, "status"];
@@ -21278,18 +21370,18 @@ async function toolFile(session, command) {
21278
21370
  const budgetFlag = maxCredits === void 0 ? {} : { max_credits: maxCredits };
21279
21371
  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
21372
  const answer = shapeAnswer({
21281
- status: failed2 ? "error" : run.running ? "running" : found || !table ? "completed" : "not_found",
21373
+ status: outcome.status,
21282
21374
  summary,
21283
21375
  run_id: runIds.length === 1 ? runIds[0] : null,
21284
21376
  cost,
21285
21377
  run_cost: runCost,
21286
- balance: (failed2 ?? run.batches.at(-1)?.answer)?.balance ?? null,
21378
+ balance: outcome.balance,
21287
21379
  total: table?.rows.length ?? sent,
21288
21380
  label: noun,
21289
21381
  columns,
21290
21382
  rows,
21291
21383
  next,
21292
- ...run.stop && !run.running ? { reason: run.stop.reason } : {},
21384
+ ...outcome.reason,
21293
21385
  ...run.batches.every((batch) => batch.replayed) ? { replayed: true } : {}
21294
21386
  });
21295
21387
  return session.emit(answer, {
@@ -21298,14 +21390,14 @@ async function toolFile(session, command) {
21298
21390
  run_ids: runIds.length > 1 ? runIds : void 0,
21299
21391
  unsent: unsent || void 0,
21300
21392
  out: command.out ? table ? command.out : "not written: still running" : void 0
21301
- }, run.stop && !run.running && !failed2 ? { exit: 3 } : {});
21393
+ }, outcome.emitOptions);
21302
21394
  }
21303
21395
 
21304
21396
  // src/gateway.ts
21305
21397
  import { randomUUID } from "node:crypto";
21306
21398
 
21307
21399
  // src/version.ts
21308
- var VERSION = "0.1.5";
21400
+ var VERSION = "0.1.6";
21309
21401
 
21310
21402
  // src/gateway.ts
21311
21403
  var CliError = class extends Error {
@@ -21786,6 +21878,102 @@ function sameService(target, apiUrl) {
21786
21878
  return url2.host === api.host || url2.hostname === site && url2.port === api.port;
21787
21879
  }
21788
21880
 
21881
+ // ../contracts/src/polling.ts
21882
+ var FOLLOW_WINDOW_MS = 10 * 6e4;
21883
+ var TOOL_POLL_POLICY = { delayMs: 2e3, maxDurationMs: FOLLOW_WINDOW_MS, errors: "pause" };
21884
+ var EVENT_POLL_POLICY = { ...TOOL_POLL_POLICY, errors: "retry", errorDelayMs: 4e3 };
21885
+ var CLI_POLL_POLICY = { delayMs: 4e3, errors: "pause", acceptLateRead: true };
21886
+ var pollDelay = (policy, attempt) => Math.min(policy.delayMs * (policy.multiplier ?? 1) ** attempt, policy.maxDelayMs ?? Infinity);
21887
+ var MAX_TIMER_MS = 2 ** 31 - 1;
21888
+ function longTimeout(callback, ms) {
21889
+ let timer;
21890
+ const arm = (remaining) => {
21891
+ timer = setTimeout(() => remaining > MAX_TIMER_MS ? arm(remaining - MAX_TIMER_MS) : callback(), Math.min(remaining, MAX_TIMER_MS));
21892
+ };
21893
+ arm(ms);
21894
+ return () => clearTimeout(timer);
21895
+ }
21896
+ async function pollUntil(options) {
21897
+ const { policy, signal, read, isDone } = options;
21898
+ if (!Number.isFinite(policy.maxDurationMs) && !Number.isFinite(policy.maxAttempts)) throw new Error("Polling requires a finite limit.");
21899
+ const now = options.now ?? Date.now;
21900
+ const deadline = now() + (policy.maxDurationMs ?? Infinity);
21901
+ let value = options.initial;
21902
+ let error61;
21903
+ let attempts = 0;
21904
+ let delayIndex = 0;
21905
+ let immediate = options.immediate ?? value === void 0;
21906
+ let failed2 = false;
21907
+ let stop;
21908
+ let cancelDeadline;
21909
+ let sleepTimer;
21910
+ let interrupt;
21911
+ const interrupted = new Promise((resolve) => {
21912
+ interrupt = () => resolve({ interrupted: true });
21913
+ });
21914
+ const abort = () => {
21915
+ stop = "cancelled";
21916
+ interrupt();
21917
+ };
21918
+ signal?.addEventListener("abort", abort, { once: true });
21919
+ if (signal?.aborted) abort();
21920
+ const acceptLate = policy.acceptLateRead === true;
21921
+ if (policy.maxDurationMs !== void 0 && !acceptLate) cancelDeadline = longTimeout(() => {
21922
+ stop = "limit";
21923
+ interrupt();
21924
+ }, policy.maxDurationMs);
21925
+ const result = (reason) => ({ reason, value, ...error61 === void 0 ? {} : { error: error61 } });
21926
+ try {
21927
+ for (; ; ) {
21928
+ if (stop) return result(stop);
21929
+ if (value !== void 0 && isDone(value)) return result("settled");
21930
+ if (policy.maxDurationMs !== void 0 && policy.maxDurationMs <= 0) return result("limit");
21931
+ if (attempts >= (policy.maxAttempts ?? Infinity)) return result("limit");
21932
+ if (!immediate) {
21933
+ const delay = failed2 && policy.errorDelayMs !== void 0 ? policy.errorDelayMs : pollDelay(policy, delayIndex);
21934
+ if (now() + delay > deadline) return result("limit");
21935
+ delayIndex += 1;
21936
+ const sleeping = options.sleep ? options.sleep(delay) : new Promise((resolve) => {
21937
+ sleepTimer = setTimeout(resolve, delay);
21938
+ });
21939
+ await Promise.race([sleeping, interrupted]);
21940
+ if (stop) return result(stop);
21941
+ }
21942
+ immediate = false;
21943
+ if (now() > deadline) return result("limit");
21944
+ attempts += 1;
21945
+ const readResult = await Promise.race([
21946
+ Promise.resolve().then(async () => {
21947
+ if (stop) return { kind: "interrupted" };
21948
+ try {
21949
+ return { kind: "value", value: await read() };
21950
+ } catch (error62) {
21951
+ return { kind: "error", error: error62 };
21952
+ }
21953
+ }),
21954
+ interrupted.then(() => ({ kind: "interrupted" }))
21955
+ ]);
21956
+ if (stop) return result(stop);
21957
+ if (!acceptLate && now() > deadline) return result("limit");
21958
+ if (readResult.kind === "interrupted") return result(stop ?? "cancelled");
21959
+ if (readResult.kind === "error") {
21960
+ error61 = readResult.error;
21961
+ failed2 = true;
21962
+ if (policy.errors === "pause" || options.retryError?.(error61, value) === false) return result("error");
21963
+ } else {
21964
+ value = readResult.value;
21965
+ error61 = void 0;
21966
+ failed2 = false;
21967
+ options.onValue?.(value);
21968
+ }
21969
+ }
21970
+ } finally {
21971
+ cancelDeadline?.();
21972
+ clearTimeout(sleepTimer);
21973
+ signal?.removeEventListener("abort", abort);
21974
+ }
21975
+ }
21976
+
21789
21977
  // src/credentials.ts
21790
21978
  import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
21791
21979
  import { join } from "node:path";
@@ -21854,7 +22042,7 @@ var CredentialStore = class {
21854
22042
 
21855
22043
  // src/session.ts
21856
22044
  var DEFAULT_API_URL = "https://api.gtmmaxing.com";
21857
- var POLL_MS = 4e3;
22045
+ var POLL_MS = CLI_POLL_POLICY.delayMs;
21858
22046
  var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
21859
22047
  function resolveApiUrl(flag, env, saved) {
21860
22048
  const raw = flag ?? env ?? saved ?? DEFAULT_API_URL;
@@ -21918,11 +22106,16 @@ var Session = class _Session {
21918
22106
  if (first.status !== "running" || !first.run_id) return first;
21919
22107
  let answer = first;
21920
22108
  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
- }
22109
+ const outcome = await pollUntil({
22110
+ policy: { ...CLI_POLL_POLICY, maxDurationMs: this.options.timeoutSeconds * 1e3 },
22111
+ initial: first,
22112
+ read: () => this.gateway.call("gtm_results", { run_id: first.run_id }),
22113
+ isDone: (value) => value.status !== "running",
22114
+ now: () => this.io.now(),
22115
+ sleep: (ms) => this.io.sleep(ms)
22116
+ });
22117
+ if (outcome.reason === "error") throw outcome.error;
22118
+ answer = outcome.value ?? first;
21926
22119
  }
21927
22120
  if (answer === first) return first;
21928
22121
  if (first.replayed) return { ...answer, replayed: true };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gtmmaxing",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "description": "gtm: the GTMMAXING command line. Find contacts, build lead lists and research companies from a terminal or a coding agent, with credit caps on every paid call.",
5
5
  "keywords": [
6
6
  "gtm",