socialcrawl-mcp 2.5.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +1,38 @@
1
1
  import { DISCOVER_INPUT_ID_RE, REVIEW_HISTORY_PLATFORMS, REVIEW_JOB_ID_RE, RUN_ID_RE, SCHEDULE_ID_RE } from "../schemas/async.js";
2
- import { EVENTS_CURSOR_EXPIRED_HINT, LONG_READ_TIMEOUT_MS, dataOf, pruneQuery, render, resolveFollowUrl, sendRequest, } from "./async-common.js";
3
- const RUN_ACTIONS_WITH_ID = new Set(["run_get", "run_export", "run_legs", "run_cancel", "run_resume", "run_more"]);
2
+ import { EVENTS_CURSOR_EXPIRED_HINT, LONG_READ_TIMEOUT_MS, dataOf, followFormat, pruneQuery, render, resolveFollowUrl, sendRequest, } from "./async-common.js";
3
+ const RUN_ACTIONS_WITH_ID = new Set([
4
+ "run_get",
5
+ "run_status",
6
+ "run_export",
7
+ "run_results_csv",
8
+ "run_comments_csv",
9
+ "run_legs",
10
+ "run_cancel",
11
+ "run_resume",
12
+ "run_more",
13
+ "run_comments",
14
+ ]);
4
15
  const SCHEDULE_ACTIONS_WITH_ID = new Set(["schedule_get", "schedule_pause", "schedule_resume", "schedule_delete"]);
5
16
  const RUN_ERROR_HINTS = {
6
17
  RUN_EXPIRED: "The run's retention passed (or it was purged), so its rows can no longer be read. Start a new run with socialcrawl_request on prism/discover.",
7
18
  run_not_completed: 'more is offered only on a completed run: poll it with action "run_get" (wait_s 25) until status is completed, or "run_resume" it first.',
8
19
  CONCURRENCY_LIMIT: "Too many calls in flight on this key; wait a moment and retry. Nothing was charged.",
9
20
  SERVICE_UNAVAILABLE: "Retryable: nothing was charged. Retry the same call after a few seconds.",
21
+ csv_posts_only: 'The CSV exports carry post rows only; this run\'s export is accounts, communities or items. Use "run_export" (JSONL) for it.',
22
+ run_running: 'The run is still running: poll it with "run_status" (wait_s 25) until it settles, then send the comments pass again.',
23
+ run_has_unsent_work: 'The run still owes searches or calls that are not comment pages, and a comments pass never resumes them: "run_resume" it first (or cancel it), then send the pass.',
10
24
  };
11
- const FOLLOW_HINT = '**Next:** any `data.next.*` URL above (status_url, results_url, changes_url) can be passed to action "follow" (input.url); continue_url bills and is NOT followed (use socialcrawl_request), resume_url/more_url map to "run_resume"/"run_more".';
25
+ const FOLLOW_HINT = '**Next:** any `data.next.*` URL above (poll_url, status_url, results_url, changes_url) can be passed to action "follow" (input.url); continue_url bills and is NOT followed (use socialcrawl_request), resume_url/more_url map to "run_resume"/"run_more".';
26
+ /** The trailer every export ends with (API-459: each line carries `kind`). */
27
+ const EXPORT_NOTE = 'One row per line, each with `kind` (`post`, `account`, `community`, `item`, `warning`, `removed`, `trailer`). The last line is the `kind: "trailer"` line: `complete: true`, or `next_cursor` when the stream stopped early (about 45 s): call again with that cursor and the SAME filters. Long exports are cut at this tool\'s response size limit; prefer "run_get" pages for large runs.';
12
28
  /** The run read filters (`RUN_PARAMS` / `JSONL_PARAMS` in the run routes). */
