@agentproto/collect-cli 0.0.0 → 0.1.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/dist/index.mjs CHANGED
@@ -2,8 +2,9 @@ import { parseArgs } from 'util';
2
2
  import { lstat, realpath, mkdir, rm, open as open$1, readFile } from 'fs/promises';
3
3
  import { dirname, resolve, join, basename, sep } from 'path';
4
4
  import { fileURLToPath, pathToFileURL } from 'url';
5
- import { readAll, CollectTask, CollectRunError, StoreLockedError, StoreVersionError, ConnectorDeclaration, listConnectors, createConnectorRegistry, canonicalUrl, itemIdFromUrl, textFingerprint, CollectItem, Observation, Pickup, Actor, seenKey, itemSeenKeys, stableStringify, recordSecrets, createCollector, Recipe, sha256Hex } from '@agentproto/collect';
6
- import { initStore, StoreNotFoundError, StoreMigrationError, openStore, createHttpTransport, createApiTransport } from '@agentproto/collect/node';
5
+ import { readAll, CollectTask, CollectRunError, StoreLockedError, StoreVersionError, ConnectorDeclaration, listConnectors, createConnectorRegistry, canonicalUrl, itemIdFromUrl, textFingerprint, CollectItem, Observation, Pickup, Actor, seenKey, itemSeenKeys, stableStringify, recordSecrets, createCollector, Recipe, TransportError, sha256Hex } from '@agentproto/collect';
6
+ import { shippedConnectors } from '@agentproto/collect/connectors';
7
+ import { initStore, StoreNotFoundError, StoreMigrationError, openStore, browserProfile, createMcpClient, createBrowserTransport, requiredTools, createHttpTransport, createApiTransport } from '@agentproto/collect/node';
7
8
  import { parse as parse$1 } from 'yaml';
8
9
  import { Writable, Readable } from 'stream';
9
10
  import { pipeline } from 'stream/promises';
@@ -17,8 +18,8 @@ import { readFileSync } from 'fs';
17
18
  // src/io.ts
18
19
  var UsageError = class extends Error {
19
20
  code = "USAGE";
20
- constructor(message) {
21
- super(message);
21
+ constructor(message2) {
22
+ super(message2);
22
23
  this.name = "UsageError";
23
24
  }
24
25
  };
@@ -78,12 +79,21 @@ function validateRecipe(input, label) {
78
79
  ${formatIssues(parsed.error)}`);
79
80
  return parsed.data;
80
81
  }
82
+ function announce(io, loaded) {
83
+ for (const line of loaded.overrides) err(io, `info: ${line}`);
84
+ }
81
85
  async function loadConnectors(paths, cwd) {
82
- const found = /* @__PURE__ */ new Map();
86
+ const found = new Map(shippedConnectors.map((c) => [c.id, c]));
87
+ const overrides = [];
83
88
  const apiAuth = /* @__PURE__ */ new Map();
84
89
  const merged = /* @__PURE__ */ new Map();
85
90
  const add = (c, where) => {
86
91
  const existing = found.get(c.id);
92
+ if (existing && existing !== c && shippedConnectors.includes(existing)) {
93
+ overrides.push(`connector "${c.id}" from ${where.replace(/^connector module /, "")} replaces the shipped one`);
94
+ found.set(c.id, c);
95
+ return;
96
+ }
87
97
  if (existing && existing !== c) throw new UsageError(`${where}: connector "${c.id}" is defined twice`);
88
98
  found.set(c.id, c);
89
99
  };
@@ -100,8 +110,8 @@ async function loadConnectors(paths, cwd) {
100
110
  if (name === "apiAuth") continue;
101
111
  for (const v of Array.isArray(value) ? value : [value]) {
102
112
  if (!looksLikeConnector(v)) continue;
103
- const { id, version, transports, access, capabilities, counters, pace } = v;
104
- const declared = ConnectorDeclaration.safeParse({ id, version, transports, access, capabilities, counters, pace });
113
+ const { id, version, transports, access, capabilities, counters, pace, sessionCheck } = v;
114
+ const declared = ConnectorDeclaration.safeParse({ id, version, transports, access, capabilities, counters, pace, sessionCheck });
105
115
  if (!declared.success) throw new UsageError(`connector module ${p}: export "${name}" is not a valid connector:
106
116
  ${formatIssues(declared.error)}`);
107
117
  let copy = merged.get(v);
@@ -116,7 +126,7 @@ ${formatIssues(declared.error)}`);
116
126
  }
117
127
  }
118
128
  for (const c of listConnectors()) if (!merged.has(c)) add(c, "registry");
