socialcrawl-mcp 2.0.0 → 2.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +94 -112
- package/dist/client.d.ts +2 -0
- package/dist/client.js +4 -0
- package/dist/constants.d.ts +10 -1
- package/dist/constants.js +10 -1
- package/dist/cost-guard.d.ts +8 -1
- package/dist/cost-guard.js +21 -9
- package/dist/data/docs-handwritten.js +4 -3
- package/dist/data/docs.js +1 -1
- package/dist/data/endpoints.js +65 -33
- package/dist/data/examples.js +1 -1
- package/dist/data/guide.d.ts +1 -1
- package/dist/data/guide.js +1 -1
- package/dist/data/outputs.js +218 -217
- package/dist/data/platforms.js +1 -1
- package/dist/data/recipes.js +1 -1
- package/dist/data/registry-meta.d.ts +4 -4
- package/dist/data/registry-meta.js +4 -4
- package/dist/endpoint-resolve.d.ts +10 -0
- package/dist/endpoint-resolve.js +34 -0
- package/dist/format/shape.d.ts +6 -0
- package/dist/format/shape.js +64 -0
- package/dist/freshness.d.ts +27 -4
- package/dist/freshness.js +42 -19
- package/dist/oauth/jwt-verifier.js +7 -0
- package/dist/oauth/resource-server.d.ts +3 -1
- package/dist/oauth/resource-server.js +12 -2
- package/dist/oauth/scopes.d.ts +13 -0
- package/dist/oauth/scopes.js +33 -0
- package/dist/result.d.ts +2 -0
- package/dist/result.js +8 -0
- package/dist/schemas/normalize.d.ts +27 -0
- package/dist/schemas/normalize.js +189 -0
- package/dist/schemas/outputs.d.ts +51 -31
- package/dist/schemas/outputs.js +10 -4
- package/dist/schemas/tools.d.ts +43 -8
- package/dist/schemas/tools.js +20 -7
- package/dist/server.js +17 -12
- package/dist/tools/cohorts.d.ts +3 -1
- package/dist/tools/cohorts.js +11 -10
- package/dist/tools/collect.d.ts +7 -3
- package/dist/tools/collect.js +110 -9
- package/dist/tools/discover.js +22 -27
- package/dist/tools/endpoint.js +9 -5
- package/dist/tools/estimate.js +53 -9
- package/dist/tools/find.d.ts +4 -0
- package/dist/tools/find.js +276 -9
- package/dist/tools/manage.d.ts +4 -0
- package/dist/tools/manage.js +106 -4
- package/dist/tools/monitors.d.ts +8 -1
- package/dist/tools/monitors.js +17 -12
- package/dist/tools/pricing.d.ts +1 -5
- package/dist/tools/pricing.js +17 -0
- package/dist/tools/request.d.ts +2 -11
- package/dist/tools/request.js +123 -74
- package/dist/tools/web.d.ts +3 -1
- package/dist/tools/web.js +4 -3
- package/dist/types.d.ts +9 -4
- package/package.json +2 -2
package/dist/tools/find.js
CHANGED
|
@@ -1,16 +1,21 @@
|
|
|
1
1
|
import { apiRequest } from "../client.js";
|
|
2
2
|
import { DISCOVERY_TIMEOUT_MS, noteRoute, routeMissing } from "../discovery-routes.js";
|
|
3
3
|
import { findPlatform, PLATFORMS } from "../data/platforms.js";
|
|
4
|
+
import { findEndpoint } from "../data/endpoints.js";
|
|
5
|
+
import { DOCS } from "../data/docs.js";
|
|
6
|
+
import { outputsFor } from "../data/outputs.js";
|
|
4
7
|
import { localQuote, fetchEstimateData } from "../cost-guard.js";
|
|
5
8
|
import { bestCaseCost, formatCost, worstCaseCost } from "../pricing.js";
|
|
6
9
|
import { errorFromText } from "../result.js";
|
|
7
10
|
import { searchTasks, suggestPlatforms } from "../search/catalog.js";
|
|
11
|
+
import { manageDocs } from "../search/manage-docs.js";
|
|
8
12
|
import { listEndpoints } from "./list-endpoints.js";
|
|
9
13
|
import { listPlatforms } from "./list-platforms.js";
|
|
10
14
|
import { JOB_ACTION_RESOURCES } from "./manage.js";
|
|
11
15
|
import { normalizeEndpointId } from "./discover.js";
|
|
12
16
|
import { resolveEndpoint } from "./request.js";
|
|
13
17
|
import { WEB_ACTION_RESOURCES } from "./web.js";
|
|
18
|
+
import { pageSizeOf } from "../walk-quote.js";
|
|
14
19
|
const DEFAULT_LIMIT = 3;
|
|
15
20
|
/** Candidates ranked before the resolve reorder and the limit cut. */
|
|
16
21
|
const POOL = 20;
|
|
@@ -68,6 +73,7 @@ export function readTask(task) {
|
|
|
68
73
|
quoted: q ? (q[1] ?? q[2]) : undefined,
|
|
69
74
|
rankQuery: [rest, ...names].join(" ").replace(/\s+/g, " ").trim(),
|
|
70
75
|
urlPlatforms,
|
|
76
|
+
text: rest.replace(/\s+/g, " ").trim(),
|
|
71
77
|
};
|
|
72
78
|
}
|
|
73
79
|
const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
@@ -130,6 +136,17 @@ function readMeta(o) {
|
|
|
130
136
|
m.note = o.note;
|
|
131
137
|
return m;
|
|
132
138
|
}
|
|
139
|
+
/** A record's scalar values as strings (the API's params_filled). */
|
|
140
|
+
function stringValues(v) {
|
|
141
|
+
if (!isObj(v))
|
|
142
|
+
return {};
|
|
143
|
+
const out = {};
|
|
144
|
+
for (const [k, x] of Object.entries(v)) {
|
|
145
|
+
if (typeof x === "string" || typeof x === "number" || typeof x === "boolean")
|
|
146
|
+
out[k] = String(x);
|
|
147
|
+
}
|
|
148
|
+
return out;
|
|
149
|
+
}
|
|
133
150
|
/**
|
|
134
151
|
* `GET /v1/utility/find`. Undefined only when there is no answer to use (not
|
|
135
152
|
* deployed, network error, timeout, unparseable, or an empty list with no
|
|
@@ -163,6 +180,7 @@ async function apiFind(ctx, params, limit) {
|
|
|
163
180
|
method: typeof item.method === "string" ? item.method.toUpperCase() : undefined,
|
|
164
181
|
summary: typeof item.summary === "string" ? item.summary : undefined,
|
|
165
182
|
why: typeof item.why === "string" ? item.why : undefined,
|
|
183
|
+
filled: stringValues(item.params_filled ?? item.params),
|
|
166
184
|
meta: readMeta(item),
|
|
167
185
|
});
|
|
168
186
|
}
|
|
@@ -207,7 +225,7 @@ function fill(e, facts, resolved) {
|
|
|
207
225
|
const lane = r.endpoints.find((x) => x.id === id);
|
|
208
226
|
if (lane) {
|
|
209
227
|
const value = r.canonical[lane.param] ?? (lane.param === "url" ? r.canonical.url ?? r.input : undefined) ?? r.input;
|
|
210
|
-
return { [lane.param]: value };
|
|
228
|
+
return { [lane.param]: value, ...(e.method === "POST" ? batchFill(e, facts) : {}), ...recencyFill(e, facts) };
|
|
211
229
|
}
|
|
212
230
|
}
|
|
213
231
|
const names = new Set(paramNames(e));
|
|
@@ -230,8 +248,101 @@ function fill(e, facts, resolved) {
|
|
|
230
248
|
if (textParam)
|
|
231
249
|
out[textParam] = facts.quoted;
|
|
232
250
|
}
|
|
251
|
+
if (e.method === "POST")
|
|
252
|
+
Object.assign(out, batchFill(e, facts));
|
|
253
|
+
Object.assign(out, recencyFill(e, facts));
|
|
254
|
+
return out;
|
|
255
|
+
}
|
|
256
|
+
/** The platforms a task names in words ("on tiktok", "Instagram"). */
|
|
257
|
+
function namedPlatforms(text) {
|
|
258
|
+
const t = ` ${text.toLowerCase()} `;
|
|
259
|
+
return PLATFORMS.filter((p) => new RegExp(`[^a-z0-9_](${p.slug}|${p.name.toLowerCase().replace(/[^a-z0-9]+/g, "\\W?")})[^a-z0-9_]`).test(t)).map((p) => p.slug);
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* A batch POST endpoint's list param, from every URL and @handle in the task,
|
|
263
|
+
* shaped like the param's own registry example: a list of URLs (`urls`), of
|
|
264
|
+
* handles (`handles`), or of objects keyed like the example's first item
|
|
265
|
+
* (`{ <..._url>: url }`, `{ platform, handle }`). JSON-encoded here; the
|
|
266
|
+
* suggested call carries it as a real array.
|
|
267
|
+
*/
|
|
268
|
+
function batchFill(e, facts) {
|
|
269
|
+
const out = {};
|
|
270
|
+
for (const p of [...e.params, ...e.optionalParams]) {
|
|
271
|
+
let example;
|
|
272
|
+
try {
|
|
273
|
+
example = JSON.parse(p.example ?? "");
|
|
274
|
+
}
|
|
275
|
+
catch {
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
if (!Array.isArray(example) || example.length === 0)
|
|
279
|
+
continue;
|
|
280
|
+
const first = example[0];
|
|
281
|
+
let list = [];
|
|
282
|
+
if (typeof first === "string") {
|
|
283
|
+
if (/urls?$/i.test(p.name))
|
|
284
|
+
list = facts.urls;
|
|
285
|
+
else if (/handles?$/i.test(p.name))
|
|
286
|
+
list = facts.handles;
|
|
287
|
+
}
|
|
288
|
+
else if (isObj(first)) {
|
|
289
|
+
const keys = Object.keys(first);
|
|
290
|
+
const urlKey = keys.find((k) => /url$/i.test(k));
|
|
291
|
+
if (urlKey && facts.urls.length > 0)
|
|
292
|
+
list = facts.urls.map((u) => ({ [urlKey]: u }));
|
|
293
|
+
else if (keys.includes("platform") && keys.includes("handle") && facts.handles.length > 0) {
|
|
294
|
+
const platforms = namedPlatforms(facts.text);
|
|
295
|
+
list = platforms.flatMap((platform) => facts.handles.map((handle) => ({ platform, handle })));
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
if (list.length > 0)
|
|
299
|
+
out[p.name] = JSON.stringify(list);
|
|
300
|
+
}
|
|
233
301
|
return out;
|
|
234
302
|
}
|
|
303
|
+
/** Sort values that mean newest first, best first. */
|
|
304
|
+
const RECENCY_VALUES = [/^recent$/i, /^most[_-]?recent$/i, /^newest$/i, /^latest$/i, /^new$/i, /^recency$/i, /^date[_-]?posted$/i, /^date$/i, /^chronological$/i, /^created$/i, /^creation_time_descend$/i, /^time$/i, /^pub_date$/i, /^newly_listed$/i];
|
|
305
|
+
const SORT_PARAMS = new Set(["sort", "sort_by", "sortBy", "order", "order_by", "sort_order"]);
|
|
306
|
+
/**
|
|
307
|
+
* "Newest", "most recent", "latest": the endpoint's own newest-first sort
|
|
308
|
+
* value (read from its enum), and, when it can read several pages before
|
|
309
|
+
* sorting (`scan_pages`), enough pages for the count the task asks for.
|
|
310
|
+
*/
|
|
311
|
+
function recencyFill(e, facts) {
|
|
312
|
+
if (!/\b(newest|most\s+recent|latest|recent|new(?:er)?\s+first)\b/i.test(facts.text))
|
|
313
|
+
return {};
|
|
314
|
+
const out = {};
|
|
315
|
+
for (const o of e.optionalParams) {
|
|
316
|
+
if (!SORT_PARAMS.has(o.name) || !o.enumValues)
|
|
317
|
+
continue;
|
|
318
|
+
const value = RECENCY_VALUES.map((re) => o.enumValues.find((v) => re.test(v))).find((v) => v !== undefined);
|
|
319
|
+
if (value) {
|
|
320
|
+
out[o.name] = value;
|
|
321
|
+
break;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
if (Object.keys(out).length === 0)
|
|
325
|
+
return {};
|
|
326
|
+
const scan = e.optionalParams.find((o) => o.name === "scan_pages");
|
|
327
|
+
const count = Number(/\b(\d{1,5})\b/.exec(facts.text)?.[1]);
|
|
328
|
+
const size = pageSizeOf(e);
|
|
329
|
+
if (scan && Number.isFinite(count) && count > 0 && size) {
|
|
330
|
+
const pages = Math.min(scan.maximum ?? Number.POSITIVE_INFINITY, Math.max(scan.minimum ?? 1, Math.ceil(count / size)));
|
|
331
|
+
out.scan_pages = String(pages);
|
|
332
|
+
}
|
|
333
|
+
return out;
|
|
334
|
+
}
|
|
335
|
+
/** A JSON-encoded list (from batchFill) back as the array the API takes. */
|
|
336
|
+
const asSent = (v) => {
|
|
337
|
+
if (!v.startsWith("["))
|
|
338
|
+
return v;
|
|
339
|
+
try {
|
|
340
|
+
return JSON.parse(v);
|
|
341
|
+
}
|
|
342
|
+
catch {
|
|
343
|
+
return v;
|
|
344
|
+
}
|
|
345
|
+
};
|
|
235
346
|
function missing(e, filled) {
|
|
236
347
|
const out = e.params.filter((p) => p.required && filled[p.name] === undefined).map((p) => p.name);
|
|
237
348
|
for (const group of e.oneOfGroups) {
|
|
@@ -252,13 +363,42 @@ function callFor(e, filled) {
|
|
|
252
363
|
const { job_id, ...input } = filled;
|
|
253
364
|
return { tool: "socialcrawl_manage", arguments: { area: "jobs", action: job.action, ...(job_id ? { id: job_id } : {}), input } };
|
|
254
365
|
}
|
|
366
|
+
const { params, body } = splitForMethod(e, filled);
|
|
255
367
|
return {
|
|
256
368
|
tool: "socialcrawl_request",
|
|
257
369
|
arguments: {
|
|
258
370
|
platform: e.platform,
|
|
259
371
|
resource: e.resource,
|
|
260
372
|
...(e.method !== "GET" ? { method: e.method } : {}),
|
|
261
|
-
params:
|
|
373
|
+
...(params ? { params } : {}),
|
|
374
|
+
...(body ? { body } : {}),
|
|
375
|
+
},
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
/** A POST endpoint reads its fields from the JSON body (query-only params stay in params). */
|
|
379
|
+
function splitForMethod(e, filled) {
|
|
380
|
+
if (e.method !== "POST")
|
|
381
|
+
return { params: filled };
|
|
382
|
+
const params = {};
|
|
383
|
+
const body = {};
|
|
384
|
+
for (const [k, v] of Object.entries(filled)) {
|
|
385
|
+
if (e.optionalParams.find((o) => o.name === k)?.in === "query")
|
|
386
|
+
params[k] = v;
|
|
387
|
+
else
|
|
388
|
+
body[k] = asSent(v);
|
|
389
|
+
}
|
|
390
|
+
return { ...(Object.keys(params).length > 0 ? { params } : {}), body };
|
|
391
|
+
}
|
|
392
|
+
/** The ready socialcrawl_estimate call for this endpoint with these params. */
|
|
393
|
+
function estimateFor(e, filled) {
|
|
394
|
+
const { params, body } = splitForMethod(e, filled);
|
|
395
|
+
return {
|
|
396
|
+
tool: "socialcrawl_estimate",
|
|
397
|
+
arguments: {
|
|
398
|
+
id: `${e.platform}/${e.resource}`,
|
|
399
|
+
...(e.method !== "GET" ? { method: e.method } : {}),
|
|
400
|
+
...(params && Object.keys(params).length > 0 ? { params } : {}),
|
|
401
|
+
...(body && Object.keys(body).length > 0 ? { body } : {}),
|
|
262
402
|
},
|
|
263
403
|
};
|
|
264
404
|
}
|
|
@@ -336,7 +476,7 @@ export async function findStructured(ctx, params) {
|
|
|
336
476
|
let pool;
|
|
337
477
|
const source = apiHits ? "api" : "local";
|
|
338
478
|
if (apiHits) {
|
|
339
|
-
pool = apiHits.map((h) => ({ id: h.id, endpoint: bundled(h.id, h.method), summary: h.summary, why: h.why, meta: h.meta }));
|
|
479
|
+
pool = apiHits.map((h) => ({ id: h.id, endpoint: bundled(h.id, h.method), summary: h.summary, why: h.why, filled: h.filled, meta: h.meta }));
|
|
340
480
|
}
|
|
341
481
|
else {
|
|
342
482
|
const query = facts.rankQuery || task;
|
|
@@ -349,15 +489,25 @@ export async function findStructured(ctx, params) {
|
|
|
349
489
|
if (resolvedIds.size > 0) {
|
|
350
490
|
pool = [...pool.filter((c) => resolvedIds.has(c.id)), ...pool.filter((c) => !resolvedIds.has(c.id))];
|
|
351
491
|
}
|
|
492
|
+
const watch = wantsMonitor(task);
|
|
493
|
+
// A monitoring task gets one scheduling pointer (below), not the ranker's generic area doc.
|
|
494
|
+
if (watch)
|
|
495
|
+
pool = pool.filter((c) => c.manage?.area !== "monitors");
|
|
352
496
|
const top = pool.slice(0, limit);
|
|
353
|
-
const
|
|
497
|
+
const endpointResults = await Promise.all(top.map(async (c) => {
|
|
354
498
|
if (c.manage)
|
|
355
499
|
return manageResult(c.manage);
|
|
356
500
|
const e = c.endpoint;
|
|
357
501
|
if (!e) {
|
|
358
|
-
return { id: c.id, summary: c.summary ?? c.why ?? "", params_filled: {}, params_missing: [], bundled: false, ...c.meta };
|
|
502
|
+
return { id: c.id, summary: c.summary ?? c.why ?? "", params_filled: c.filled ?? {}, params_missing: [], bundled: false, ...c.meta };
|
|
359
503
|
}
|
|
360
|
-
|
|
504
|
+
// The API's params_filled wins over what was read locally from the task,
|
|
505
|
+
// except a whole list built from every URL / handle in it (the API fills one).
|
|
506
|
+
const local = fill(e, facts, resolved);
|
|
507
|
+
const filled = { ...local, ...(c.filled ?? {}) };
|
|
508
|
+
for (const [k, v] of Object.entries(local))
|
|
509
|
+
if (v.startsWith("["))
|
|
510
|
+
filled[k] = v;
|
|
361
511
|
const miss = missing(e, filled);
|
|
362
512
|
return {
|
|
363
513
|
id: c.id,
|
|
@@ -368,9 +518,12 @@ export async function findStructured(ctx, params) {
|
|
|
368
518
|
params_filled: filled,
|
|
369
519
|
params_missing: miss,
|
|
370
520
|
call: callFor(e, filled),
|
|
521
|
+
estimate: estimateFor(e, filled),
|
|
371
522
|
...c.meta,
|
|
372
523
|
};
|
|
373
524
|
}));
|
|
525
|
+
const pointer = watch ? monitorPointer(task, facts, top, endpointResults) : undefined;
|
|
526
|
+
const results = pointer ? [pointer, ...endpointResults] : endpointResults;
|
|
374
527
|
const structured = { ok: true, source, results, ...metaFields(topMeta) };
|
|
375
528
|
const unbundled = results.filter((r) => "bundled" in r && r.bundled === false).map((r) => r.id);
|
|
376
529
|
if (unbundled.length > 0)
|
|
@@ -380,6 +533,109 @@ export async function findStructured(ctx, params) {
|
|
|
380
533
|
}
|
|
381
534
|
return { text: render(task, source, results, topMeta), structured };
|
|
382
535
|
}
|
|
536
|
+
/**
|
|
537
|
+
* Words that ask for something to run on a schedule or fire on a change,
|
|
538
|
+
* rather than one read now: alert, notify, monitor, watch, every day/week,
|
|
539
|
+
* schedule, "when ... posts/changes".
|
|
540
|
+
*/
|
|
541
|
+
const MONITOR_INTENT = /\b(alerts?|alerting|notify|notifications?|monitor(?:s|ing)?|watch(?:ing)?|schedul(?:e|ed|ing)|recurring|daily|weekly|hourly|nightly|whenever|every\s+(?:day|week|hour|morning|evening|night|month|monday|tuesday|wednesday|thursday|friday|saturday|sunday))\b|\btrack\w*\b[^.?!]{0,60}\bover\s+time\b|\bwhen\b[^.?!]{0,60}\b(posts?|posted|uploads?|changes?|changed|updates?|updated|publish(?:es)?|goes\s+live|drops?)\b/i;
|
|
542
|
+
/** Read on the task's words only: URLs and handles are taken out first (a YouTube `watch?v=` is not intent). */
|
|
543
|
+
export const wantsMonitor = (task) => MONITOR_INTENT.test(readTask(task).text);
|
|
544
|
+
/** The cadence a task asks for: hourly, weekly, else daily. */
|
|
545
|
+
function cadenceOf(task) {
|
|
546
|
+
if (/\b(hourly|every\s+hour)\b/i.test(task))
|
|
547
|
+
return "hourly";
|
|
548
|
+
if (/\b(weekly|every\s+(?:week|monday|tuesday|wednesday|thursday|friday|saturday|sunday)|each\s+week)\b/i.test(task))
|
|
549
|
+
return "weekly";
|
|
550
|
+
return "daily";
|
|
551
|
+
}
|
|
552
|
+
const firstSentence = (text) => /^.*?[.!?](?=\s|$)/.exec(text)?.[0] ?? text;
|
|
553
|
+
const CADENCE_MINUTES = { hourly: 60, daily: 1440, weekly: 10080 };
|
|
554
|
+
/** Replace with the caller's own HTTPS endpoint (listed in params_missing). */
|
|
555
|
+
const WEBHOOK_PLACEHOLDER = "https://your-server.example/socialcrawl-webhook";
|
|
556
|
+
/** A task about new items: "new video", "posts", "uploads". */
|
|
557
|
+
const NEW_ITEMS = /\bnew\b|\b(posts?|uploads?|publish(?:es)?)\b/i;
|
|
558
|
+
/**
|
|
559
|
+
* The new-items alert as the bundled monitors guide documents it: its
|
|
560
|
+
* rows_new rule (only on a tracking monitor), its webhook-only-on-alert
|
|
561
|
+
* switch, and a track over one of the recipe's numeric row fields (from the
|
|
562
|
+
* endpoint's output contract). Undefined when the guide or the contract has
|
|
563
|
+
* no such pattern.
|
|
564
|
+
*/
|
|
565
|
+
function newItemsAlert(e) {
|
|
566
|
+
const guide = DOCS.monitors ?? "";
|
|
567
|
+
const rule = /\{"metric":"rows_new"[^}]*\}/.exec(guide);
|
|
568
|
+
if (!rule)
|
|
569
|
+
return undefined;
|
|
570
|
+
let parsed;
|
|
571
|
+
try {
|
|
572
|
+
parsed = JSON.parse(rule[0]);
|
|
573
|
+
}
|
|
574
|
+
catch {
|
|
575
|
+
return undefined;
|
|
576
|
+
}
|
|
577
|
+
const out = outputsFor(e);
|
|
578
|
+
const rowsAt = out?.rows_at ?? "";
|
|
579
|
+
if (!rowsAt.startsWith("data.items[]"))
|
|
580
|
+
return undefined;
|
|
581
|
+
const numeric = (out?.fields ?? []).filter((f) => /number|integer/.test(f.type) && !/published|_at$|epoch/.test(f.path));
|
|
582
|
+
const metric = numeric.find((f) => /engagement\.views$/.test(f.path)) ?? numeric.find((f) => /engagement\./.test(f.path)) ?? numeric[0];
|
|
583
|
+
if (!metric)
|
|
584
|
+
return undefined;
|
|
585
|
+
return {
|
|
586
|
+
track: { metrics: [`items[].${metric.path}`] },
|
|
587
|
+
alert_rules: [parsed],
|
|
588
|
+
...(/suppress_webhook_unless_alert/.test(guide) ? { suppress_webhook_unless_alert: true } : {}),
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
/**
|
|
592
|
+
* For a monitoring task, where to schedule it: a web change monitor for a
|
|
593
|
+
* page's URL ("notify me when this page changes"), else a recipe monitor over
|
|
594
|
+
* the best endpoint result, with its filled params and the cadence the task
|
|
595
|
+
* asks for. The call validates first (dry_run: true); the area's own text
|
|
596
|
+
* comes from the bundled manage docs.
|
|
597
|
+
*/
|
|
598
|
+
function monitorPointer(task, facts, pool, results) {
|
|
599
|
+
const cadence = cadenceOf(task);
|
|
600
|
+
const pageUrl = facts.urls.find((u) => {
|
|
601
|
+
const p = platformFromUrl(u);
|
|
602
|
+
return !p || p === "web";
|
|
603
|
+
});
|
|
604
|
+
if (pageUrl && /\b(chang\w*|updat\w*|page|site|website|differ\w*)\b/i.test(task)) {
|
|
605
|
+
const e = findEndpoint("web", "monitors", "POST");
|
|
606
|
+
const input = { url: pageUrl, cadence_minutes: CADENCE_MINUTES[cadence] };
|
|
607
|
+
return {
|
|
608
|
+
id: "web/monitors",
|
|
609
|
+
kind: "manage",
|
|
610
|
+
area: "web",
|
|
611
|
+
action: "monitor_create",
|
|
612
|
+
summary: `Schedule a change check of ${pageUrl} (${cadence}). ${e?.purpose?.summary ?? e?.summary ?? ""}`.trim(),
|
|
613
|
+
params_filled: { url: pageUrl, cadence_minutes: String(input.cadence_minutes) },
|
|
614
|
+
params_missing: [],
|
|
615
|
+
call: { tool: "socialcrawl_manage", arguments: { area: "web", action: "monitor_create", dry_run: true, input } },
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
const recipe = results.find((r) => r.kind !== "manage" && r.bundled !== false && !r.id.startsWith("web/") && pool.some((c) => c.id === r.id && c.endpoint));
|
|
619
|
+
const doc = manageDocs().find((d) => d.area === "monitors");
|
|
620
|
+
const recipeEndpoint = recipe ? pool.find((c) => c.id === recipe.id)?.endpoint : undefined;
|
|
621
|
+
const alert = NEW_ITEMS.test(task) && recipeEndpoint ? newItemsAlert(recipeEndpoint) : undefined;
|
|
622
|
+
const input = {
|
|
623
|
+
...(recipe ? { recipe: recipe.id, params: recipe.params_filled } : {}),
|
|
624
|
+
cadence,
|
|
625
|
+
webhook_url: WEBHOOK_PLACEHOLDER,
|
|
626
|
+
...(alert ?? {}),
|
|
627
|
+
};
|
|
628
|
+
return {
|
|
629
|
+
id: "monitors",
|
|
630
|
+
kind: "manage",
|
|
631
|
+
area: "monitors",
|
|
632
|
+
action: "create",
|
|
633
|
+
summary: `Schedule ${recipe ? recipe.id : "a recipe"} ${cadence}; ${alert ? "the webhook fires only when a run finds new rows (rows_new on a tracking monitor)" : "each run's result goes to your webhook"}. ${firstSentence(doc?.summary ?? "")}`.trim(),
|
|
634
|
+
params_filled: { ...(recipe ? { recipe: recipe.id } : {}), cadence },
|
|
635
|
+
params_missing: [...(recipe ? [] : ["recipe"]), "webhook_url"],
|
|
636
|
+
call: { tool: "socialcrawl_manage", arguments: { area: "monitors", action: "create", dry_run: true, input } },
|
|
637
|
+
};
|
|
638
|
+
}
|
|
383
639
|
/**
|
|
384
640
|
* A stateful family as a result: not one call but an area of socialcrawl_manage,
|
|
385
641
|
* started by its first action. Free of params until that action's input is known.
|
|
@@ -432,6 +688,7 @@ async function planOutput(ctx, task, steps) {
|
|
|
432
688
|
params_missing: st.missing,
|
|
433
689
|
...(st.binds ? { binds: st.binds } : {}),
|
|
434
690
|
call: callFor(e, st.params),
|
|
691
|
+
estimate: estimateFor(e, st.params),
|
|
435
692
|
};
|
|
436
693
|
}));
|
|
437
694
|
const structured = { ok: true, source: "plan", results };
|
|
@@ -442,11 +699,11 @@ async function planOutput(ctx, task, steps) {
|
|
|
442
699
|
}
|
|
443
700
|
function render(task, source, results, meta = {}) {
|
|
444
701
|
const uncertain = meta.uncertain === true || results.some((r) => r.uncertain === true);
|
|
445
|
-
const lines = uncertain ? [UNCERTAIN_LINE] : [];
|
|
702
|
+
const lines = uncertain && results.length > 0 ? [UNCERTAIN_LINE] : [];
|
|
446
703
|
const top = metaLine(meta);
|
|
447
704
|
if (results.length === 0) {
|
|
448
705
|
lines.push(source === "api" && meta.reason
|
|
449
|
-
? `No endpoint for "${task}" (${top}).`
|
|
706
|
+
? `No endpoint for "${task}" (${top}). SocialCrawl only reads public data; it can't post, reply, like, follow, message or manage accounts. It can read the comments or the post itself instead.`
|
|
450
707
|
: `No endpoint matches "${task}". Try other words, or socialcrawl_find with a platform and no task to list that platform's endpoints.`);
|
|
451
708
|
return lines.join("\n");
|
|
452
709
|
}
|
|
@@ -457,7 +714,15 @@ function render(task, source, results, meta = {}) {
|
|
|
457
714
|
results.forEach((r, i) => {
|
|
458
715
|
if (r.kind === "manage") {
|
|
459
716
|
lines.push(`${i + 1}. ${r.id} (socialcrawl_manage area "${r.area}") - ${r.summary ?? ""}`);
|
|
460
|
-
|
|
717
|
+
if (r.actions)
|
|
718
|
+
lines.push(` Actions: ${r.actions.join(", ")}. Read first: socialcrawl_endpoint with id "${r.id}".`);
|
|
719
|
+
else {
|
|
720
|
+
const needs = r.params_missing.length > 0 ? ` Replace or add ${r.params_missing.join(", ")} in input.` : "";
|
|
721
|
+
const input = (r.call?.arguments?.input ?? {});
|
|
722
|
+
if (input.track && input.alert_rules)
|
|
723
|
+
lines.push(" Keep track and alert_rules together: the rows_new alert needs track.");
|
|
724
|
+
lines.push(` To run it on a schedule:${needs} dry_run: true validates and quotes it without creating anything; repeat without dry_run to create it.`);
|
|
725
|
+
}
|
|
461
726
|
if (r.call)
|
|
462
727
|
lines.push(` Call: ${JSON.stringify(r.call)}`);
|
|
463
728
|
return;
|
|
@@ -476,6 +741,8 @@ function render(task, source, results, meta = {}) {
|
|
|
476
741
|
lines.push(` Filled from earlier rows: ${Object.entries(r.binds).map(([k, v]) => `${k} <- ${v}`).join(", ")}`);
|
|
477
742
|
if (r.call)
|
|
478
743
|
lines.push(` Call: ${JSON.stringify(r.call)}`);
|
|
744
|
+
if (r.estimate)
|
|
745
|
+
lines.push(` Estimate: ${JSON.stringify(r.estimate)}`);
|
|
479
746
|
const rowMeta = metaLine({ uncertain: r.uncertain, reason: r.reason, source: r.source, ...("confidence" in r ? { confidence: r.confidence } : {}), note: r.note });
|
|
480
747
|
if (r.uncertain === true || rowMeta)
|
|
481
748
|
lines.push(` ${r.uncertain === true ? "Uncertain" : "Match"}: ${rowMeta ?? "unconfirmed"}`);
|
package/dist/tools/manage.d.ts
CHANGED
|
@@ -15,7 +15,11 @@ export interface ManageParams {
|
|
|
15
15
|
id?: string;
|
|
16
16
|
input?: Record<string, unknown>;
|
|
17
17
|
idempotencyKey?: string;
|
|
18
|
+
/** Validate and quote a create/update without creating it (`?dry_run=1`). */
|
|
19
|
+
dry_run?: boolean;
|
|
18
20
|
}
|
|
21
|
+
/** The actions a dry run can stand in for, per area. */
|
|
22
|
+
export declare const DRY_RUN_ACTIONS: Record<ManageArea, string[]>;
|
|
19
23
|
/** The `jobs` area's actions and the prism endpoints they call. */
|
|
20
24
|
export declare const JOB_ACTION_RESOURCES: {
|
|
21
25
|
action: "submit" | "list" | "get";
|
package/dist/tools/manage.js
CHANGED
|
@@ -1,9 +1,92 @@
|
|
|
1
|
+
import { apiRequest } from "../client.js";
|
|
1
2
|
import { errorFromText, isErrorText } from "../result.js";
|
|
2
3
|
import { CohortsInputSchema, MonitorsInputSchema, WebInputSchema } from "../schemas/tools.js";
|
|
3
4
|
import { cohorts } from "./cohorts.js";
|
|
4
5
|
import { monitors } from "./monitors.js";
|
|
5
6
|
import { requestStructured } from "./request.js";
|
|
6
7
|
import { web } from "./web.js";
|
|
8
|
+
/** The actions a dry run can stand in for, per area. */
|
|
9
|
+
export const DRY_RUN_ACTIONS = {
|
|
10
|
+
monitors: ["create"],
|
|
11
|
+
web: ["monitor_create", "monitor_update"],
|
|
12
|
+
cohorts: ["create", "add_members", "query"],
|
|
13
|
+
jobs: [],
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Routes whose dry_run support is checked before the dry run is sent, with a
|
|
17
|
+
* probe that cannot create anything: an empty body and an invalid dry_run
|
|
18
|
+
* value. A route that reads dry_run refuses the value (a 400 naming dry_run);
|
|
19
|
+
* one that ignores it refuses the empty body. Web and cohort routes always
|
|
20
|
+
* answer dry_run, so they need no probe.
|
|
21
|
+
*/
|
|
22
|
+
const PROBED = { "monitors/create": "/v1/monitors" };
|
|
23
|
+
/** Asked on every dry run (free, one round trip), so an API change is picked up at once. */
|
|
24
|
+
async function supportsDryRun(ctx, path) {
|
|
25
|
+
const answer = await apiRequest(ctx, { method: "POST", path, query: { dry_run: "probe" }, body: {}, errorPlatform: "monitors" });
|
|
26
|
+
return /^Error/.test(answer) && /dry_run/i.test(answer);
|
|
27
|
+
}
|
|
28
|
+
/** How to remove what a create made, when the API ran it for real despite dry_run. */
|
|
29
|
+
const UNDO = {
|
|
30
|
+
"monitors/create": (id) => `/v1/monitors/${encodeURIComponent(id)}`,
|
|
31
|
+
"web/monitor_create": (id) => `/v1/web/monitors/${encodeURIComponent(id)}`,
|
|
32
|
+
"cohorts/create": (id) => `/v1/cohorts/${encodeURIComponent(id)}`,
|
|
33
|
+
};
|
|
34
|
+
const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
35
|
+
/** The JSON body an area's text carries (its first json block), or undefined. */
|
|
36
|
+
function bodyOf(text) {
|
|
37
|
+
const m = /```json\n([\s\S]*?)\n```/.exec(text);
|
|
38
|
+
if (!m)
|
|
39
|
+
return undefined;
|
|
40
|
+
try {
|
|
41
|
+
const v = JSON.parse(m[1]);
|
|
42
|
+
return isObj(v) ? v : undefined;
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** True when the answer is a dry run's (validation + quote), not a created or changed resource. */
|
|
49
|
+
function isDryRunAnswer(body) {
|
|
50
|
+
const layers = [body, isObj(body.data) ? body.data : {}];
|
|
51
|
+
return layers.some((l) => l.dry_run === true || typeof l.valid === "boolean" || isObj(l.estimate) || isObj(l.quote) || isObj(l.normalized_params));
|
|
52
|
+
}
|
|
53
|
+
/** The id of whatever the call created, if it created something. */
|
|
54
|
+
function createdId(body) {
|
|
55
|
+
const data = isObj(body.data) ? body.data : {};
|
|
56
|
+
const candidates = [
|
|
57
|
+
isObj(body.monitor) ? body.monitor.id : undefined,
|
|
58
|
+
isObj(data.monitor) ? data.monitor.id : undefined,
|
|
59
|
+
data.id, data.monitor_id, data.cohort_id, body.id, body.monitor_id, body.cohort_id,
|
|
60
|
+
];
|
|
61
|
+
const id = candidates.find((c) => typeof c === "string" && c.length > 0);
|
|
62
|
+
return typeof id === "string" ? id : undefined;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* A dry run's answer checked: an error (a free validation refusal) or a dry-run
|
|
66
|
+
* answer passes through; anything the API created anyway is deleted at once
|
|
67
|
+
* and the call is refused, so dry_run never leaves a resource behind.
|
|
68
|
+
*/
|
|
69
|
+
async function checkDryRun(ctx, area, action, text) {
|
|
70
|
+
if (isErrorText(text))
|
|
71
|
+
return done(text);
|
|
72
|
+
const body = bodyOf(text);
|
|
73
|
+
if (body && isDryRunAnswer(body)) {
|
|
74
|
+
return done(`Dry run: validated and quoted; nothing was created or changed.\n${text}`, { ok: true, dry_run: true });
|
|
75
|
+
}
|
|
76
|
+
const id = body ? createdId(body) : undefined;
|
|
77
|
+
const undo = id ? UNDO[`${area}/${action}`] : undefined;
|
|
78
|
+
let cleanup = "";
|
|
79
|
+
if (id && undo) {
|
|
80
|
+
const del = await apiRequest(ctx, { method: "DELETE", path: undo(id), errorPlatform: area });
|
|
81
|
+
cleanup = /^Error/.test(del)
|
|
82
|
+
? ` It created ${id}, and deleting it failed (${del.split("\n")[0]}): delete it with action "${area === "web" ? "monitor_delete" : "delete"}" and id "${id}".`
|
|
83
|
+
: ` It created ${id}, which was deleted at once.`;
|
|
84
|
+
}
|
|
85
|
+
else if (id || !body) {
|
|
86
|
+
cleanup = ` The API applied the call${id ? ` (${id})` : ""}; check it with the matching get action.`;
|
|
87
|
+
}
|
|
88
|
+
return done(`Error: dry_run is not supported by the API for ${area} ${action} yet, so this was refused rather than run.${cleanup} Nothing was kept. Check the fields against socialcrawl_endpoint id "${area}", or repeat without dry_run to create it for real.`);
|
|
89
|
+
}
|
|
7
90
|
const optionsOf = (schema) => schema.shape.action.options;
|
|
8
91
|
/** The `jobs` area's actions and the prism endpoints they call. */
|
|
9
92
|
export const JOB_ACTION_RESOURCES = [
|
|
@@ -30,17 +113,36 @@ function invalid(area, err) {
|
|
|
30
113
|
`Actions: ${MANAGE_ACTIONS[area].join(", ")}. Put the action's fields in \`input\` and the resource id in \`id\`.`,
|
|
31
114
|
].join("\n"));
|
|
32
115
|
}
|
|
116
|
+
const truthy = (v) => v === true || v === 1 || v === "1" || v === "true";
|
|
33
117
|
export async function manage(ctx, p) {
|
|
34
118
|
const actions = MANAGE_ACTIONS[p.area];
|
|
35
119
|
if (!actions.includes(p.action)) {
|
|
36
120
|
return done(`Error: Unknown action "${p.action}" for area "${p.area}". Actions: ${actions.join(", ")}.`);
|
|
37
121
|
}
|
|
38
|
-
|
|
122
|
+
// dry_run is a top-level flag; one inside input counts too, and never reaches the body.
|
|
123
|
+
const { dry_run: inputDryRun, ...rest } = p.input ?? {};
|
|
124
|
+
const dryRun = p.dry_run === true || truthy(inputDryRun);
|
|
125
|
+
const input = rest;
|
|
126
|
+
if (dryRun && !DRY_RUN_ACTIONS[p.area].includes(p.action)) {
|
|
127
|
+
const ok = Object.entries(DRY_RUN_ACTIONS).flatMap(([a, list]) => list.map((x) => `${a} ${x}`));
|
|
128
|
+
return done(`Error: dry_run is only for ${ok.join(", ")}; "${p.area} ${p.action}" was not sent.`);
|
|
129
|
+
}
|
|
130
|
+
if (!dryRun)
|
|
131
|
+
return dispatch(ctx, p, input, false);
|
|
132
|
+
const probePath = PROBED[`${p.area}/${p.action}`];
|
|
133
|
+
if (probePath && ctx.apiKey && !(await supportsDryRun(ctx, probePath))) {
|
|
134
|
+
return done(`Error: dry_run is not supported by the API for ${p.area} ${p.action} yet, so nothing was sent and nothing was created. Check the fields against socialcrawl_endpoint id "${p.area}", or repeat without dry_run to create it for real.`);
|
|
135
|
+
}
|
|
136
|
+
const out = await dispatch(ctx, p, input, true);
|
|
137
|
+
return out.structured.ok === false ? out : checkDryRun(ctx, p.area, p.action, out.text);
|
|
138
|
+
}
|
|
139
|
+
/** Run one validated action; `sendDry` adds `?dry_run=1` to the API call. */
|
|
140
|
+
async function dispatch(ctx, p, input, sendDry) {
|
|
39
141
|
if (p.area === "monitors") {
|
|
40
142
|
const parsed = MonitorsInputSchema.safeParse({ ...input, action: p.action, ...(p.id ? { id: p.id } : {}) });
|
|
41
143
|
if (!parsed.success)
|
|
42
144
|
return invalid(p.area, parsed.error);
|
|
43
|
-
return done(await monitors(ctx, parsed.data));
|
|
145
|
+
return done(await monitors(ctx, parsed.data, { dryRun: sendDry }));
|
|
44
146
|
}
|
|
45
147
|
if (p.area === "web") {
|
|
46
148
|
const parsed = WebInputSchema.safeParse({
|
|
@@ -51,7 +153,7 @@ export async function manage(ctx, p) {
|
|
|
51
153
|
});
|
|
52
154
|
if (!parsed.success)
|
|
53
155
|
return invalid(p.area, parsed.error);
|
|
54
|
-
return done(await web(ctx, parsed.data));
|
|
156
|
+
return done(await web(ctx, parsed.data, { dryRun: sendDry }));
|
|
55
157
|
}
|
|
56
158
|
if (p.area === "cohorts") {
|
|
57
159
|
// A query's own id for the query_* actions; the cohort's for the rest.
|
|
@@ -64,7 +166,7 @@ export async function manage(ctx, p) {
|
|
|
64
166
|
});
|
|
65
167
|
if (!parsed.success)
|
|
66
168
|
return invalid(p.area, parsed.error);
|
|
67
|
-
return done(await cohorts(ctx, parsed.data));
|
|
169
|
+
return done(await cohorts(ctx, parsed.data, { dryRun: sendDry }));
|
|
68
170
|
}
|
|
69
171
|
// Prism background jobs: submit (POST prism/jobs), list, get one.
|
|
70
172
|
if (p.action === "get") {
|
package/dist/tools/monitors.d.ts
CHANGED
|
@@ -21,6 +21,11 @@ export interface MonitorsParams {
|
|
|
21
21
|
suppress_webhook_unless_alert?: boolean;
|
|
22
22
|
output_schema?: Record<string, unknown>;
|
|
23
23
|
webhook_secret?: string;
|
|
24
|
+
track?: {
|
|
25
|
+
metrics: string[];
|
|
26
|
+
row_key?: string;
|
|
27
|
+
max_rows?: number;
|
|
28
|
+
};
|
|
24
29
|
status?: string;
|
|
25
30
|
cursor?: string;
|
|
26
31
|
limit?: number;
|
|
@@ -29,4 +34,6 @@ export interface MonitorsParams {
|
|
|
29
34
|
include?: string;
|
|
30
35
|
metric?: string;
|
|
31
36
|
}
|
|
32
|
-
export declare function monitors(ctx: ApiContext, input: MonitorsParams
|
|
37
|
+
export declare function monitors(ctx: ApiContext, input: MonitorsParams, opts?: {
|
|
38
|
+
dryRun?: boolean;
|
|
39
|
+
}): Promise<string>;
|