@trawlme/cli 3.14.1 → 3.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -54,7 +54,7 @@ trawl create <url> --prompt <goal> [--no-autofix] [--no-digest] [--json] # url
54
54
  trawl list|ls [--json] [--status <success|failure|never|running|regression>] [--unhealthy] [--limit <n>] [--page <n>]
55
55
  trawl get <id> [--json] Get scrap details
56
56
  trawl run <id> [--watch] [--json] Run a scrap (blocks until finished)
57
- trawl trigger <id> [--watch] [--wait] [--json] Launch a scrap as a background worker (returns immediately)
57
+ trawl trigger <id> [--param <k=v>]... [--watch] [--wait] [--json] Launch a scrap as a background worker (returns immediately)
58
58
  trawl data <id> [--json] [--fresh] [--errors] Get scrap data (last persisted run — read-only, no quota; --fresh to launch one)
59
59
  trawl runs|history <id> [--json] [-n <limit>] List past runs for a scrap (newest first)
60
60
  trawl run-info <hid> [--json] Show details of a single run
@@ -109,6 +109,14 @@ trawl scraps delete <id> [--force] [--json] Alias: rm
109
109
  - `scraps banner -f <file>` only accepts `png`/`jpg`/`jpeg`/`webp`; any other extension is a usage error (exit 2) instead of silently uploading the file under a fabricated `image/png` Content-Type.
110
110
  - `scraps delete`/`banner --json` print `{"deleted":true,"id"}` / the raw upload response.
111
111
 
112
+ ### Params & scenarios
113
+
114
+ - Params stored with `scraps update -p/--params-file` are **scenarios** (test cases): every `trawl run` and scheduled run picks ONE set at random, never "the last saved set".
115
+ - `trawl trigger <id> --param k=v` (repeatable) runs the scrap once with your own values and leaves the stored sets untouched. Keys come from the first stored set (`TRAWL.` prefix optional); values are typed like that set (number, `true`/`false`, or string). Every key is required; blank values, unknown, duplicate and wrongly typed keys are refused with exit 2 (unknown or missing keys list the expected keys; type errors say "must be a number" or "must be true or false"). Works with `--wait` and the async default. `-p` is taken by `update`, so `--param` has no short form.
116
+ - Without `--param`, a scrap that has params is rejected with 422 under `--wait`; the default async trigger is acked as queued and the run then fails in the worker. Pass `--param`.
117
+ - `--param` reads the scrap first, so an API key needs `trawl:scraps:read` besides `trawl:scraps:run`.
118
+ - On a scrap with no cron, every `trigger` prints a stderr warning: the stored scenarios never run unattended.
119
+
112
120
  ### Scrap accounts
113
121
 