13
29
  function runReadQuery(input, withPaging) {
30
+ const name = input.action;
14
31
  if (!withPaging && (input.wait_s !== undefined || input.page_size !== undefined)) {
15
- return 'Error: Invalid parameter value(s): run_export takes no `wait_s` or `page_size`: it streams every matching row and ends with {"complete":true} or {"next_cursor":…}. Nothing was sent.';
32
+ return `Error: Invalid parameter value(s): ${name} takes no \`wait_s\` or \`page_size\`: it streams every matching row and ends with a trailer line ({"kind":"trailer","complete":true} or {"kind":"trailer","next_cursor":…}). Nothing was sent.`;
33
+ }
34
+ if (!withPaging && (input.summary !== undefined || input.summary_extra !== undefined)) {
35
+ return `Error: Invalid parameter value(s): ${name} takes no \`summary\` or \`summary_extra\` (the export carries rows, not the run summary; read it with "run_get"). Nothing was sent.`;
16
36
  }
17
37
  if (withPaging && input.page_size !== undefined && input.page_size > 100) {
18
38
  return "Error: Invalid parameter value(s): `page_size` on run_get is 1 to 100 (default 50). Nothing was sent.";
@@ -29,10 +49,15 @@ function runReadQuery(input, withPaging) {
29
49
  sort: input.sort,
30
50
  state: input.state,
31
51
  include: input.include,
52
+ // API-458: the row shape for this read, and how much summary comes back.
53
+ format: input.format,
54
+ fields: input.fields,
32
55
  };
33
56
  if (withPaging) {
34
57
  query.wait_s = input.wait_s?.toString();
35
58
  query.page_size = input.page_size?.toString();
59
+ query.summary = input.summary;
60
+ query.summary_extra = input.summary_extra;
36
61
  }
37
62
  for (const [k, v] of Object.entries(input.tags ?? {})) {
38
63
  if (!/^[A-Za-z0-9_.-]{1,64}$/.test(k)) {
@@ -117,6 +142,31 @@ export async function discoverRuns(ctx, input) {
117
142
  errorHints: RUN_ERROR_HINTS,
118
143
  });
119
144
  }
145
+ case "run_status": {
146
+ // API-455: the read to poll answers run, next and _warnings only, and takes only wait_s.
147
+ const extra = Object.keys(input).filter((k) => !["action", "run_id", "wait_s", "dryRun"].includes(k) && input[k] !== undefined);
148
+ if (extra.length > 0) {
149
+ return `Error: Invalid parameter value(s): run_status takes only \`wait_s\`, not ${extra.map((k) => `\`${k}\``).join(", ")}: it answers the run's status alone. Read rows with "run_get". Nothing was sent.`;
150
+ }
151
+ const response = await sendRequest(ctx, {
152
+ method: "GET",
153
+ path: `${runPath}/status`,
154
+ query: pruneQuery({ wait_s: input.wait_s?.toString() }),
155
+ errorPlatform: "prism",
156
+ timeoutMs: LONG_READ_TIMEOUT_MS,
157
+ });
158
+ return render({
159
+ title: "SocialCrawl Discover Run: status",
160
+ label: `GET /v1/prism/discover/runs/${input.run_id}/status${input.wait_s ? ` (wait_s=${input.wait_s})` : ""}`,
161
+ cost: "0 credits",
162
+ notes: [
163
+ "`run` only (status, `progress.stages` and `progress.current_stage`, rows collected, judging and held, `eta_s` with `eta_basis`, `credits_remaining`), `next` and `_warnings`: about 2 KB where `run_get` is about 100 KB. Poll this; read rows with \"run_get\" or the exports once it settles.",
164
+ FOLLOW_HINT,
165
+ ],
166
+ response,
167
+ errorHints: RUN_ERROR_HINTS,
168
+ });
169
+ }
120
170
  case "run_export": {
121
171
  const query = runReadQuery(input, false);
122
172
  if (typeof query === "string")
@@ -132,11 +182,37 @@ export async function discoverRuns(ctx, input) {
132
182
  title: "SocialCrawl Discover Run — JSONL export",
133
183
  label: `GET /v1/prism/discover/runs/${input.run_id}/results.jsonl`,
134
184
  cost: "0 credits",
185
+ notes: [EXPORT_NOTE],
186
+ response,
187
+ format: "jsonl",
188
+ errorHints: RUN_ERROR_HINTS,
189
+ });
190
+ }
191
+ case "run_results_csv":
192
+ case "run_comments_csv": {
193
+ // API-460: results.jsonl's own answer as CSV (same filters and cursor).
194
+ const query = runReadQuery(input, false);
195
+ if (typeof query === "string")
196
+ return query;
197
+ const file = action === "run_results_csv" ? "results.csv" : "comments.csv";
198
+ const response = await sendRequest(ctx, {
199
+ method: "GET",
200
+ path: `${runPath}/${file}`,
201
+ query,
202
+ errorPlatform: "prism",
203
+ timeoutMs: LONG_READ_TIMEOUT_MS,
204
+ });
205
+ return render({
206
+ title: `SocialCrawl Discover Run: ${file}`,
207
+ label: `GET /v1/prism/discover/runs/${input.run_id}/${file}`,
208
+ cost: "0 credits",
135
209
  notes: [
136
- 'One row per line. The last line is {"complete":true}, or {"next_cursor":"…"} when the stream stopped early (about 45 s): call run_export again with that cursor and the SAME filters. Long exports are cut at this tool\'s response size limit; prefer "run_get" pages for large runs.',
210
+ action === "run_results_csv"
211
+ ? "One line per kept post row: fixed columns, then one `question.<id>` column per question. RFC 4180, UTF-8 with a BOM, formula-like cells guarded. Same filters and cursor as \"run_export\"; a run that is not posts is a free 400 `csv_posts_only`."
212
+ : "One line per comment the rows carry, keyed by `post_id`. RFC 4180, UTF-8 with a BOM, formula-like cells guarded. Same filters and cursor as \"run_export\"; a run that is not posts is a free 400 `csv_posts_only`.",
137
213
  ],
138
214
  response,
139
- format: "jsonl",
215
+ format: "csv",
140
216
  errorHints: RUN_ERROR_HINTS,
141
217
  });
142
218
  }
@@ -168,11 +244,28 @@ export async function discoverRuns(ctx, input) {
168
244
  });
169
245
  }