119
- return { registry: createConnectorRegistry([...found.values()]), apiAuth };
129
+ return { registry: createConnectorRegistry([...found.values()]), apiAuth, overrides };
120
130
  }
121
131
  function envSecrets(env) {
122
132
  return { get: async (name) => env[name] || void 0 };
@@ -124,10 +134,11 @@ function envSecrets(env) {
124
134
  function secretNameOf(c) {
125
135
  return c.access.level === "key" ? c.access.secret : void 0;
126
136
  }
127
- function buildTransports(loaded, secrets, rateMs) {
137
+ function buildTransports(loaded, secrets, rateMs, browser) {
128
138
  const http = createHttpTransport(rateMs === void 0 ? {} : { minIntervalMs: rateMs });
129
139
  return {
130
140
  http,
141
+ ...browser ? { browser } : {},
131
142
  api: (connector) => {
132
143
  if (connector.access.level !== "key") return http;
133
144
  const secret = connector.access.secret;
@@ -167,7 +178,9 @@ var CONNECTOR_OPTION = { connector: { type: "string", multiple: true } };
167
178
  async function runConnectors(argv, io) {
168
179
  const { values, positionals } = parse(argv, CONNECTOR_OPTION);
169
180
  positional(positionals, "none", 0);
170
- const { registry } = await loadConnectors(values.connector ?? [], io.cwd);
181
+ const loadedAll = await loadConnectors(values.connector ?? [], io.cwd);
182
+ announce(io, loadedAll);
183
+ const { registry } = loadedAll;
171
184
  const list = registry.list().map((c) => ({
172
185
  id: c.id,
173
186
  version: c.version,
@@ -191,11 +204,188 @@ async function runConnectors(argv, io) {
191
204
  out(io, table(rows));
192
205
  return 0;
193
206
  }
207
+ var BROWSER_OPTIONS = {
208
+ "browser-mcp": { type: "string" },
209
+ "browser-profile": { type: "string" },
210
+ "browser-proxy-tool": { type: "string" },
211
+ "browser-alias": { type: "string" },
212
+ "browser-instance": { type: "string" },
213
+ "browser-header": { type: "string", multiple: true },
214
+ "browser-pace": { type: "string" }
215
+ };
216
+ function envHeaders(env) {
217
+ return (env.COLLECT_BROWSER_HEADER ?? "").split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
218
+ }
219
+ function parseHeader(line) {
220
+ const i = line.indexOf(":");
221
+ const name = line.slice(0, i).trim();
222
+ if (i <= 0 || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)) throw new UsageError("--browser-header must look like 'Name: value'");
223
+ return [name, line.slice(i + 1).trim()];
224
+ }
225
+ function browserConfig(values, env) {
226
+ const endpoint = values["browser-mcp"] ?? (env.COLLECT_BROWSER_MCP || void 0);
227
+ const profileName = values["browser-profile"] ?? (env.COLLECT_BROWSER_PROFILE || void 0);
228
+ const proxyTool = values["browser-proxy-tool"] ?? (env.COLLECT_BROWSER_PROXY_TOOL || void 0);
229
+ const alias = values["browser-alias"] ?? (env.COLLECT_BROWSER_ALIAS || void 0);
230
+ const instance = values["browser-instance"] ?? (env.COLLECT_BROWSER_INSTANCE || void 0);
231
+ const paceText = values["browser-pace"] ?? (env.COLLECT_BROWSER_PACE || void 0);
232
+ const headerLines = [...envHeaders(env), ...values["browser-header"] ?? []];
233
+ if (!endpoint) {
234
+ const orphan = ["browser-profile", "browser-proxy-tool", "browser-alias", "browser-instance", "browser-header", "browser-pace"].find((k) => values[k] !== void 0);
235
+ if (orphan) throw new UsageError(`--${orphan} needs --browser-mcp <url>`);
236
+ return void 0;
237
+ }
238
+ let url;
239
+ try {
240
+ url = new URL(endpoint);
241
+ } catch {
242
+ throw new UsageError("--browser-mcp must be an http(s) URL");
243
+ }
244
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new UsageError("--browser-mcp must be an http(s) URL");
245
+ if (Boolean(proxyTool) !== Boolean(alias)) throw new UsageError("--browser-proxy-tool and --browser-alias go together");
246
+ let profile;
247
+ try {
248
+ profile = browserProfile(profileName ?? "chrome-devtools");
249
+ } catch (e) {
250
+ throw new UsageError(e instanceof Error ? e.message : String(e));
251
+ }
252
+ const headers = {};
253
+ for (const line of headerLines) {
254
+ const [k, v] = parseHeader(line);
255
+ headers[k] = v;
256
+ }
257
+ let pace;
258
+ if (paceText !== void 0) {
259
+ const m = /^(\d+)-(\d+)$/.exec(paceText);
260
+ if (!m || Number(m[1]) > Number(m[2])) throw new UsageError("--browser-pace must look like 2000-6000 (min-max milliseconds)");
261
+ pace = { minMs: Number(m[1]), maxMs: Number(m[2]) };
262
+ }
263
+ return { endpoint, profile, ...pace ? { pace } : {}, ...proxyTool && alias ? { proxy: { tool: proxyTool, alias } } : {}, ...instance ? { instance } : {}, headers };
264
+ }
265
+ function displayEndpoint(endpoint) {
266
+ const u = new URL(endpoint);
267
+ return `${u.protocol}//${u.host}${u.pathname}`;
268
+ }
269
+ function redactBrowser(io, config) {
270
+ const values = [...Object.values(config.headers)];
271
+ const u = new URL(config.endpoint);
272
+ if (u.password) values.push(u.password);
273
+ if (u.username) values.push(u.username);
274
+ for (const v of u.searchParams.values()) values.push(v);
275
+ const secrets = values.filter((v) => v.length >= 4).sort((x, y) => y.length - x.length);
276
+ if (secrets.length === 0) return;
277
+ io.addRedactor?.((text) => secrets.reduce((t, v) => t.split(v).join("[redacted]"), text));
278
+ }
279
+ function createBrowser(config, io, defaultPace) {
280
+ const pace = config.pace ?? defaultPace;
281
+ const client = createMcpClient({
282
+ endpoint: config.endpoint,
283
+ headers: config.headers,
284
+ signal: io.signal,
285
+ clientInfo: { name: "collect", version: "0" }
286
+ });
287
+ const transport = createBrowserTransport({
288
+ client,
289
+ profile: config.profile,
290
+ ...config.proxy ? { proxy: config.proxy } : {},
291
+ ...config.instance ? { instance: config.instance } : {},
292
+ ...pace ? { pace } : {},
293
+ // Stops paced waits when the run is cancelled; the cleanup calls do not depend on it.
294
+ signal: io.signal
295
+ });
296
+ return {
297
+ client,
298
+ transport,
299
+ async dispose() {
300
+ await transport.closeAll();
301
+ const left = transport.leftOpen();
302
+ if (left.length > 0) err(io, `collect: ${left.length} browser tab${left.length === 1 ? "" : "s"} could not be closed safely and ${left.length === 1 ? "was" : "were"} left open`);
303
+ await client.close();
304
+ }
305
+ };
306
+ }
194
307
 
195
308
  // src/commands/doctor.ts
309
+ var message = (e) => e instanceof Error ? e.message : String(e);
310
+ async function checkBrowser(config, io, browser) {
311
+ if (!config || !browser) return { configured: false, ok: false, missingTools: [] };
312
+ const report = {
313
+ configured: true,
314
+ endpoint: displayEndpoint(config.endpoint),
315
+ profile: config.profile.name,
316
+ proxy: Boolean(config.proxy),
317
+ ok: false,
318
+ missingTools: []
319
+ };
320
+ try {
321
+ const toolList = await browser.client.listTools({ signal: io.signal });
322
+ const tools = new Set(toolList.map((t) => t.name));
323
+ if (config.proxy) {
324
+ if (!tools.has(config.proxy.tool)) report.missingTools = [config.proxy.tool];
325
+ } else {
326
+ report.missingTools = requiredTools(config.profile).filter((t) => !tools.has(t));
327
+ const schemaOf = (name) => (toolList.find((t) => t.name === name)?.inputSchema ?? {}).properties ?? {};
328
+ const closeProps = schemaOf(config.profile.tools.closeTab);
329
+ if (config.profile.name === "chrome-devtools" && "pageIdx" in closeProps && !("pageId" in closeProps)) {
330
+ report.error = "this server names pages by index (pageIdx): use --browser-profile chrome-devtools-index (a fallback that needs a browser session no other client drives)";
331
+ return report;
332
+ }
333
+ if (config.profile.name === "chrome-devtools-index" && "pageId" in closeProps) {
334
+ report.error = "this server names pages by stable id (pageId): use --browser-profile chrome-devtools";
335
+ return report;
336
+ }
337
+ }
338
+ if (report.missingTools.length) {
339
+ report.error = `missing tools: ${report.missingTools.join(", ")}`;
340
+ return report;
341
+ }
342
+ const sum = await browser.transport.probe();
343
+ report.blankTab = true;
344
+ report.evaluate = sum === 2;
345
+ if (!report.evaluate) report.error = "the probe evaluation did not return 2";
346
+ report.probeClosed = true;
347
+ report.listing = await browser.transport.canList();
348
+ report.ok = report.evaluate === true;
349
+ } catch (e) {
350
+ report.error = message(e);
351
+ if (/probe tab could not be closed/.test(report.error)) {
352
+ report.probeClosed = false;
353
+ }
354
+ if (report.blankTab === void 0 && report.missingTools.length === 0 && report.error) report.blankTab = false;
355
+ }
356
+ return report;
357
+ }
358
+ function sessionCheckScript(body) {
359
+ return `try {
360
+ const __answer = await (async () => {
361
+ ${body}
362
+ })();
363
+ return __answer === true ? "open" : "none";
364
+ } catch (__e) {
365
+ return "error";
366
+ }`;
367
+ }
368
+ async function checkSession(check, browser) {
369
+ let page;
370
+ try {
371
+ page = await browser.transport.open(check.url);
372
+ const code = await browser.transport.evaluate(page, sessionCheckScript(check.evaluate));
373
+ if (code === "open") return { state: "open" };
374
+ if (code === "none") return { state: "none" };
375
+ if (code === "error") return { state: "error", note: "the check could not run" };
376
+ return { state: "unknown", note: "the check gave no answer" };
377
+ } catch (e) {
378
+ if (e instanceof TransportError && e.cause === "challenge") return { state: "unknown", note: "the site showed a verification page; nothing was bypassed" };
379
+ return { state: "error", note: "the check could not run" };
380
+ } finally {
381
+ if (page) await browser.transport.close(page).catch(() => void 0);
382
+ }
383
+ }
196
384
  async function runDoctor(argv, io) {
197
- const { values, positionals } = parse(argv, { ...CONNECTOR_OPTION, source: { type: "string", multiple: true } });
385
+ const { values, positionals } = parse(argv, { ...CONNECTOR_OPTION, ...BROWSER_OPTIONS, source: { type: "string", multiple: true } });
198
386
  if (positionals.length > 1) positional(positionals, "recipe", 1);
387
+ const config = browserConfig(values, io.env);
388
+ if (config) redactBrowser(io, config);
199
389
  const modules = [...values.connector ?? []];
200
390
  let wanted = values.source ?? [];
201
391
  if (positionals[0]) {
@@ -203,48 +393,86 @@ async function runDoctor(argv, io) {
203
393
  modules.push(...loaded.connectors);
204
394
  if (wanted.length === 0) wanted = [...new Set(loaded.recipe.sources.map((s) => s.connector))];
205
395
  }
206
- const { registry } = await loadConnectors(modules, io.cwd);
396
+ const loadedAll = await loadConnectors(modules, io.cwd);
397
+ announce(io, loadedAll);
398
+ const { registry } = loadedAll;
207
399
  const ids = wanted.length > 0 ? wanted : registry.list().map((c) => c.id);
208
- let unusable = 0;
209
- const reports = ids.map((id) => {
210
- const c = registry.get(id);
211
- if (!c) {
212
- unusable++;
213
- return { id, registered: false, usable: false, problems: [`connector "${id}" is not registered`] };
214
- }
215
- const secret = secretNameOf(c);
216
- const secretPresent = secret ? Boolean(io.env[secret]) : void 0;
217
- const transports = {};
218
- for (const t of c.transports) {
219
- if (t === "http") transports[t] = { available: true };
220
- else if (t === "api") transports[t] = secret ? { available: Boolean(secretPresent), note: secretPresent ? void 0 : `${secret} is not set` } : { available: false, note: "the connector declares no secret" };
221
- else transports[t] = { available: false, note: "not available in this version" };
222
- }
223
- const problems = [];
224
- if (secret && !secretPresent) problems.push(`secret ${secret} is not set`);
225
- if (c.access.level === "session") problems.push(`needs a logged-in session on ${c.access.site} (browser transport not available in this version)`);
226
- const usable = problems.length === 0 && Object.values(transports).some((t) => t.available);
227
- if (!usable && problems.length === 0) problems.push("no usable transport");
228
- if (!usable) unusable++;
229
- return { id, registered: true, version: c.version, access: c.access, secret, secretPresent, transports, usable, problems };
230
- });
231
- if (values.json) outJson(io, { connectors: reports, ok: unusable === 0 });
232
- else if (reports.length === 0) out(io, "no connectors to check");
233
- else {
234
- const rows = [["connector", "access", "secret", "transports", "usable"]];
235
- for (const r of reports) {
236
- if (!r.registered) {
237
- rows.push([r.id, "-", "-", "-", "no (not registered)"]);
400
+ const browser = config ? createBrowser(config, io, { minMs: 500, maxMs: 1500 }) : void 0;
401
+ try {
402
+ const browserReport = await checkBrowser(config, io, browser);
403
+ let unusable = 0;
404
+ const reports = [];
405
+ for (const id of ids) {
406
+ const c = registry.get(id);
407
+ if (!c) {
408
+ unusable++;
409
+ reports.push({ id, registered: false, usable: false, problems: [`connector "${id}" is not registered`] });
238
410
  continue;
239
411
  }
240
- const t = Object.entries(r.transports).map(([n, a]) => `${n}:${a.available ? "yes" : `no${a.note ? ` (${a.note})` : ""}`}`).join(" ");
241
- const secret = r.secret ? `${r.secret}: ${r.secretPresent ? "set" : "missing"}` : "-";
242
- rows.push([r.id, r.access.level, secret, t, r.usable ? "yes" : "no"]);
412
+ const secret = secretNameOf(c);
413
+ const secretPresent = secret ? Boolean(io.env[secret]) : void 0;
414
+ const transports = {};
415
+ for (const t of c.transports) {
416
+ if (t === "http") transports[t] = { available: true };
417
+ else if (t === "api") transports[t] = secret ? { available: Boolean(secretPresent), note: secretPresent ? void 0 : `${secret} is not set` } : { available: false, note: "the connector declares no secret" };
418
+ else if (!browserReport.configured) transports[t] = { available: false, note: "no browser: use --browser-mcp <url>" };
419
+ else transports[t] = browserReport.ok ? { available: true } : { available: false, note: browserReport.error ?? "the browser is not usable" };
420
+ }
421
+ const problems = [];
422
+ if (secret && !secretPresent) problems.push(`secret ${secret} is not set`);
423
+ let session;
424
+ if (c.access.level === "session") {
425
+ const site = c.access.site;
426
+ if (!browserReport.ok || !browser) {
427
+ session = { site, state: "unknown", note: "no usable browser" };
428
+ problems.push(`needs a logged-in session on ${site}, and no usable browser is configured`);
429
+ } else if (!c.sessionCheck) {
430
+ session = { site, state: "unknown", note: "the connector declares no session check" };
431
+ } else {
432
+ session = { site, ...await checkSession(c.sessionCheck, browser) };
433
+ if (session.state === "none") problems.push(`no open session on ${site}: log in with the browser first`);
434
+ }
435
+ }
436
+ const usable = problems.length === 0 && Object.values(transports).some((t) => t.available);
437
+ if (!usable && problems.length === 0) problems.push("no usable transport");
438
+ if (!usable) unusable++;
439
+ reports.push({ id, registered: true, version: c.version, access: c.access, secret, secretPresent, transports, ...session ? { session } : {}, usable, problems });
243
440
  }
244
- out(io, table(rows));
245
- for (const r of reports) for (const p of r.problems) out(io, `${r.id}: ${p}`);
441
+ const ok = unusable === 0 && !(browserReport.configured && !browserReport.ok);
442
+ if (values.json) outJson(io, { browser: browserReport, connectors: reports, ok });
443
+ else {
444
+ if (browserReport.configured) {
445
+ const detail = browserReport.ok ? "ok" : `FAILED (${browserReport.error})`;
446
+ out(io, `browser: ${browserReport.endpoint} profile ${browserReport.profile}${browserReport.proxy ? " (through a proxy tool)" : ""}: ${detail}`);
447
+ if (browserReport.ok) out(io, "browser: listed the tools, opened a probe tab, navigated it to a safe data: URL, evaluated 1+1 in it and closed it");
448
+ if (browserReport.ok && browserReport.listing === false) {
449
+ out(io, "browser: cannot list tabs: a tab whose creation times out cannot be found and closed afterwards");
450
+ }
451
+ }
452
+ if (reports.length === 0) out(io, "no connectors to check");
453
+ else {
454
+ const rows = [["connector", "access", "secret", "transports", "session", "usable"]];
455
+ for (const r of reports) {
456
+ if (!r.registered) {
457
+ rows.push([r.id, "-", "-", "-", "-", "no (not registered)"]);
458
+ continue;
459
+ }
460
+ const t = Object.entries(r.transports).map(([n, a]) => `${n}:${a.available ? "yes" : `no${a.note ? ` (${a.note})` : ""}`}`).join(" ");
461
+ const secret = r.secret ? `${r.secret}: ${r.secretPresent ? "set" : "missing"}` : "-";
462
+ const session = r.session ? `${r.session.state} (${r.session.site})` : "-";
463
+ rows.push([r.id, r.access.level, secret, t, session, r.usable ? "yes" : "no"]);
464
+ }
465
+ out(io, table(rows));
466
+ for (const r of reports) {
467
+ for (const p of r.problems) out(io, `${r.id}: ${p}`);
468
+ if ((r.session?.state === "unknown" || r.session?.state === "error") && r.session.note) out(io, `${r.id}: session ${r.session.state}: ${r.session.note}`);
469
+ }
470
+ }
471
+ }
472
+ return ok ? 0 : 1;
473
+ } finally {
474
+ await browser?.dispose().catch(() => void 0);
246
475
  }
247
- return unusable > 0 ? 1 : 0;
248
476
  }
249
477
  function classify(e) {
250
478
  const cause = e instanceof CollectRunError ? e.cause : e;
@@ -308,13 +536,20 @@ async function execute(io, opts) {
308
536
  const store = await open(opts.storePath);
309
537
  const secrets = recordSecrets(envSecrets(io.env));
310
538
  io.addRedactor?.(secrets.redact);
539
+ if (opts.browser) redactBrowser(io, opts.browser);
540
+ const browser = opts.browser ? createBrowser(opts.browser, io) : void 0;
311
541
  const collector = createCollector({
312
542
  store,
313
- transports: buildTransports(opts.loaded, secrets, opts.rateMs),
543
+ transports: buildTransports(opts.loaded, secrets, opts.rateMs, browser?.transport),
314
544
  secrets,
315
545
  connectors: opts.loaded.registry
316
546
  });
317
- const report = await opts.start(collector, progress(io, opts.json, opts.quiet));
547
+ let report;
548
+ try {
549
+ report = await opts.start(collector, progress(io, opts.json, opts.quiet));
550
+ } finally {
551
+ await browser?.dispose();
552
+ }
318
553
  const interrupted = io.signal?.aborted === true;
319
554
  if (opts.json) outJson(io, { ...report, interrupted });
320
555
  else {
@@ -467,7 +702,7 @@ async function runRuns(argv, io) {
467
702
  runId: id,
468
703
  name: run?.recipe.name,
469
704
  createdAt: run?.createdAt,
470
- state: report?.finishedAt ? "finished" : "unfinished",
705
+ state: run?.origin === "reparse" ? "reparsed" : report?.finishedAt ? "finished" : "unfinished",
471
706
  connectors: (report?.connectors ?? []).map((c) => ({ connector: c.connector, status: c.status }))
472
707
  });
473
708
  }
@@ -493,7 +728,7 @@ async function runStatus(argv, io) {
493
728
  byStatus[t.status] = (byStatus[t.status] ?? 0) + 1;
494
729
  if (t.status === "failed") failures[t.cause ?? "other"] = (failures[t.cause ?? "other"] ?? 0) + 1;
495
730
  }
496
- const state = report?.finishedAt ? "finished" : "unfinished";
731
+ const state = run.origin === "reparse" ? "reparsed" : report?.finishedAt ? "finished" : "unfinished";
497
732
  if (values.json) {
498
733
  outJson(io, { runId, name: run.recipe.name, createdAt: run.createdAt, state, tasks: byStatus, failures, report: report ?? null });
499
734
  return 0;
@@ -505,13 +740,14 @@ async function runStatus(argv, io) {
505
740
  out(io, table([["connector", "status", "new", "obs", "dup"], ...report.connectors.map((c) => [c.connector, c.status, String(c.newItems), String(c.observations), String(c.duplicates)])]));
506
741
  }
507
742
  if (state === "unfinished") out(io, `continue with: collect resume ${runId}`);
743
+ if (state === "reparsed") out(io, "this is a copy kept by reparse: it can be reparsed again but not resumed");
508
744
  return 0;
509
745
  }
510
746
  async function ingestRaw(target, connector, entry, position, bytes, task, writtenActors, totals) {
511
747
  const parsed = await connector.parse({
512
748
  connector: connector.id,
513
749
  task: CollectTask.parse(task),
514
- raw: { ref: entry.ref, url: entry.url, ext: entry.ext, bytes, httpStatus: entry.httpStatus, fetchedAt: entry.fetchedAt, transport: entry.transport }
750
+ raw: { ref: entry.ref, url: entry.url, ext: entry.ext, bytes, httpStatus: entry.httpStatus, contentType: entry.contentType, fetchedAt: entry.fetchedAt, transport: entry.transport }
515
751
  });
516
752
  const keyOf = (kind, i) => sha256Hex(JSON.stringify([entry.runId ?? "", "reparse", position, entry.hash, kind, i]));
517
753
  const items = [];
@@ -623,6 +859,18 @@ async function realTarget(path) {
623
859
  }
624
860
  }
625
861
  var inside = (child, parent) => child === parent || child.startsWith(parent + sep);
862
+ async function copyRuns(source, target, referenced, problems) {
863
+ for (const [runId, taskIds] of referenced) {
864
+ const run = await source.getRun(runId);
865
+ if (!run) continue;
866
+ await target.createRun(runId, run.recipe, { ...run.connectorModules ? { connectorModules: run.connectorModules } : {}, origin: "reparse" });
867
+ const plan = (await source.readPlan(runId))?.filter((e) => taskIds.has(e.taskId));
868
+ if (plan?.length) await target.writePlan(runId, plan);
869
+ const log = source.tasks(runId);
870
+ for await (const t of log) if (taskIds.has(t.taskId)) await target.appendTask(runId, t);
871
+ if (log.skipped) problems.push(`run ${runId}: ${log.skipped} unreadable line(s) in its task log were not copied`);
872
+ }
873
+ }
626
874
  async function originalTask(source, cache, entry) {
627
875
  if (!entry.runId || !entry.taskId) return void 0;
628
876
  let tasks = cache.get(entry.runId);
@@ -642,7 +890,9 @@ async function runReparse(argv, io) {
642
890
  if (!values.into) throw new UsageError("reparse needs --into <new store path>: the source store is never rewritten in place");
643
891
  const sourcePath = storePathOf(io, values.store);
644
892
  const wanted = resolve(io.cwd, values.into);
645
- const { registry } = await loadConnectors(values.connector ?? [], io.cwd);
893
+ const loadedAll = await loadConnectors(values.connector ?? [], io.cwd);
894
+ announce(io, loadedAll);
895
+ const { registry } = loadedAll;
646
896
  const source = await open(sourcePath);
647
897
  const exists = await lstat(wanted).then(
648
898
  () => true,
@@ -686,6 +936,7 @@ async function runReparse(argv, io) {
686
936
  targetLock = await out2.acquireLock();
687
937
  const writtenActors = /* @__PURE__ */ new Set();
688
938
  const taskCache = /* @__PURE__ */ new Map();
939
+ const referenced = /* @__PURE__ */ new Map();
689
940
  let position = 0;
690
941
  const index = source.rawIndex();
691
942
  for await (const entry of index) {
@@ -701,6 +952,11 @@ async function runReparse(argv, io) {
701
952
  position++;
702
953
  continue;
703
954
  }
955
+ if (entry.runId && entry.taskId) {
956
+ const ids = referenced.get(entry.runId) ?? /* @__PURE__ */ new Set();
957
+ ids.add(entry.taskId);
958
+ referenced.set(entry.runId, ids);
959
+ }
704
960
  await out2.putRaw({
705
961
  connector: entry.connector,
706
962
  ext: entry.ext,
@@ -708,6 +964,7 @@ async function runReparse(argv, io) {
708
964
  url: entry.url,
709
965
  fetchedAt: entry.fetchedAt,
710
966
  httpStatus: entry.httpStatus,
967
+ contentType: entry.contentType,
711
968
  transport: entry.transport,
712
969
  runId: entry.runId,
713
970
  taskId: entry.taskId,
@@ -739,6 +996,7 @@ async function runReparse(argv, io) {
739
996
  position++;
740
997
  }
741
998
  totals.skippedIndexLines = index.skipped;
999
+ await copyRuns(source, out2, referenced, totals.problems);
742
1000
  } catch (e) {
743
1001
  if (!targetLock) await rm(target, { recursive: true, force: true }).catch(() => void 0);
744
1002
  throw e;
@@ -761,7 +1019,8 @@ async function runReparse(argv, io) {
761
1019
  var RUN_OPTIONS = {
762
1020
  ...CONNECTOR_OPTION,
763
1021
  store: { type: "string" },
764
- "rate-ms": { type: "string" }
1022
+ "rate-ms": { type: "string" },
1023
+ ...BROWSER_OPTIONS
765
1024
  };
766
1025
  function rateOf(value) {
767
1026
  if (value === void 0) return void 0;
@@ -780,6 +1039,7 @@ async function runRun(argv, io) {
780
1039
  if (positionals.length > 1) positional(positionals, "recipe", 1);
781
1040
  const max = intOption("max", values.max);
782
1041
  const rateMs = rateOf(values["rate-ms"]);
1042
+ const browser = browserConfig(values, io.env);
783
1043
  const modules = [...values.connector ?? []];
784
1044
  let recipe;
785
1045
  if (positionals[0]) {
@@ -806,6 +1066,7 @@ async function runRun(argv, io) {
806
1066
  recipe = validateRecipe(recipe, "after applying the command-line options");
807
1067
  const moduleFiles = [...new Set(modules.map((m) => resolve(io.cwd, m)))];
808
1068
  const loadedConnectors = await loadConnectors(moduleFiles, io.cwd);
1069
+ announce(io, loadedConnectors);
809
1070
  if (values["dry-run"]) {
810
1071
  const tasks = [];
811
1072
  const seen = /* @__PURE__ */ new Set();
@@ -835,6 +1096,7 @@ async function runRun(argv, io) {
835
1096
  quiet: Boolean(values.quiet),
836
1097
  loaded: loadedConnectors,
837
1098
  rateMs,
1099
+ browser,
838
1100
  start: (collector, onEvent) => collector.run(recipe, { signal: io.signal, onEvent, connectorModules: moduleFiles })
839
1101
  });
840
1102
  }
@@ -845,14 +1107,17 @@ async function runResume(argv, io) {
845
1107
  const storePath = storePathOf(io, values.store);
846
1108
  const run = await (await open(storePath)).getRun(runId);
847
1109
  if (!run) throw new UsageError(`unknown run ${runId}`);
1110
+ if (run.origin === "reparse") throw new UsageError(`run ${runId} is a copy kept by reparse and cannot be resumed; run its recipe again instead`);
848
1111
  const modules = [.../* @__PURE__ */ new Set([...run.connectorModules ?? [], ...(values.connector ?? []).map((m) => resolve(io.cwd, m))])];
849
1112
  const loaded = await loadConnectors(modules, io.cwd);
1113
+ announce(io, loaded);
850
1114
  return execute(io, {
851
1115
  storePath,
852
1116
  json: Boolean(values.json),
853
1117
  quiet: Boolean(values.quiet),
854
1118
  loaded,
855
1119
  rateMs,
1120
+ browser: browserConfig(values, io.env),
856
1121
  start: (collector, onEvent) => collector.resume(runId, { signal: io.signal, onEvent })
857
1122
  });
858
1123
  }
@@ -876,8 +1141,10 @@ var HELP = `collect: collect public posts and articles with provenance (v${VERSI
876
1141
  Commands:
877
1142
  init <store> Create a store
878
1143
  connectors List the connectors that are registered or loaded
879
- doctor [recipe.yaml] Check connectors: access level, secret (name only), transports
1144
+ doctor [recipe.yaml] Check connectors: access level, secret (name only), transports, browser session
880
1145
  [--source id]... (default: every registered connector)
1146
+ With a browser configured: lists its tools, opens and closes a blank tab,
1147
+ and asks each session connector whether its site has an open session.
881
1148
  run [recipe.yaml] Run a recipe
882
1149
  [--source id]... [--query text]... [--subject label] [--max n]
883
1150
  [--dry-run] [--store path]
@@ -888,7 +1155,21 @@ Commands:
888
1155
  export Items as JSONL (default) or --format csv
889
1156
  [--source id] [--out file]
890
1157
  reparse --into <new store> Rebuild items, observations, actors and pickups from stored raws.
891
- No network; the source store is never modified.
1158
+ No network; the source store is never modified. The copy keeps the run
1159
+ records of its raws for reparsing again; it is not meant for resume.
1160
+
1161
+ Browser (run, resume, doctor), over an MCP server for an already-connected browser:
1162
+ --browser-mcp url streamable-HTTP endpoint ($COLLECT_BROWSER_MCP)
1163
+ --browser-profile name chrome-devtools (default, stable page ids), chrome-devtools-index (older
1164
+ servers that name pages by index; exclusive mode) or tab-tools
1165
+ ($COLLECT_BROWSER_PROFILE)
1166
+ --browser-proxy-tool name reach the browser tools through one tool taking { alias, toolName, args }
1167
+ --browser-alias name alias sent to the proxy tool (both go together)
1168
+ --browser-instance name browser instance sent with every call (tab-tools)
1169
+ --browser-pace min-max wait between page actions in ms, e.g. 2000-6000 (default; $COLLECT_BROWSER_PACE)
1170
+ --browser-header 'Name: v' extra header, e.g. authorisation (repeatable; $COLLECT_BROWSER_HEADER, one
1171
+ per line). Values never appear in output.
1172
+ The browser only reads pages: no clicks, no typing, no forms.
892
1173
 
893
1174
  Options on every command:
894
1175
  --json machine output on stdout (progress stays on stderr)