114
122
  ```
@@ -2,6 +2,85 @@ import { Command } from 'commander';
2
2
  type AttachOptions = {
3
3
  hidden?: boolean;
4
4
  };
5
+ interface HistoryRun {
6
+ _id?: string;
7
+ status?: boolean | null;
8
+ statusDetail?: 'success' | 'error' | 'empty' | 'regression' | null;
9
+ time?: number;
10
+ proxyTier?: string | null;
11
+ failureKind?: string | null;
12
+ block?: {
13
+ kind?: string | null;
14
+ } | null;
15
+ blockType?: string | null;
16
+ createdAt?: string;
17
+ items?: unknown[];
18
+ errorSnapshot?: {
19
+ errorMessage?: string;
20
+ selector?: string;
21
+ };
22
+ emptyContext?: EmptyContext | null;
23
+ }
24
+ interface EmptyContext {
25
+ selectors?: Record<string, number>;
26
+ page?: {
27
+ title?: string;
28
+ url?: string;
29
+ totalAnchors?: number;
30
+ topClasses?: {
31
+ class: string;
32
+ count: number;
33
+ }[];
34
+ topAnchorPaths?: {
35
+ path: string;
36
+ count: number;
37
+ }[];
38
+ };
39
+ _captureWarnings?: string[];
40
+ }
41
+ interface Scrap {
42
+ _id: string;
43
+ title: string;
44
+ request: string;
45
+ scrapper: string;
46
+ url?: string;
47
+ cron: string | null;
48
+ params?: Record<string, unknown>[];
49
+ autoFix?: boolean | null;
50
+ digest?: {
51
+ enabled: boolean;
52
+ mode: 'latest' | 'changes' | 'changes_only';
53
+ prompt: string | null;
54
+ recipient: string | null;
55
+ };
56
+ createdAt: string;
57
+ updatedAt: string;
58
+ runs?: HistoryRun[];
59
+ history?: HistoryRun[];
60
+ account?: AccountStatus;
61
+ lastCronOutcome?: 'ok' | 'quota_denied' | 'error' | 'skipped_unhealthy' | null;
62
+ consecutiveFailedRuns?: number;
63
+ unhealthySince?: string | null;
64
+ _tierOverride?: {
65
+ requestedMaxTier?: string;
66
+ effectiveMaxTier?: string | null;
67
+ refused?: boolean;
68
+ reason?: string;
69
+ provider?: string;
70
+ warning?: string | null;
71
+ proxyTier?: {
72
+ requested: string;
73
+ effective: string;
74
+ clamped: boolean;
75
+ reason?: string;
76
+ };
77
+ };
78
+ }
79
+ interface AccountStatus {
80
+ hasCredentials: boolean;
81
+ hasSession: boolean;
82
+ sessionSavedAt?: string | null;
83
+ }
5
84
  export declare const scraps: Command;
6
85
  interface BeforeRunState {
7
86
  id?: string;
@@ -24,5 +103,15 @@ export declare function attachRunCommand(parent: Command, attachOpts?: AttachOpt
24
103
  export declare function attachDataCommand(parent: Command, attachOpts?: AttachOptions): Command;
25
104
  export declare function attachRunsCommand(parent: Command, attachOpts?: AttachOptions): Command;
26
105
  export declare function attachRunInfoCommand(parent: Command, attachOpts?: AttachOptions): Command;
106
+ export declare function parseTriggerPairs(pairs: string[]): {
107
+ entries: [string, string][];
108
+ } | {
109
+ error: string;
110
+ };
111
+ export declare function buildTriggerParams(scrap: Scrap, pairs: string[]): {
112
+ body: Record<string, unknown>;
113
+ } | {
114
+ error: string;
115
+ };
27
116
  export declare function attachTriggerCommand(parent: Command, attachOpts?: AttachOptions): Command;
28
117
  export {};
@@ -141,11 +141,13 @@ async function watchActivities(id, asJson) {
141
141
  }
142
142
  }
143
143
  }
144
+ function beforeRunStateFrom(scrap) {
145
+ const top = (scrap ? runsOf(scrap) : undefined)?.[0];
146
+ return { id: top?._id, alreadyInFlight: top?.status === null, captured: true };
147
+ }
144
148
  async function captureBeforeRunState(id) {
145
149
  try {
146
- const scrap = await api.get(`/api/scraps/${id}`);
147
- const top = runsOf(scrap)?.[0];
148
- return { id: top?._id, alreadyInFlight: top?.status === null, captured: true };
150
+ return beforeRunStateFrom(await api.get(`/api/scraps/${id}`));
149
151
  }
150
152
  catch {
151
153
  return { id: undefined, alreadyInFlight: false, captured: false };
@@ -465,8 +467,8 @@ scraps
465
467
  .option('--no-digest', 'Disable the AI digest (partial update — other digest settings are kept)')
466
468
  .option('--digest-mode <mode>', `Digest mode (${VALID_DIGEST_MODES.join('|')} — latest: this run's data · changes: only what changed · changes_only: like changes, no mail when nothing changed; partial update — other digest settings are kept)`)
467
469
  .option('--digest-prompt <text>', 'Digest prompt (empty string to clear; partial update — other digest settings are kept)')
468
- .option('-p, --params <json>', 'Runtime params as JSON array of objects (e.g. \'[{"TRAWL.paramName":"value"}]\')')
469
- .option('--params-file <path>', 'Runtime params from a JSON file')
470
+ .option('-p, --params <json>', 'Scenario sets as a JSON array of objects (e.g. \'[{"TRAWL.q":"shoes"},{"TRAWL.q":"boots"}]\'). One set is picked at random on every run (trawl run and the schedule); the first set\'s keys/types define what `trawl trigger --param` accepts')
471
+ .option('--params-file <path>', 'Scenario sets (same shape as --params) from a JSON file')
470
472
  .option('--tier <tier>', `Force proxy tier (${VALID_TIERS.join('|')})`)
471
473
  .option('--force-tier <tier>', `Raise the proxy-tier ceiling PAST the auto-cap (${VALID_TIERS.join('|')}) — history-gated: may be refused or cost more`)
472
474
  .option('--json', 'Output as JSON')
@@ -880,18 +882,111 @@ scraps
880
882
  validateObjectId(id);
881
883
  await watchActivities(id, opts.json);
882
884
  });
