@agentproto/collect 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.
@@ -0,0 +1,384 @@
1
+ import { F as FailureCause, o as CollectItem, O as Observation, e as Actor, W as Pickup, R as Recipe, $ as RunReport, a7 as TransportSet, b as SecretsPort, C as Connector, c as ConnectorRegistry } from './connector-DUNy3vSU.js';
2
+ import { z } from 'zod';
3
+
4
+ /** One line of `raw/index.jsonl`: where a fetched body lives and how it was fetched. */
5
+ declare const RawIndexEntry: z.ZodObject<{
6
+ ref: z.ZodString;
7
+ connector: z.ZodString;
8
+ hash: z.ZodString;
9
+ ext: z.ZodString;
10
+ bytes: z.ZodNumber;
11
+ url: z.ZodString;
12
+ fetchedAt: z.ZodISODateTime;
13
+ httpStatus: z.ZodOptional<z.ZodNumber>;
14
+ contentType: z.ZodOptional<z.ZodString>;
15
+ transport: z.ZodString;
16
+ runId: z.ZodOptional<z.ZodString>;
17
+ taskId: z.ZodOptional<z.ZodString>;
18
+ failure: z.ZodOptional<z.ZodEnum<{
19
+ blocked: "blocked";
20
+ empty: "empty";
21
+ network: "network";
22
+ http: "http";
23
+ challenge: "challenge";
24
+ parse: "parse";
25
+ other: "other";
26
+ }>>;
27
+ }, z.core.$strip>;
28
+ type RawIndexEntry = z.infer<typeof RawIndexEntry>;
29
+ /** One line of `plan.jsonl`: a root task of the run, written once and atomically before anything runs. */
30
+ declare const PlanEntry: z.ZodObject<{
31
+ taskId: z.ZodString;
32
+ connector: z.ZodString;
33
+ order: z.ZodArray<z.ZodNumber>;
34
+ payload: z.ZodRecord<z.ZodString, z.ZodUnknown>;
35
+ }, z.core.$strip>;
36
+ type PlanEntry = z.infer<typeof PlanEntry>;
37
+ declare const TaskStatus: z.ZodEnum<{
38
+ failed: "failed";
39
+ skipped: "skipped";
40
+ done: "done";
41
+ pending: "pending";
42
+ started: "started";
43
+ }>;
44
+ type TaskStatus = z.infer<typeof TaskStatus>;
45
+ /** One line of `tasks.jsonl`. The last line for a task id is its current state. */
46
+ declare const TaskRecord: z.ZodObject<{
47
+ taskId: z.ZodString;
48
+ connector: z.ZodString;
49
+ status: z.ZodEnum<{
50
+ failed: "failed";
51
+ skipped: "skipped";
52
+ done: "done";
53
+ pending: "pending";
54
+ started: "started";
55
+ }>;
56
+ transport: z.ZodOptional<z.ZodString>;
57
+ reason: z.ZodOptional<z.ZodString>;
58
+ cause: z.ZodOptional<z.ZodEnum<{
59
+ blocked: "blocked";
60
+ empty: "empty";
61
+ network: "network";
62
+ http: "http";
63
+ challenge: "challenge";
64
+ parse: "parse";
65
+ other: "other";
66
+ }>>;
67
+ order: z.ZodOptional<z.ZodArray<z.ZodNumber>>;
68
+ counters: z.ZodOptional<z.ZodObject<{
69
+ items: z.ZodNumber;
70
+ newItems: z.ZodNumber;
71
+ duplicates: z.ZodNumber;
72
+ observations: z.ZodNumber;
73
+ metricValues: z.ZodNumber;
74
+ durationMs: z.ZodNumber;
75
+ }, z.core.$strip>>;
76
+ charged: z.ZodOptional<z.ZodBoolean>;
77
+ escalations: z.ZodOptional<z.ZodArray<z.ZodObject<{
78
+ from: z.ZodString;
79
+ to: z.ZodString;
80
+ }, z.core.$strip>>>;
81
+ payload: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
82
+ updatedAt: z.ZodISODateTime;
83
+ }, z.core.$strip>;
84
+ type TaskRecord = z.infer<typeof TaskRecord>;
85
+ /** One line of `sampling.jsonl`: a candidate seen, and whether the sampling kept it. */
86
+ declare const SamplingRecord: z.ZodObject<{
87
+ candidate: z.ZodString;
88
+ decision: z.ZodEnum<{
89
+ kept: "kept";
90
+ dropped: "dropped";
91
+ }>;
92
+ rule: z.ZodOptional<z.ZodString>;
93
+ band: z.ZodOptional<z.ZodNumber>;
94
+ url: z.ZodOptional<z.ZodString>;
95
+ domain: z.ZodOptional<z.ZodString>;
96
+ seed: z.ZodOptional<z.ZodNumber>;
97
+ connector: z.ZodOptional<z.ZodString>;
98
+ taskId: z.ZodOptional<z.ZodString>;
99
+ at: z.ZodISODateTime;
100
+ }, z.core.$strip>;
101
+ type SamplingRecord = z.infer<typeof SamplingRecord>;
102
+ /** One line of `events.jsonl`. */
103
+ declare const EventRecord: z.ZodObject<{
104
+ at: z.ZodISODateTime;
105
+ type: z.ZodString;
106
+ data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
107
+ }, z.core.$strip>;
108
+ type EventRecord = z.infer<typeof EventRecord>;
109
+ /** Content of `runs/<runId>/recipe.json`: the recipe as it was when the run started, and its hash. */
110
+ declare const RunRecord: z.ZodObject<{
111
+ runId: z.ZodString;
112
+ createdAt: z.ZodISODateTime;
113
+ recipeHash: z.ZodString;
114
+ recipe: z.ZodObject<{
115
+ name: z.ZodOptional<z.ZodString>;
116
+ sources: z.ZodArray<z.ZodObject<{
117
+ connector: z.ZodString;
118
+ instance: z.ZodOptional<z.ZodString>;
119
+ queries: z.ZodDefault<z.ZodArray<z.ZodObject<{
120
+ text: z.ZodString;
121
+ subject: z.ZodString;
122
+ }, z.core.$strip>>>;
123
+ options: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
124
+ }, z.core.$strip>>;
125
+ window: z.ZodOptional<z.ZodObject<{
126
+ from: z.ZodOptional<z.ZodISODateTime>;
127
+ to: z.ZodOptional<z.ZodISODateTime>;
128
+ }, z.core.$strip>>;
129
+ sampling: z.ZodOptional<z.ZodObject<{
130
+ bands: z.ZodOptional<z.ZodArray<z.ZodObject<{
131
+ metric: z.ZodOptional<z.ZodEnum<{
132
+ views: "views";
133
+ likes: "likes";
134
+ reposts: "reposts";
135
+ replies: "replies";
136
+ bookmarks: "bookmarks";
137
+ points: "points";
138
+ comments: "comments";
139
+ reactions: "reactions";
140
+ score: "score";
141
+ rating: "rating";
142
+ helpfulVotes: "helpfulVotes";
143
+ }>>;
144
+ min: z.ZodOptional<z.ZodNumber>;
145
+ max: z.ZodOptional<z.ZodNumber>;
146
+ quota: z.ZodOptional<z.ZodNumber>;
147
+ }, z.core.$strip>>>;
148
+ keepMissingMetric: z.ZodOptional<z.ZodBoolean>;
149
+ perDomainCap: z.ZodOptional<z.ZodNumber>;
150
+ seed: z.ZodOptional<z.ZodNumber>;
151
+ }, z.core.$strip>>;
152
+ caps: z.ZodOptional<z.ZodObject<{
153
+ perConnector: z.ZodOptional<z.ZodNumber>;
154
+ total: z.ZodOptional<z.ZodNumber>;
155
+ }, z.core.$strip>>;
156
+ workers: z.ZodDefault<z.ZodNumber>;
157
+ lookahead: z.ZodOptional<z.ZodNumber>;
158
+ sinks: z.ZodOptional<z.ZodArray<z.ZodString>>;
159
+ }, z.core.$strip>;
160
+ connectorModules: z.ZodOptional<z.ZodArray<z.ZodString>>;
161
+ origin: z.ZodOptional<z.ZodLiteral<"reparse">>;
162
+ }, z.core.$strip>;
163
+ type RunRecord = z.infer<typeof RunRecord>;
164
+ interface PutRawInput {
165
+ connector: string;
166
+ /** File extension without the dot, e.g. `json`, `html`. */
167
+ ext: string;
168
+ bytes: Uint8Array;
169
+ url: string;
170
+ fetchedAt: string;
171
+ httpStatus?: number;
172
+ contentType?: string;
173
+ transport: string;
174
+ runId?: string;
175
+ /** `<connector>/<task id>`: the task that fetched this body. */
176
+ taskId?: string;
177
+ failure?: FailureCause;
178
+ }
179
+ interface PutRawResult {
180
+ ref: string;
181
+ hash: string;
182
+ /** False when a body with the same bytes already sat at the same path; the index line is still appended. */
183
+ stored: boolean;
184
+ }
185
+ /**
186
+ * A streaming read. `skipped` counts the lines that were unreadable (not JSON,
187
+ * or failing schema validation) and were left out; it is final once the
188
+ * iteration is over and restarts at 0 on each new iteration.
189
+ */
190
+ interface Reader<T> extends AsyncIterable<T> {
191
+ readonly skipped: number;
192
+ }
193
+ interface StoreLock {
194
+ release(): Promise<void>;
195
+ }
196
+ /** Where records are kept, as seen by the engine. Same contract for the memory and the disk store. */
197
+ interface CollectStore {
198
+ /** Version of the stored shapes this store holds (after any migration). */
199
+ schemaVersion(): Promise<number>;
200
+ putRaw(input: PutRawInput): Promise<PutRawResult>;
201
+ getRaw(ref: string): Promise<Uint8Array | undefined>;
202
+ rawIndex(): Reader<RawIndexEntry>;
203
+ /** Insert or replace an item: the last write for an id wins. */
204
+ upsertItem(item: CollectItem): Promise<void>;
205
+ getItem(id: string): Promise<CollectItem | undefined>;
206
+ /** Current version of each item. `source` is the prefix of the item id (`hn` for `hn:1`), which is also the file the item is kept in. */
207
+ items(source?: string): Reader<CollectItem>;
208
+ /** Observations, actors: filed by the id prefix (`itemId` / `ref`), and `source` filters on that prefix. */
209
+ appendObservation(observation: Observation): Promise<void>;
210
+ observations(source?: string): Reader<Observation>;
211
+ appendActor(actor: Actor): Promise<void>;
212
+ actors(source?: string): Reader<Actor>;
213
+ appendPickup(pickup: Pickup): Promise<void>;
214
+ pickups(): Reader<Pickup>;
215
+ /** Dedup keys, see `seenKey`. */
216
+ seenHas(key: string): Promise<boolean>;
217
+ /** The item id that owns a key. `undefined` when the key is unknown or was recorded without an owner. */
218
+ seenGet(key: string): Promise<string | undefined>;
219
+ /** Record a key. `itemId` is the item that owns it; adding an owner to a key that had none sets it, an existing owner is kept. */
220
+ seenAdd(key: string, itemId?: string): Promise<void>;
221
+ seenKeys(): Promise<string[]>;
222
+ /** Recompute the seen keys, with their owners, from the stored items (current version of each). */
223
+ rebuildSeenIndex(): Promise<void>;
224
+ createRun(runId: string, recipe: Recipe, extra?: {
225
+ connectorModules?: string[];
226
+ origin?: "reparse";
227
+ }): Promise<RunRecord>;
228
+ getRun(runId: string): Promise<RunRecord | undefined>;
229
+ listRuns(): Promise<string[]>;
230
+ /** The run-log writers below throw when the run was not created. Append a task state; the last line for a task id is its current state. */
231
+ appendTask(runId: string, task: TaskRecord): Promise<void>;
232
+ tasks(runId: string): Reader<TaskRecord>;
233
+ /** Write the whole root plan of a run in one atomic write. A second call replaces it. */
234
+ writePlan(runId: string, plan: PlanEntry[]): Promise<void>;
235
+ readPlan(runId: string): Promise<PlanEntry[] | undefined>;
236
+ appendSampling(runId: string, record: SamplingRecord): Promise<void>;
237
+ /** Append all the records in one write: a crash leaves a prefix of them, never a reordered or interleaved set. Every record is validated first. */
238
+ appendSamplingBatch(runId: string, records: SamplingRecord[]): Promise<void>;
239
+ sampling(runId: string): Reader<SamplingRecord>;
240
+ appendEvent(runId: string, event: EventRecord): Promise<void>;
241
+ events(runId: string): Reader<EventRecord>;
242
+ writeReport(runId: string, report: RunReport): Promise<void>;
243
+ readReport(runId: string): Promise<RunReport | undefined>;
244
+ /** Take the store-wide writer lock. Throws `StoreLockedError` when it is held. */
245
+ acquireLock(): Promise<StoreLock>;
246
+ }
247
+ declare class StoreLockedError extends Error {
248
+ readonly holder?: {
249
+ pid: number;
250
+ at: string;
251
+ host?: string;
252
+ } | undefined;
253
+ readonly code = "STORE_LOCKED";
254
+ constructor(message: string, holder?: {
255
+ pid: number;
256
+ at: string;
257
+ host?: string;
258
+ } | undefined);
259
+ }
260
+ /** The store was written by a newer version than this reader understands. */
261
+ declare class StoreVersionError extends Error {
262
+ readonly found: number;
263
+ readonly supported: number;
264
+ readonly code = "STORE_VERSION";
265
+ constructor(found: number, supported: number);
266
+ }
267
+ /**
268
+ * Drop the copy a task writes again when it is redone after a crash: records
269
+ * with a `recordKey` are kept once per key, the first write wins (a retry that
270
+ * reads other values for the same raw and index is the same record); records
271
+ * without one always pass. Two distinct readings with equal values have
272
+ * different keys and are both kept.
273
+ */
274
+ declare function dropRedone<T>(source: Reader<T>, tag: (r: T) => string | undefined): Reader<T>;
275
+ /** Records without a `recordKey` (not written by the engine) are never dropped. */
276
+ declare const observationRedoKey: (o: Observation) => string | undefined;
277
+ declare const pickupRedoKey: (p: Pickup) => string | undefined;
278
+ declare const actorRedoKey: (a: Actor) => string | undefined;
279
+ /** Dedup key kinds. Keys are `<kind>:<value>`. */
280
+ declare function seenKey(kind: "id" | "url" | "content", value: string): string;
281
+ /** The keys an item contributes to the seen index: native id, canonical URL, content id. */
282
+ declare function itemSeenKeys(item: CollectItem): string[];
283
+ /** Names that become a path segment (connector, source, run id, extension) are restricted to a safe alphabet. */
284
+ declare function assertSafeName(kind: string, value: string): string;
285
+ /** Source prefix of an id or ref of the form `source:rest`. */
286
+ declare function sourceOf(idOrRef: string): string;
287
+ /** `yyyy-mm` (UTC) of a timestamp. */
288
+ declare function monthOf(timestamp: string): string;
289
+ declare function sha256Bytes(bytes: Uint8Array): Promise<string>;
290
+ /** JSON with object keys sorted, so equal values give equal text. */
291
+ declare function stableStringify(value: unknown): string;
292
+ declare function recipeHash(recipe: Recipe): Promise<string>;
293
+ /** Strict parser of a raw ref. Throws on anything that is not exactly `raw/<connector>/<yyyy-mm>/<sha256>.<ext>.gz`. */
294
+ declare function parseRawRef(ref: string): {
295
+ connector: string;
296
+ month: string;
297
+ hash: string;
298
+ ext: string;
299
+ };
300
+ /** Relative path of a stored raw body. */
301
+ declare function rawRef(connector: string, fetchedAt: string, hash: string, ext: string): string;
302
+ /** Build a `Reader` from a generator that reports each skipped line through `onSkip`. */
303
+ declare function makeReader<T>(gen: (onSkip: () => void) => AsyncGenerator<T>): Reader<T>;
304
+ /** Drain a reader into an array, with the skipped count. */
305
+ declare function readAll<T>(reader: Reader<T>): Promise<{
306
+ records: T[];
307
+ skipped: number;
308
+ }>;
309
+ /** Keep the last record of each key, in order of first appearance. */
310
+ declare function lastWins<T>(source: AsyncIterable<T>, key: (r: T) => string): AsyncGenerator<T>;
311
+
312
+ interface Clock {
313
+ /** Milliseconds since the epoch. */
314
+ now(): number;
315
+ sleep(ms: number, signal?: AbortSignal): Promise<void>;
316
+ }
317
+ interface CollectorOptions {
318
+ store: CollectStore;
319
+ transports: TransportSet;
320
+ /**
321
+ * Where secrets come from. Every value resolved through it during a run is
322
+ * scrubbed from events, task records and reports before they are stored or
323
+ * handed to `onEvent`, and from the message of a `CollectRunError`. Pass a
324
+ * `recordSecrets(port)` recorder and give the same one to anything else that
325
+ * resolves secrets (an API transport) so they share one redaction set.
326
+ */
327
+ secrets?: SecretsPort;
328
+ /**
329
+ * After `signal` aborts, how long to wait for tasks that do not settle (a
330
+ * connector that ignores the abort signal) before the run gives up on them,
331
+ * releases the store lock and returns. Their tasks stay `started` in the run
332
+ * log (so `resume` redoes them) and whatever they do later is not written.
333
+ * Default 10000.
334
+ */
335
+ abortGraceMs?: number;
336
+ /** A list, or a registry. Defaults to the process-wide registry (`registerConnector`). */
337
+ connectors?: Connector[] | ConnectorRegistry;
338
+ clock?: Clock;
339
+ /** Source of randomness for run ids: returns a number in [0, 1). */
340
+ random?: () => number;
341
+ }
342
+ interface RunEvent extends EventRecord {
343
+ runId: string;
344
+ }
345
+ interface RunOptions {
346
+ /** Paths of the connector modules the host loaded for this run; kept in the run record so `resume` can load them again. */
347
+ connectorModules?: string[];
348
+ /** Stop taking tasks when aborted; pending tasks stay pending and a partial report is written. */
349
+ signal?: AbortSignal;
350
+ onEvent?: (event: RunEvent) => void;
351
+ runId?: string;
352
+ }
353
+ /** The run stopped on an error of its own (the store failed, a connector could not plan). The run is left resumable. */
354
+ declare class CollectRunError extends Error {
355
+ readonly runId: string;
356
+ readonly cause: unknown;
357
+ readonly code = "RUN_ERROR";
358
+ constructor(runId: string, cause: unknown);
359
+ }
360
+ /**
361
+ * One collector drives one store: the store lock allows a single run at a
362
+ * time, so the host gate and the browser lane below are per collector and
363
+ * per run by construction. Do not share a browser between two collectors.
364
+ */
365
+ interface Collector {
366
+ /** Plan the recipe and run it. Creates a new run. */
367
+ run(recipe: Recipe | unknown, options?: RunOptions): Promise<RunReport>;
368
+ /**
369
+ * Continue a run from its log. Reloads the frozen recipe, the plan and every
370
+ * task as last recorded; `done` tasks are skipped and never fetched again,
371
+ * `pending`, `failed` and `skipped` tasks are redone (a skipped task is
372
+ * re-checked against the transports and secrets available now; a connector
373
+ * that is no longer registered has its tasks reported skipped). Tasks come
374
+ * back in their recorded global order. The per-connector and total caps are
375
+ * restored from the task states: a task that was `done` or `failed` already
376
+ * used its budget, so retrying it takes none, while a task that never
377
+ * started does. The report covers the whole run, earlier attempts included.
378
+ * A challenge stop does not carry over: the connector is tried again.
379
+ */
380
+ resume(runId: string, options?: Omit<RunOptions, "runId">): Promise<RunReport>;
381
+ }
382
+ declare function createCollector(options: CollectorOptions): Collector;
383
+
384
+ export { readAll as A, recipeHash as B, type CollectStore as C, seenKey as D, EventRecord as E, sha256Bytes as F, sourceOf as G, stableStringify as H, PlanEntry as P, RawIndexEntry as R, SamplingRecord as S, TaskRecord as T, type Clock as a, CollectRunError as b, type Collector as c, type CollectorOptions as d, type PutRawInput as e, type PutRawResult as f, type Reader as g, type RunEvent as h, type RunOptions as i, RunRecord as j, type StoreLock as k, StoreLockedError as l, StoreVersionError as m, TaskStatus as n, actorRedoKey as o, assertSafeName as p, createCollector as q, dropRedone as r, itemSeenKeys as s, lastWins as t, makeReader as u, monthOf as v, observationRedoKey as w, parseRawRef as x, pickupRedoKey as y, rawRef as z };