170
246
  case "run_resume": {
247
+ if (input.attach_stored_only === true) {
248
+ // API-462: read back stored comment pages no row shows; nothing else.
249
+ if (input.max_credits !== undefined || input.retry_failed !== undefined) {
250
+ return 'Error: Invalid parameter value(s): `attach_stored_only` reads back only the comment pages the run already stored, so it takes no `max_credits` or `retry_failed`. Send {"attach_stored_only": true} alone, or drop it to resume the run. Nothing was sent.';
251
+ }
252
+ const response = await sendRequest(ctx, { method: "POST", path: `${runPath}/resume`, body: { attach_stored_only: true }, errorPlatform: "prism" });
253
+ return render({
254
+ title: "SocialCrawl Discover Run: stored comments attached",
255
+ label: `POST /v1/prism/discover/runs/${input.run_id}/resume (attach_stored_only)`,
256
+ cost: "0 credits: it bills nothing and keeps the run's status; `data.attached` counts the posts and pages attached.",
257
+ notes: ["If `_warnings` says posts with stored pages were not reached in this call, send it again to attach the rest.", FOLLOW_HINT],
258
+ response,
259
+ errorHints: RUN_ERROR_HINTS,
260
+ });
261
+ }
171
262
  const body = {};
172
263
  if (input.max_credits !== undefined)
173
264
  body.max_credits = input.max_credits;
174
265
  if (input.retry_failed !== undefined)
175
266
  body.retry_failed = input.retry_failed;
267
+ if (input.attach_stored_only === false)
268
+ body.attach_stored_only = false;
176
269
  const response = await sendRequest(ctx, { method: "POST", path: `${runPath}/resume`, body, errorPlatform: "prism" });
177
270
  return render({
178
271
  title: "SocialCrawl Discover Run — resumed",
@@ -212,6 +305,32 @@ export async function discoverRuns(ctx, input) {
212
305
  errorHints: RUN_ERROR_HINTS,
213
306
  });
214
307
  }
308
+ case "run_comments": {
309
+ // API-461: a comments pass over a settled posts run's kept rows.
310
+ const body = {};
311
+ for (const k of ["top_posts", "per_post", "platforms", "labels", "max_credits"]) {
312
+ if (input[k] !== undefined)
313
+ body[k] = input[k];
314
+ }
315
+ if (input.dryRun)
316
+ body.dry_run = true;
317
+ const response = await sendRequest(ctx, { method: "POST", path: `${runPath}/comments`, body, errorPlatform: "prism" });
318
+ return render({
319
+ title: "SocialCrawl Discover Run: comments pass",
320
+ label: `POST /v1/prism/discover/runs/${input.run_id}/comments${input.dryRun ? " (dry run)" : ""}`,
321
+ cost: input.dryRun
322
+ ? "0 credits: a dry run answers the pass's estimate and starts nothing"
323
+ : "metered: the comment pages bill at their lanes' prices (as the run's comments stage does) under max_credits, which defaults to the quote's max; a page an earlier pass stored replays free, and a post that already carries comments keeps them.",
324
+ notes: [
325
+ input.dryRun
326
+ ? "Ask the user to approve the quoted credits, then send the same fields without dry_run."
327
+ : 'The answer is 202 with the run: poll "run_status" (wait_s 25), then read the comments with "run_get" or "run_comments_csv".',
328
+ FOLLOW_HINT,
329
+ ],
330
+ response,
331
+ errorHints: RUN_ERROR_HINTS,
332
+ });
333
+ }
215
334
  // ── discover schedules ─────────────────────────────────────────────
216
335
  case "schedule_list": {
217
336
  if (input.page_size !== undefined && input.page_size > 100) {
@@ -331,7 +450,7 @@ export async function discoverRuns(ctx, input) {
331
450
  cost: "0 credits (a free read)",
332
451
  notes: [FOLLOW_HINT],
333
452
  response,
334
- format: resolved.path.split("?")[0].endsWith(".jsonl") ? "jsonl" : "json",
453
+ format: followFormat(resolved.path),
335
454
  errorHints: { ...RUN_ERROR_HINTS, CURSOR_EXPIRED: EVENTS_CURSOR_EXPIRED_HINT },
336
455
  });
337
456
  }
@@ -15,9 +15,10 @@ export const DRY_RUN_ACTIONS = {
15
15
  web: ["monitor_create", "monitor_update"],
16
16
  cohorts: ["create", "add_members", "query"],
17
17
  jobs: [],
18
- // No discover-run, schedule, review-history, events or webhook-endpoint
19
- // route reads dry_run (run resume/more refuse any query parameter).
20
- discover: [],
18
+ // Of the discover routes only the comments pass reads dry_run (in its body,
19
+ // API-461); no schedule, review-history, events or webhook-endpoint route
20
+ // does (run resume/more refuse any query parameter).
21
+ discover: ["run_comments"],
21
22
  review_history: [],
22
23
  events: [],
23
24
  // more and include answer a free plan + estimate under `dry_run: true`.
@@ -225,7 +226,7 @@ async function dispatch(ctx, p, input, sendDry) {
225
226
  const parsed = DiscoverInputSchema.safeParse(parsedInput);
226
227
  if (!parsed.success)
227
228
  return invalid(p.area, parsed.error);
228
- return done(await discoverRuns(ctx, parsed.data));
229
+ return done(await discoverRuns(ctx, { ...parsed.data, dryRun: sendDry }));
229
230
  }
230
231
  if (p.area === "review_history") {
231
232
  const parsed = ReviewHistoryInputSchema.safeParse(parsedInput);
@@ -30,6 +30,8 @@ export interface MonitorsParams {
30
30
  recipe?: string;
31
31
  params?: Record<string, unknown>;
32
32
  cadence?: string;
33
+ /** create: IANA zone a cron cadence is read in (API-514). Cron only. */
34
+ timezone?: string;
33
35
  webhook_url?: string;
34
36
  name?: string;
35
37
  alert_rules?: unknown[];
@@ -37,7 +39,7 @@ export interface MonitorsParams {
37
39
  output_schema?: Record<string, unknown>;
38
40
  webhook_secret?: string;
39
41
  track?: MonitorTrack;
40
- webhook_format?: "full" | "rows";
42
+ webhook_format?: "full" | "rows" | "chat";
41
43
  webhook_rows?: "all" | "new";
42
44
  /** create/update/pause/resume: whole credits a month, 1-10,000,000; null (update) removes the cap. */
43
45
  max_credits_per_month?: number | null;
@@ -46,12 +46,16 @@ const INCLUDE_RE = /^(result|numbers)(,(result|numbers))?$/;
46
46
  * direct (non-MCP) callers get the same guarantee.
47
47
  */
48
48
  const MONITOR_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
49
- /** Map the validated `cadence` string to the API's union (preset | {cron}). */
50
- function toCadence(cadence) {
49
+ const PRESET_CADENCES = new Set(["hourly", "daily", "weekly"]);
50
+ /**
51
+ * Map the validated `cadence` string to the API's union (preset | {cron}).
52
+ * API-514: a cron carries the optional IANA `timezone` it is read in.
53
+ */
54
+ function toCadence(cadence, timezone) {
51
55
  if (cadence === "hourly" || cadence === "daily" || cadence === "weekly") {
52
56
  return cadence;
53
57
  }
54
- return { cron: cadence };
58
+ return timezone ? { cron: cadence, timezone } : { cron: cadence };
55
59
  }
56
60
  function pruneQuery(q) {
57
61
  const out = {};
@@ -80,6 +84,9 @@ function validateCreate(input) {
80
84
  if (missing.length > 0) {
81
85
  return `Error: Missing required parameter(s) for create: ${missing.join(", ")}.`;
82
86
  }
87
+ if (input.timezone && PRESET_CADENCES.has(input.cadence)) {
88
+ return "Error: `timezone` applies only to a cron `cadence` (for example \"0 6-18/2 * * 1-5\" with \"America/New_York\"). Hourly, daily and weekly run from the time the monitor is created.";
89
+ }
83
90
  // The recipe must resolve to a registered GET endpoint. Prism composites are
84
91
  // added often and may be newer than this server's bundled catalogue, so an
85
92
  // unknown prism/* recipe is left to the API's own (free) 400.
@@ -132,6 +139,15 @@ function validateCreate(input) {
132
139
  if (input.webhook_format === "rows" && !track) {
133
140
  return 'Error: `webhook_format: "rows"` needs `track`: the rows payload is built from the tracked numbers. Add track, or use webhook_format "full".';
134
141
  }
142
+ if (input.webhook_format === "chat") {
143
+ // API-520: chat posts each new row as a line of text, so it needs the new-rows store.
144
+ if (!track || !hasRowMetric) {
145
+ return "Error: `webhook_format: \"chat\"` posts each new row as a line in a chat channel, so it needs `track` with at least one 'items[].<path>' metric and a `row_key`, and `webhook_rows: \"new\"`.";
146
+ }
147
+ if (input.webhook_rows !== "new") {
148
+ return "Error: `webhook_format: \"chat\"` posts only the rows new since the previous run, so set `webhook_rows: \"new\"`.";
149
+ }
150
+ }
135
151
  if (input.webhook_rows === "new") {
136
152
  if (!track || !hasRowMetric) {
137
153
  return "Error: `webhook_rows: \"new\"` sends only the list rows that are new since the previous run, so it needs `track` with at least one 'items[].<path>' metric.";
@@ -165,7 +181,7 @@ export async function monitors(ctx, input, opts = {}) {
165
181
  return invalid;
166
182
  const body = {
167
183
  recipe: input.recipe,
168
- cadence: toCadence(input.cadence),
184
+ cadence: toCadence(input.cadence, input.timezone),
169
185
  };
170
186
  if (input.webhook_url)
171
187
  body.webhook_url = input.webhook_url;
@@ -4,7 +4,8 @@ import { CACHE_TTLS, CREDIT_LADDER, REGISTRY_STATS } from "../data/registry-meta
4
4
  import { hydratingEndpoints, laneCeilingCredits, laneMaxCredits, isPublicSibling, quoteHydration, siblingRef, } from "../hydration.js";
5
5
  import { bestCaseCost, endpointLabel, endpointPath, explainPricing, flatOverrideEndpoints, formatCost, formatTtl, freeEndpoints, meteredEndpoints, hydrationCeiling, meteredRule, worstCaseCost, } from "../pricing.js";
6
6
  import { judgedEndpoints, judgmentHoldMax, judgedRowCap, labelFamily, quoteJudgments, LEVERS, } from "../judgments.js";
7
- import { bandExplained, pagesLever, unaskedJoinCredits } from "../cost-guard.js";
7
+ import { bandExplained, meteredBase, pagesLever, unaskedJoinCredits } from "../cost-guard.js";
8
+ import { valueAndAddOnCredits } from "../value-prices.js";
8
9
  import { errorFromText, isErrorText } from "../result.js";
9
10
  const BILLING_RULES = [
10
11
  "**Cache hits are free.** A repeat of the same call inside the endpoint's TTL returns `cached: true` and deducts 0 credits.",
@@ -236,6 +237,8 @@ function callQuote(endpoint, params) {
236
237
  const pageFloor = bestCaseCost(endpoint.pricing);
237
238
  const exact = bandExplained(endpoint);
238
239
  let pageHold;
240
+ // A batch priced per handle is the whole hold: no joins, judgments or pages on top.
241
+ let wholeCall = false;
239
242
  if (!exact) {
240
243
  // The band's ceiling includes every join; a join the call does not turn
241
244
  // on is not held, so it comes off (tiktok/search: 62 − 20 for an unasked
@@ -249,19 +252,37 @@ function callQuote(endpoint, params) {
249
252
  : `| the page (metered band ${formatCost(endpoint.pricing)}, every opt-in included) | up to ${pageHold}cr |`);
250
253
  notes.push("This endpoint meters on more than joins and judgments (see the rule above), so the band's ceiling is the budget; the settled charge follows the rule.");
251
254
  }
252
- else if (hydration) {
253
- pageHold = hydration.held;
254
- rows.push(`| the page itself | ${hydration.base}cr |`);
255
- for (const l of hydration.lanes) {
256
- rows.push(`| \`include=${l.lane.token}\` (${l.rows} rows × ${l.lane.creditsPerItem}cr) | ${l.held}cr |`);
257
- }
258
- }
259
255
  else {
260
- pageHold = endpoint.pricing.cost;
261
- rows.push(`| the page itself | ${pageHold}cr |`);
256
+ // The rule's own meter for these params (rows on `limit`, places,
257
+ // segments, platforms, handles), quoted as the cost guard quotes it.
258
+ const metered = meteredBase(endpoint, q);
259
+ const base = metered?.credits ?? endpoint.pricing.cost;
260
+ const pageRow = metered ? `| the call (${metered.basis}) | ${base}cr |` : `| the page itself | ${base}cr |`;
261
+ if (metered?.whole) {
262
+ wholeCall = true;
263
+ pageHold = base;
264
+ rows.push(pageRow);
265
+ }
266
+ else if (hydration) {
267
+ pageHold = hydration.held - hydration.base + base;
268
+ rows.push(pageRow);
269
+ for (const l of hydration.lanes) {
270
+ rows.push(`| \`include=${l.lane.token}\` (${l.rows} rows × ${l.lane.creditsPerItem}cr) | ${l.held}cr |`);
271
+ }
272
+ }
273
+ else {
274
+ pageHold = base;
275
+ rows.push(pageRow);
276
+ }
277
+ // A value that sets the page price (sort=likes) or a fixed include add-on.
278
+ const addOns = wholeCall ? 0 : valueAndAddOnCredits(endpoint, q);
279
+ if (addOns > 0) {
280
+ pageHold += addOns;
281
+ rows.push(`| a value price or \`include\` add-on these params name (rule above) | ${addOns}cr |`);
282
+ }
262
283
  }
263
284
  // API-280/281: further pages asked with `pages`, each at the posts page price.
264
- const lever = exact ? pagesLever(endpoint) : undefined;
285
+ const lever = exact && !wholeCall ? pagesLever(endpoint) : undefined;
265
286
  const pagesAsked = Number(q.pages);
266
287
  if (lever && Number.isFinite(pagesAsked) && pagesAsked > 1) {
267
288
  const further = Math.min(Math.floor(pagesAsked), lever.max) - 1;
@@ -275,7 +296,7 @@ function callQuote(endpoint, params) {
275
296
  }
276
297
  const jq = quoteJudgments(endpoint, q);
277
298
  // Inside an unexplained band the judgment holds are already in the ceiling.
278
- if (!exact) {
299
+ if (!exact || wholeCall) {
279
300
  jq.held = 0;
280
301
  jq.labelHold = 0;
281
302
  jq.relevanceHold = 0;
@@ -1,5 +1,5 @@
1
1
  import { RUN_ID_RE, WATCH_ID_RE } from "../schemas/async.js";
2
- import { LONG_READ_TIMEOUT_MS, pruneQuery, render, resolveFollowUrl, sendRequest } from "./async-common.js";
2
+ import { LONG_READ_TIMEOUT_MS, followFormat, pruneQuery, render, resolveFollowUrl, sendRequest } from "./async-common.js";
3
3
  const SEARCH = {
4
4
  name: "Search Run",
5
5
  area: "search_runs",
@@ -84,7 +84,9 @@ async function runCommon(ctx, fam, input, readKeys) {
84
84
  cost: "0 credits",
85
85
  notes: paged
86
86
  ? [followHint(fam.area)]
87
- : ['One row per line. The last line is {"complete":true,"changes_url":…}, or {"next_cursor":"…"} when the stream stopped early: call again with that cursor and the SAME filters.'],
87
+ : fam.area === "creator_runs"
88
+ ? ['One row per line, each with `kind` (`account`, `warning`, `removed`, `trailer`). The last line is the `kind: "trailer"` line: `complete: true`, or `next_cursor` when the stream stopped early: call again with that cursor and the SAME filters.']
89
+ : ['One row per line. The last line is {"complete":true,"changes_url":…}, or {"next_cursor":"…"} when the stream stopped early: call again with that cursor and the SAME filters.'],
88
90
  response,
89
91
  format: paged ? "json" : "jsonl",
90
92
  errorHints: RUN_ERROR_HINTS,
@@ -276,6 +278,28 @@ export async function creatorRuns(ctx, input) {
276
278
  const runPath = `${CREATORS.runs}/${input.run_id ? encodeURIComponent(input.run_id) : ""}`;
277
279
  const idem = input.idempotencyKey ? { idempotencyKey: input.idempotencyKey } : {};
278
280
  switch (input.action) {
281
+ case "run_status": {
282
+ // API-455: the light read to poll (run, next, _warnings), wait_s only.
283
+ const extra = Object.keys(input).filter((k) => !["action", "run_id", "wait_s", "idempotencyKey"].includes(k) && input[k] !== undefined);
284
+ if (extra.length > 0) {
285
+ return `Error: Invalid parameter value(s): run_status takes only \`wait_s\`, not ${extra.map((k) => `\`${k}\``).join(", ")}: it answers the run's status alone. Read creators with "run_get". Nothing was sent.`;
286
+ }
287
+ const response = await sendRequest(ctx, {
288
+ method: "GET",
289
+ path: `${runPath}/status`,
290
+ query: pruneQuery({ wait_s: input.wait_s?.toString() }),
291
+ errorPlatform: "prism",
292
+ timeoutMs: LONG_READ_TIMEOUT_MS,
293
+ });
294
+ return render({
295
+ title: "SocialCrawl Creator Run: status",
296
+ label: `GET ${CREATORS.runs}/${input.run_id}/status${input.wait_s ? ` (wait_s=${String(input.wait_s)})` : ""}`,
297
+ cost: "0 credits",
298
+ notes: ["`run`, `next` and `_warnings` only (a few KB): poll this, then read creators with \"run_get\" or \"run_export\".", followHint("creator_runs")],
299
+ response,
300
+ errorHints: RUN_ERROR_HINTS,
301
+ });
302
+ }
279
303
  case "run_more": {
280
304
  const body = {};
281
305
  for (const k of ["new_searches", "max_credits", "pages"])
@@ -326,7 +350,7 @@ async function follow(ctx, url, area) {
326
350
  cost: "0 credits (a free read)",
327
351
  notes: [followHint(area)],
328
352
  response,
329
- format: resolved.path.split("?")[0].endsWith(".jsonl") ? "jsonl" : "json",
353
+ format: followFormat(resolved.path),
330
354
  errorHints: RUN_ERROR_HINTS,
331
355
  });
332
356
  }
@@ -0,0 +1,32 @@
1
+ import type { Endpoint } from "./types.js";
2
+ /**
3
+ * Lanes whose hold is a unit price times the units a call names, stated in the
4
+ * pricing rule (brand-report wave, API-472, API-474, API-475, 01/12/2026):
5
+ *
6
+ * - `google_trends/explore`: "5 credits per place that returns data", one
7
+ * place per distinct comma-separated `location` (none counts as one).
8
+ * - `naver/search-trend`: "With `breakdown`, 5 credits per segment": `gender`
9
+ * and `device` split in two (one when the matching filter is set), `age` in
10
+ * the age bands (`ages` narrows them).
11
+ * - `naver/shopping-insight/keyword`: "With `breakdown`, 5 credits per
12
+ * keyword": one request per keyword in `keyword`.
13
+ * - `prism/find-accounts`: each platform's search at its lane price plus 1
14
+ * judged, and the profile lookups `profile_check` makes.
15
+ *
16
+ * Each meter is read from the registry wording and switches itself off when
17
+ * that wording is gone, so a changed rule falls back to the band's ceiling
18
+ * (an over-quote) instead of a stale exact figure. The arithmetic mirrors the
19
+ * API's own estimator (credits/dynamic-cost.ts in the backend).
20
+ */
21
+ export interface UnitHold {
22
+ credits: number;
23
+ /** What the units were, for an itemised quote. */
24
+ basis: string;
25
+ }
26
+ export interface UnitMeter {
27
+ hold(params: Record<string, unknown>): UnitHold;
28
+ /** The most any call holds, for the band check. */
29
+ ceiling: number;
30
+ }
31
+ /** The unit meter this lane's rule states, or undefined. */
32
+ export declare function unitMeter(e: Endpoint): UnitMeter | undefined;
@@ -0,0 +1,137 @@
1
+ const str = (v) => (v === undefined || v === null ? "" : String(v)).trim();
2
+ const csv = (v) => str(v)
3
+ .split(",")
4
+ .map((s) => s.trim())
5
+ .filter(Boolean);
6
+ const distinct = (xs) => [...new Set(xs.map((x) => x.toLowerCase()))];
7
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
8
+ function placesMeter(e) {
9
+ const m = /^(\d+) credits per place that returns data\b/.exec(e.pricing.description ?? "");
10
+ const max = e.pricing.maxCost;
11
+ if (!m || max === undefined || !e.optionalParams.some((o) => o.name === "location"))
12
+ return undefined;
13
+ const per = Number(m[1]);
14
+ const most = Math.floor(max / per);
15
+ return {
16
+ hold(params) {
17
+ const n = Math.min(Math.max(1, distinct(csv(params.location)).length), most);
18
+ return { credits: per * n, basis: `${plural(n, "place")} × ${per}cr` };
19
+ },
20
+ ceiling: per * most,
21
+ };
22
+ }
23
+ function segmentsMeter(e) {
24
+ const m = /\bWith `breakdown`, (\d+) credits per segment that returns data\b/.exec(e.pricing.description ?? "");
25
+ const max = e.pricing.maxCost;
26
+ const breakdown = e.optionalParams.find((o) => o.name === "breakdown");
27
+ if (!m || max === undefined || !breakdown)
28
+ return undefined;
29
+ const per = Number(m[1]);
30
+ // The age bands are the band's ceiling over the unit price (11 on search-trend: 55 / 5).
31
+ const ageBands = Math.floor(max / per);
32
+ const filterValues = (name) => e.optionalParams.find((o) => o.name === name)?.enumValues ?? [];
33
+ return {
34
+ hold(params) {
35
+ // Read as the API reads them: exact codes and values, case as sent.
36
+ const split = str(params.breakdown);
37
+ let n = 1;
38
+ if (split === "age") {
39
+ const asked = [...new Set(csv(params.ages))].filter((c) => /^[1-9]\d*$/.test(c) && Number(c) <= ageBands);
40
+ n = asked.length > 0 ? asked.length : ageBands;
41
+ }
42
+ else if (split === "gender" || split === "device") {
43
+ const all = filterValues(split);
44
+ n = all.includes(str(params[split])) ? 1 : Math.max(1, all.length);
45
+ }
46
+ else {
47
+ return { credits: e.pricing.cost, basis: "one request" };
48
+ }
49
+ return { credits: per * n, basis: `\`breakdown=${split}\`: ${plural(n, "segment")} × ${per}cr` };
50
+ },
51
+ ceiling: per * ageBands,
52
+ };
53
+ }
54
+ function keywordSplitMeter(e) {
55
+ const m = /\bWith `breakdown`, (\d+) credits per keyword that returns data\b/.exec(e.pricing.description ?? "");
56
+ const max = e.pricing.maxCost;
57
+ if (!m || max === undefined || !e.optionalParams.some((o) => o.name === "breakdown"))
58
+ return undefined;
59
+ const per = Number(m[1]);
60
+ const most = Math.floor(max / per);
61
+ return {
62
+ hold(params) {
63
+ if (str(params.breakdown) === "")
64
+ return { credits: e.pricing.cost, basis: "one request" };
65
+ const n = Math.min(Math.max(1, csv(params.keyword).length), most);
66
+ return { credits: per * n, basis: `\`breakdown\`: ${plural(n, "keyword")} × ${per}cr` };
67
+ },
68
+ ceiling: per * most,
69
+ };
70
+ }
71
+ // ── prism/find-accounts ────────────────────────────────────────────────
72
+ const FA_PLATFORMS = ["linkedin", "instagram", "tiktok", "twitter", "threads", "youtube", "facebook"];
73
+ /** Each platform's search at its lane price, as the rule states it. */
74
+ const FA_SEARCH = { linkedin: 10, instagram: 1, tiktok: 1, twitter: 1, threads: 1, youtube: 1, facebook: 1 };
75
+ const FA_JUDGE = 1;
76
+ /** One profile lookup's price; 0 = never looked up (X, YouTube, Facebook, a LinkedIn member). */
77
+ const FA_LOOKUP = {
78
+ person: { linkedin: 0, instagram: 1, tiktok: 1, twitter: 0, threads: 1, youtube: 0, facebook: 0 },
79
+ company: { linkedin: 5, instagram: 1, tiktok: 1, twitter: 0, threads: 1, youtube: 0, facebook: 0 },
80
+ };
81
+ const FA_DEFAULTS = {
82
+ person: ["instagram", "tiktok", "twitter"],
83
+ company: ["linkedin", "instagram", "tiktok", "twitter"],
84
+ };
85
+ const FA_CANDIDATES_MAX = 5;
86
+ const FA_PRE_RANK = 2;
87
+ /** The wording these tables were read from; any change switches the meter off. */
88
+ const FA_RULE = [
89
+ "The searches at their own prices (1 credit each for Instagram, TikTok and X, 10 for LinkedIn) plus 1 credit per platform judged",
90
+ "Threads, YouTube or Facebook, when named, is 1 credit for its search plus 1 for its judging (a Facebook page is never looked up by `profile_check`)",
91
+ "(1 credit on Instagram, TikTok and Threads, 5 for a company page on LinkedIn)",
92
+ "except a company's Instagram and TikTok, where the top two candidates are looked up before the ranking and the leading one after it when it ranked lower, so at most 3 lookups (3 credits) per platform",
93
+ "With profile_check_scope=leader every platform makes one lookup, of the leading candidate",
94
+ ];
95
+ const FA_DEFAULTS_TEXT = "Default: instagram, tiktok, twitter for a person; linkedin, instagram, tiktok, twitter for a company.";
96
+ function lookups(type, p, candidates, leader) {
97
+ if (FA_LOOKUP[type][p] === 0)
98
+ return 0;
99
+ if (leader)
100
+ return 1;
101
+ if (type !== "company" || (p !== "instagram" && p !== "tiktok"))
102
+ return 1;
103
+ const pre = Math.min(FA_PRE_RANK, candidates);
104
+ return pre + (candidates > pre ? 1 : 0);
105
+ }
106
+ function findAccountsMeter(e) {
107
+ const rule = e.pricing.description ?? "";
108
+ const platformsText = e.optionalParams.find((o) => o.name === "platforms")?.description ?? "";
109
+ if (e.pricing.model !== "metered" || !FA_RULE.every((s) => rule.includes(s)) || !platformsText.includes(FA_DEFAULTS_TEXT))
110
+ return undefined;
111
+ const quote = (type, platforms, check, candidates, leader) => platforms.reduce((sum, p) => sum + FA_SEARCH[p] + FA_JUDGE + (check ? FA_LOOKUP[type][p] * lookups(type, p, candidates, leader) : 0), 0);
112
+ return {
113
+ hold(params) {
114
+ // An unknown type, platform or scope is a free 400: priced as the API's estimator prices it.
115
+ const type = str(params.type).toLowerCase() === "company" ? "company" : "person";
116
+ const asked = csv(params.platforms).map((p) => p.toLowerCase());
117
+ const known = asked.every((p) => FA_PLATFORMS.includes(p));
118
+ const platforms = asked.length > 0 && known ? FA_PLATFORMS.filter((p) => asked.includes(p)) : FA_DEFAULTS[type];
119
+ const check = str(params.profile_check).toLowerCase() === "true";
120
+ const c = Number(str(params.candidates));
121
+ const candidates = Number.isInteger(c) && c >= 1 && c <= FA_CANDIDATES_MAX ? c : FA_CANDIDATES_MAX;
122
+ const leader = str(params.profile_check_scope).toLowerCase() === "leader";
123
+ return {
124
+ credits: quote(type, platforms, check, candidates, leader),
125
+ basis: `${type}: ${platforms.join(", ")} (each search + ${FA_JUDGE} judged${check ? ", with profile lookups" : ""})`,
126
+ };
127
+ },
128
+ ceiling: quote("company", [...FA_PLATFORMS], true, FA_CANDIDATES_MAX, false),
129
+ };
130
+ }
131
+ /** The unit meter this lane's rule states, or undefined. */
132
+ export function unitMeter(e) {
133
+ if (e.pricing.model !== "metered")
134
+ return undefined;
135
+ return placesMeter(e) ?? segmentsMeter(e) ?? keywordSplitMeter(e) ?? findAccountsMeter(e);
136
+ }
137
+ //# sourceMappingURL=unit-meters.js.map
@@ -12,6 +12,26 @@ export interface IncludeAddOn {
12
12
  credits: number;
13
13
  }
14
14
  export declare function includeAddOns(e: Endpoint): IncludeAddOn[];
15
+ export interface RowMeter {
16
+ /** Credits held for this `limit` (the limit's own default when none is sent). */
17
+ hold(limit: unknown): number;
18
+ /** What the largest allowed `limit` holds; undefined when the limit has no maximum. */
19
+ ceiling: number | undefined;
20
+ }
21
+ /**
22
+ * A metered band whose rule says what a `limit` holds: "holds `ceil(limit / 4)`
23
+ * (at least 3)" or "holds limit x 107". The default limit is the one in the
24
+ * `limit` param's own text ("Default 300").
25
+ */
26
+ export declare function rowMeter(e: Endpoint): RowMeter | undefined;
27
+ /**
28
+ * The exact hold of a batch whose rule prices each handle on its own platform
29
+ * (`prism/profiles`): each handle's profile price, and the insights hold on
30
+ * the platforms that carry insights when `include` has it. Undefined when the
31
+ * call joins posts or comments (their pages are the band's ceiling), or a
32
+ * handle's platform has no profile price here.
33
+ */
34
+ export declare function perHandleHold(e: Endpoint, params: Record<string, unknown>): number | undefined;
15
35
  /** Credits the value-priced params and include add-ons of this call add to the page price. */
16
36
  export declare function valueAndAddOnCredits(e: Endpoint, params: Record<string, unknown>): number;
17
37
  /** The most the value-priced params and include add-ons can add (for the band check). */