885
+ export function parseTriggerPairs(pairs) {
886
+ const entries = [];
887
+ for (const pair of pairs) {
888
+ const eq = pair.indexOf('=');
889
+ const k = eq === -1 ? '' : pair.slice(0, eq);
890
+ const v = eq === -1 ? '' : pair.slice(eq + 1);
891
+ if (!k)
892
+ return { error: `Invalid --param "${pair}" (expected key=value)` };
893
+ if (v.trim() === '')
894
+ return { error: `--param ${k} has an empty value` };
895
+ entries.push([k, v]);
896
+ }
897
+ return { entries };
898
+ }
899
+ export function buildTriggerParams(scrap, pairs) {
900
+ const parsed = parseTriggerPairs(pairs);
901
+ if ('error' in parsed)
902
+ return parsed;
903
+ const schema = scrap.params?.[0];
904
+ if (!schema || Object.keys(schema).length === 0) {
905
+ return { error: `Scrap ${scrap._id} takes no params (it has no stored scenario set) — drop --param` };
906
+ }
907
+ const bare = (k) => (k.startsWith('TRAWL.') ? k.slice(6) : k);
908
+ const stored = new Map();
909
+ for (const key of Object.keys(schema)) {
910
+ const prev = stored.get(bare(key));
911
+ if (prev !== undefined) {
912
+ return { error: `Scrap params have conflicting keys ${prev} / ${key} — fix them with trawl scraps update ${scrap._id} -p` };
913
+ }
914
+ stored.set(bare(key), key);
915
+ }
916
+ const expected = [...stored.keys()].join(', ');
917
+ const body = {};
918
+ for (const [k, v] of parsed.entries) {
919
+ const storedKey = stored.get(bare(k));
920
+ if (storedKey === undefined)
921
+ return { error: `Unknown param "${k}" — expected: ${expected}` };
922
+ if (Object.hasOwn(body, storedKey))
923
+ return { error: `Duplicate --param ${k}` };
924
+ const type = typeof schema[storedKey];
925
+ if (type === 'number') {
926
+ const n = Number(v);
927
+ if (!Number.isFinite(n))
928
+ return { error: `--param ${k} must be a number` };
929
+ body[storedKey] = n;
930
+ }
931
+ else if (type === 'boolean') {
932
+ if (v !== 'true' && v !== 'false')
933
+ return { error: `--param ${k} must be true or false` };
934
+ body[storedKey] = v === 'true';
935
+ }
936
+ else {
937
+ body[storedKey] = v;
938
+ }
939
+ }
940
+ const missing = [...stored.entries()].filter(([, sk]) => !Object.hasOwn(body, sk)).map(([b]) => b);
941
+ if (missing.length > 0)
942
+ return { error: `Missing param(s): ${missing.join(', ')} — expected: ${expected}` };
943
+ return { body };
944
+ }
883
945
  export function attachTriggerCommand(parent, attachOpts = {}) {
884
946
  return parent
885
947
  .command('trigger <id>', attachOpts)
886
948
  .description('Launch a scrap as a background worker (returns immediately)')
887
949
  .option('-w, --watch', 'Poll for progress after triggering (#91 — the default async run happens in a separate cron pod; activities SSE never reaches it)')
888
950
  .option('--wait', 'Run synchronously and wait for the result (legacy behaviour — prefer `trawl run` instead)')
951
+ .option('--param <key=value>', "Run with custom params (repeatable; key as in the scrap's params, TRAWL. prefix optional). Values are typed like the stored set. A one-off run, not added to the scrap's scenarios", (v, prev) => prev.concat(v), [])
889
952
  .option('--json', 'Output the raw trigger payload as JSON')
890
953
  .action(async (id, opts) => {
891
954
  validateObjectId(id);
892
- const beforeRun = opts.watch ? await captureBeforeRunState(id) : undefined;
955
+ const pairs = opts.param ?? [];
956
+ const syntax = parseTriggerPairs(pairs);
957
+ if ('error' in syntax) {
958
+ usageError(syntax.error, { json: opts.json });
959
+ return;
960
+ }
961
+ let scrap;
962
+ let readFailed = false;
963
+ try {
964
+ scrap = await api.get(`/api/scraps/${id}`);
965
+ }
966
+ catch (e) {
967
+ if (pairs.length > 0)
968
+ throw e;
969
+ readFailed = true;
970
+ }
971
+ let body;
972
+ if (pairs.length > 0) {
973
+ const r = buildTriggerParams(typeof scrap === 'object' && scrap ? scrap : { _id: id }, pairs);
974
+ if ('error' in r) {
975
+ usageError(r.error, { json: opts.json });
976
+ return;
977
+ }
978
+ body = r.body;
979
+ }
980
+ if (scrap && typeof scrap === 'object' && !scrap.cron) {
981
+ console.error(chalk.yellow(` ⚠ Scrap ${id} has no schedule: nothing runs it unattended after this one-off run, so nothing checks its health. Add one: trawl scraps update ${id} --cron <expr>`));
982
+ }
983
+ const beforeRun = opts.watch
984
+ ? readFailed
985
+ ? { id: undefined, alreadyInFlight: false, captured: false }
986
+ : beforeRunStateFrom(scrap)
987
+ : undefined;
893
988
  const path = opts.wait ? `/api/scraps/worker/${id}` : `/api/scraps/worker/${id}?wait=false`;
894
- const call = () => (opts.wait ? api.postLongRunning(path, undefined, { timeoutMs: LONG_RUN_TIMEOUT_MS }) : api.post(path));
989
+ const call = () => (opts.wait ? api.postLongRunning(path, body, { timeoutMs: LONG_RUN_TIMEOUT_MS }) : body ? api.post(path, body) : api.post(path));
895
990
  const data = opts.json
896
991
  ? await call()
897
992
  : await spin(call, {
@@ -84,7 +84,7 @@ trawl create <url> --prompt <goal> [--no-autofix] [--no-digest] [--json] # url
84
84
  trawl list|ls [--json] [--status <s>] [--unhealthy] [--limit <n>] [--page <n>] List all scraps
85
85
  trawl get <id> [--json] Get scrap details
86
86
  trawl run <id> [--watch] [--json] Run a scrap (blocks until finished)
87
- trawl trigger <id> [--watch] [--wait] [--json] Launch a scrap as a background worker
87
+ trawl trigger <id> [--param <k=v>]... [--watch] [--wait] [--json] Launch a scrap as a background worker
88
88
  trawl data <id> [--json] [--fresh] [--errors] Get scrap data (last persisted run, or --fresh to launch one)
89
89
  trawl runs|history <id> [--json] [-n <limit>] List past runs for a scrap
90
90
  trawl run-info <hid> [--json] Show details of a single run
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trawlme/cli",
3
- "version": "3.14.1",
3
+ "version": "3.15.0",
4
4
  "description": "Trawl CLI — manage scraps from the terminal",
5
5
  "type": "module",
6
6
  "bin": {