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