@agentproto/collect 0.0.0-stage → 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,213 @@
1
+ import { FailureCause, Recipe, sha256Hex } from './chunk-FQLYZIVI.mjs';
2
+ import { z } from 'zod';
3
+
4
+ /**
5
+ * @agentproto/collect
6
+ * Schemas, ids, URL canonicalisation and text fingerprints for collected public content.
7
+ */
8
+ var RawIndexEntry = z.object({
9
+ /** Store-relative path of the stored body, `raw/<connector>/<yyyy-mm>/<sha256>.<ext>.gz`. */
10
+ ref: z.string().min(1),
11
+ connector: z.string().min(1),
12
+ /** SHA-256 of the body bytes, lowercase hex. */
13
+ hash: z.string().length(64),
14
+ ext: z.string().min(1),
15
+ bytes: z.number().int().nonnegative(),
16
+ url: z.string(),
17
+ fetchedAt: z.iso.datetime({ offset: true }),
18
+ httpStatus: z.number().int().optional(),
19
+ /** `Content-Type` of the response (or what a browser snapshot is stored as), so a body is decoded the way it was served. Absent in older stores. */
20
+ contentType: z.string().optional(),
21
+ transport: z.string(),
22
+ runId: z.string().optional(),
23
+ /** `<connector>/<task id>` of the task that fetched it (a key of the run's task log). Absent in older stores. */
24
+ taskId: z.string().optional(),
25
+ /** Set when the fetch failed (403, empty page, ...). The body, if any, is still kept. */
26
+ failure: FailureCause.optional()
27
+ });
28
+ var PlanEntry = z.object({
29
+ taskId: z.string().min(1),
30
+ connector: z.string().min(1),
31
+ order: z.array(z.number().int().nonnegative()),
32
+ payload: z.record(z.string(), z.unknown())
33
+ });
34
+ var TaskStatus = z.enum(["pending", "started", "done", "failed", "skipped"]);
35
+ var TaskRecord = z.object({
36
+ taskId: z.string().min(1),
37
+ connector: z.string().min(1),
38
+ status: TaskStatus,
39
+ transport: z.string().optional(),
40
+ reason: z.string().optional(),
41
+ /** Why a failed task failed. */
42
+ cause: FailureCause.optional(),
43
+ /** Global start order: connector index in the recipe, plan index, then follow-up depth and index. */
44
+ order: z.array(z.number().int().nonnegative()).optional(),
45
+ /** What the task did, recorded with its `done` (or `failed`) state; the run report is rebuilt from these. */
46
+ counters: z.object({
47
+ items: z.number().int().nonnegative(),
48
+ newItems: z.number().int().nonnegative(),
49
+ duplicates: z.number().int().nonnegative(),
50
+ observations: z.number().int().nonnegative(),
51
+ metricValues: z.number().int().nonnegative(),
52
+ durationMs: z.number().nonnegative()
53
+ }).optional(),
54
+ /** The task took budget (it has a `started` record), whatever its state is now. */
55
+ charged: z.boolean().optional(),
56
+ /** Transport changes the task went through (`http` to `browser`). */
57
+ escalations: z.array(z.object({ from: z.string(), to: z.string() })).optional(),
58
+ /** The task as the connector planned it (`id`, `kind`, `params`), so a run can be resumed from its log alone. */
59
+ payload: z.record(z.string(), z.unknown()).optional(),
60
+ updatedAt: z.iso.datetime({ offset: true })
61
+ });
62
+ var SamplingRecord = z.object({
63
+ candidate: z.string().min(1),
64
+ decision: z.enum(["kept", "dropped"]),
65
+ /** Why a candidate was dropped: `band_quota`, `domain_cap`, `no_metric` or `out_of_bands`. */
66
+ rule: z.string().optional(),
67
+ /** Index of the counter band the candidate fell in. */
68
+ band: z.number().int().nonnegative().optional(),
69
+ /** Canonical URL of the candidate, so a later alias of it follows its decision. */
70
+ url: z.string().optional(),
71
+ /** Host the candidate counted against. */
72
+ domain: z.string().optional(),
73
+ seed: z.number().int().optional(),
74
+ connector: z.string().optional(),
75
+ taskId: z.string().optional(),
76
+ at: z.iso.datetime({ offset: true })
77
+ });
78
+ var EventRecord = z.object({
79
+ at: z.iso.datetime({ offset: true }),
80
+ type: z.string().min(1),
81
+ data: z.record(z.string(), z.unknown()).optional()
82
+ });
83
+ var RunRecord = z.object({
84
+ runId: z.string().min(1),
85
+ createdAt: z.iso.datetime({ offset: true }),
86
+ recipeHash: z.string().length(64),
87
+ recipe: Recipe,
88
+ /** Absolute paths of the connector modules the run was started with, for hosts that load connectors from files. */
89
+ connectorModules: z.array(z.string()).optional(),
90
+ /** `reparse`: a copy of the run records of a reparsed store, for reparsing again only. It cannot be resumed. */
91
+ origin: z.literal("reparse").optional()
92
+ });
93
+ var StoreLockedError = class extends Error {
94
+ constructor(message, holder) {
95
+ super(message);
96
+ this.holder = holder;
97
+ this.name = "StoreLockedError";
98
+ }
99
+ holder;
100
+ code = "STORE_LOCKED";
101
+ };
102
+ var StoreVersionError = class extends Error {
103
+ constructor(found, supported) {
104
+ super(`store schema version ${found} is newer than the supported version ${supported}; upgrade @agentproto/collect`);
105
+ this.found = found;
106
+ this.supported = supported;
107
+ this.name = "StoreVersionError";
108
+ }
109
+ found;
110
+ supported;
111
+ code = "STORE_VERSION";
112
+ };
113
+ function dropRedone(source, tag) {
114
+ return {
115
+ get skipped() {
116
+ return source.skipped;
117
+ },
118
+ async *[Symbol.asyncIterator]() {
119
+ const seen = /* @__PURE__ */ new Set();
120
+ for await (const r of source) {
121
+ const k = tag(r);
122
+ if (k !== void 0) {
123
+ if (seen.has(k)) continue;
124
+ seen.add(k);
125
+ }
126
+ yield r;
127
+ }
128
+ }
129
+ };
130
+ }
131
+ var observationRedoKey = (o) => o.recordKey;
132
+ var pickupRedoKey = (p) => p.recordKey;
133
+ var actorRedoKey = (a) => a.recordKey;
134
+ function seenKey(kind, value) {
135
+ if (value.includes("\n") || value.includes(" ")) throw new Error("a seen key cannot contain a newline or a tab");
136
+ return `${kind}:${value}`;
137
+ }
138
+ function itemSeenKeys(item) {
139
+ const keys = [seenKey("id", item.id)];
140
+ if (item.canonicalUrl) keys.push(seenKey("url", item.canonicalUrl));
141
+ if (item.contentId) keys.push(seenKey("content", item.contentId));
142
+ return keys;
143
+ }
144
+ var SAFE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
145
+ function assertSafeName(kind, value) {
146
+ if (!SAFE_NAME.test(value) || value.includes("..")) {
147
+ throw new Error(`invalid ${kind} "${value}": use letters, digits, ".", "_" and "-"`);
148
+ }
149
+ return value;
150
+ }
151
+ function sourceOf(idOrRef) {
152
+ const i = idOrRef.indexOf(":");
153
+ if (i <= 0) throw new Error(`"${idOrRef}" has no source prefix`);
154
+ return assertSafeName("source", idOrRef.slice(0, i));
155
+ }
156
+ function monthOf(timestamp) {
157
+ return new Date(timestamp).toISOString().slice(0, 7);
158
+ }
159
+ async function sha256Bytes(bytes) {
160
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
161
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
162
+ }
163
+ function stableStringify(value) {
164
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
165
+ if (value && typeof value === "object") {
166
+ const o = value;
167
+ return `{${Object.keys(o).sort().filter((k) => o[k] !== void 0).map((k) => `${JSON.stringify(k)}:${stableStringify(o[k])}`).join(",")}}`;
168
+ }
169
+ return JSON.stringify(value) ?? "null";
170
+ }
171
+ async function recipeHash(recipe) {
172
+ return sha256Hex(stableStringify(recipe));
173
+ }
174
+ var RAW_REF = /^raw\/([A-Za-z0-9][A-Za-z0-9._-]*)\/(\d{4}-\d{2})\/([0-9a-f]{64})\.([A-Za-z0-9][A-Za-z0-9._-]*)\.gz$/;
175
+ function parseRawRef(ref) {
176
+ const m = RAW_REF.exec(ref);
177
+ if (!m || ref.includes("..") || ref.includes("\\")) throw new Error(`invalid raw ref "${ref}"`);
178
+ return { connector: m[1], month: m[2], hash: m[3], ext: m[4] };
179
+ }
180
+ function rawRef(connector, fetchedAt, hash, ext) {
181
+ const ref = `raw/${assertSafeName("connector", connector)}/${monthOf(fetchedAt)}/${hash}.${assertSafeName("extension", ext)}.gz`;
182
+ parseRawRef(ref);
183
+ return ref;
184
+ }
185
+ function makeReader(gen) {
186
+ const r = {
187
+ skipped: 0,
188
+ [Symbol.asyncIterator]() {
189
+ r.skipped = 0;
190
+ return gen(() => {
191
+ r.skipped++;
192
+ });
193
+ }
194
+ };
195
+ return r;
196
+ }
197
+ async function readAll(reader) {
198
+ const records = [];
199
+ for await (const r of reader) records.push(r);
200
+ return { records, skipped: reader.skipped };
201
+ }
202
+ async function* lastWins(source, key) {
203
+ const m = /* @__PURE__ */ new Map();
204
+ for await (const r of source) m.set(key(r), r);
205
+ yield* m.values();
206
+ }
207
+
208
+ // src/version.ts
209
+ var STORE_SCHEMA_VERSION = 1;
210
+
211
+ export { EventRecord, PlanEntry, RawIndexEntry, RunRecord, STORE_SCHEMA_VERSION, SamplingRecord, StoreLockedError, StoreVersionError, TaskRecord, TaskStatus, actorRedoKey, assertSafeName, dropRedone, itemSeenKeys, lastWins, makeReader, monthOf, observationRedoKey, parseRawRef, pickupRedoKey, rawRef, readAll, recipeHash, seenKey, sha256Bytes, sourceOf, stableStringify };
212
+ //# sourceMappingURL=chunk-SOLT3HJH.mjs.map
213
+ //# sourceMappingURL=chunk-SOLT3HJH.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/store.ts","../src/version.ts"],"names":[],"mappings":";;;;;;;AAKO,IAAM,aAAA,GAAgB,EAAE,MAAA,CAAO;AAAA;AAAA,EAEpC,GAAA,EAAK,CAAA,CAAE,MAAA,EAAO,CAAE,IAAI,CAAC,CAAA;AAAA,EACrB,SAAA,EAAW,CAAA,CAAE,MAAA,EAAO,CAAE,IAAI,CAAC,CAAA;AAAA;AAAA,EAE3B,IAAA,EAAM,CAAA,CAAE,MAAA,EAAO,CAAE,OAAO,EAAE,CAAA;AAAA,EAC1B,GAAA,EAAK,CAAA,CAAE,MAAA,EAAO,CAAE,IAAI,CAAC,CAAA;AAAA,EACrB,OAAO,CAAA,CAAE,MAAA,EAAO,CAAE,GAAA,GAAM,WAAA,EAAY;AAAA,EACpC,GAAA,EAAK,EAAE,MAAA,EAAO;AAAA,EACd,WAAW,CAAA,CAAE,GAAA,CAAI,SAAS,EAAE,MAAA,EAAQ,MAAM,CAAA;AAAA,EAC1C,YAAY,CAAA,CAAE,MAAA,EAAO,CAAE,GAAA,GAAM,QAAA,EAAS;AAAA;AAAA,EAEtC,WAAA,EAAa,CAAA,CAAE,MAAA,EAAO,CAAE,Q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EAAA,OAAO,GAAA;AACT;AAGO,SAAS,WAAc,GAAA,EAA2D;AACvF,EAAA,MAAM,CAAA,GAAI;AAAA,IACR,OAAA,EAAS,CAAA;AAAA,IACT,CAAC,MAAA,CAAO,aAAa,CAAA,GAAI;AACvB,MAAA,CAAA,CAAE,OAAA,GAAU,CAAA;AACZ,MAAA,OAAO,IAAI,MAAM;AACf,QAAA,CAAA,CAAE,OAAA,EAAA;AAAA,MACJ,CAAC,CAAA;AAAA,IACH;AAAA,GACF;AACA,EAAA,OAAO,CAAA;AACT;AAGA,eAAsB,QAAW,MAAA,EAA+D;AAC9F,EAAA,MAAM,UAAe,EAAC;AACtB,EAAA,WAAA,MAAiB,CAAA,IAAK,MAAA,EAAQ,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA;AAC5C,EAAA,OAAO,EAAE,OAAA,EAAS,OAAA,EAAS,MAAA,CAAO,OAAA,EAAQ;AAC5C;AAGA,gBAAuB,QAAA,CAAY,QAA0B,GAAA,EAA0C;AACrG,EAAA,MAAM,CAAA,uBAAQ,GAAA,EAAe;AAC7B,EAAA,WAAA,MAAiB,KAAK,MAAA,EAAQ,CAAA,CAAE,IAAI,GAAA,CAAI,CAAC,GAAG,CAAC,CAAA;AAC7C,EAAA,OAAO,EAAE,MAAA,EAAO;AAClB;;;ACpWO,IAAM,oBAAA,GAAuB","file":"chunk-SOLT3HJH.mjs","sourcesContent":["import { z } from \"zod\"\nimport { Actor, CollectItem, FailureCause, Observation, Pickup, Recipe, RunReport } from \"./schemas\"\nimport { sha256Hex } from \"./ids\"\n\n/** One line of `raw/index.jsonl`: where a fetched body lives and how it was fetched. */\nexport const RawIndexEntry = z.object({\n /** Store-relative path of the stored body, `raw/<connector>/<yyyy-mm>/<sha256>.<ext>.gz`. */\n ref: z.string().min(1),\n connector: z.string().min(1),\n /** SHA-256 of the body bytes, lowercase hex. */\n hash: z.string().length(64),\n ext: z.string().min(1),\n bytes: z.number().int().nonnegative(),\n url: z.string(),\n fetchedAt: z.iso.datetime({ offset: true }),\n httpStatus: z.number().int().optional(),\n /** `Content-Type` of the response (or what a browser snapshot is stored as), so a body is decoded the way it was served. Absent in older stores. */\n contentType: z.string().optional(),\n transport: z.string(),\n runId: z.string().optional(),\n /** `<connector>/<task id>` of the task that fetched it (a key of the run's task log). Absent in older stores. */\n taskId: z.string().optional(),\n /** Set when the fetch failed (403, empty page, ...). The body, if any, is still kept. */\n failure: FailureCause.optional(),\n})\nexport type RawIndexEntry = z.infer<typeof RawIndexEntry>\n\n/** One line of `plan.jsonl`: a root task of the run, written once and atomically before anything runs. */\nexport const PlanEntry = z.object({\n taskId: z.string().min(1),\n connector: z.string().min(1),\n order: z.array(z.number().int().nonnegative()),\n payload: z.record(z.string(), z.unknown()),\n})\nexport type PlanEntry = z.infer<typeof PlanEntry>\n\nexport const TaskStatus = z.enum([\"pending\", \"started\", \"done\", \"failed\", \"skipped\"])\nexport type TaskStatus = z.infer<typeof TaskStatus>\n\n/** One line of `tasks.jsonl`. The last line for a task id is its current state. */\nexport const TaskRecord = z.object({\n taskId: z.string().min(1),\n connector: z.string().min(1),\n status: TaskStatus,\n transport: z.string().optional(),\n reason: z.string().optional(),\n /** Why a failed task failed. */\n cause: FailureCause.optional(),\n /** Global start order: connector index in the recipe, plan index, then follow-up depth and index. */\n order: z.array(z.number().int().nonnegative()).optional(),\n /** What the task did, recorded with its `done` (or `failed`) state; the run report is rebuilt from these. */\n counters: z\n .object({\n items: z.number().int().nonnegative(),\n newItems: z.number().int().nonnegative(),\n duplicates: z.number().int().nonnegative(),\n observations: z.number().int().nonnegative(),\n metricValues: z.number().int().nonnegative(),\n durationMs: z.number().nonnegative(),\n })\n .optional(),\n /** The task took budget (it has a `started` record), whatever its state is now. */\n charged: z.boolean().optional(),\n /** Transport changes the task went through (`http` to `browser`). */\n escalations: z.array(z.object({ from: z.string(), to: z.string() })).optional(),\n /** The task as the connector planned it (`id`, `kind`, `params`), so a run can be resumed from its log alone. */\n payload: z.record(z.string(), z.unknown()).optional(),\n updatedAt: z.iso.datetime({ offset: true }),\n})\nexport type TaskRecord = z.infer<typeof TaskRecord>\n\n/** One line of `sampling.jsonl`: a candidate seen, and whether the sampling kept it. */\nexport const SamplingRecord = z.object({\n candidate: z.string().min(1),\n decision: z.enum([\"kept\", \"dropped\"]),\n /** Why a candidate was dropped: `band_quota`, `domain_cap`, `no_metric` or `out_of_bands`. */\n rule: z.string().optional(),\n /** Index of the counter band the candidate fell in. */\n band: z.number().int().nonnegative().optional(),\n /** Canonical URL of the candidate, so a later alias of it follows its decision. */\n url: z.string().optional(),\n /** Host the candidate counted against. */\n domain: z.string().optional(),\n seed: z.number().int().optional(),\n connector: z.string().optional(),\n taskId: z.string().optional(),\n at: z.iso.datetime({ offset: true }),\n})\nexport type SamplingRecord = z.infer<typeof SamplingRecord>\n\n/** One line of `events.jsonl`. */\nexport const EventRecord = z.object({\n at: z.iso.datetime({ offset: true }),\n type: z.string().min(1),\n data: z.record(z.string(), z.unknown()).optional(),\n})\nexport type EventRecord = z.infer<typeof EventRecord>\n\n/** Content of `runs/<runId>/recipe.json`: the recipe as it was when the run started, and its hash. */\nexport const RunRecord = z.object({\n runId: z.string().min(1),\n createdAt: z.iso.datetime({ offset: true }),\n recipeHash: z.string().length(64),\n recipe: Recipe,\n /** Absolute paths of the connector modules the run was started with, for hosts that load connectors from files. */\n connectorModules: z.array(z.string()).optional(),\n /** `reparse`: a copy of the run records of a reparsed store, for reparsing again only. It cannot be resumed. */\n origin: z.literal(\"reparse\").optional(),\n})\nexport type RunRecord = z.infer<typeof RunRecord>\n\nexport interface PutRawInput {\n connector: string\n /** File extension without the dot, e.g. `json`, `html`. */\n ext: string\n bytes: Uint8Array\n url: string\n fetchedAt: string\n httpStatus?: number\n contentType?: string\n transport: string\n runId?: string\n /** `<connector>/<task id>`: the task that fetched this body. */\n taskId?: string\n failure?: FailureCause\n}\n\nexport interface PutRawResult {\n ref: string\n hash: string\n /** False when a body with the same bytes already sat at the same path; the index line is still appended. */\n stored: boolean\n}\n\n/**\n * A streaming read. `skipped` counts the lines that were unreadable (not JSON,\n * or failing schema validation) and were left out; it is final once the\n * iteration is over and restarts at 0 on each new iteration.\n */\nexport interface Reader<T> extends AsyncIterable<T> {\n readonly skipped: number\n}\n\nexport interface StoreLock {\n release(): Promise<void>\n}\n\n/** Where records are kept, as seen by the engine. Same contract for the memory and the disk store. */\nexport interface CollectStore {\n /** Version of the stored shapes this store holds (after any migration). */\n schemaVersion(): Promise<number>\n\n putRaw(input: PutRawInput): Promise<PutRawResult>\n getRaw(ref: string): Promise<Uint8Array | undefined>\n rawIndex(): Reader<RawIndexEntry>\n\n /** Insert or replace an item: the last write for an id wins. */\n upsertItem(item: CollectItem): Promise<void>\n getItem(id: string): Promise<CollectItem | undefined>\n /** 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. */\n items(source?: string): Reader<CollectItem>\n\n /** Observations, actors: filed by the id prefix (`itemId` / `ref`), and `source` filters on that prefix. */\n appendObservation(observation: Observation): Promise<void>\n observations(source?: string): Reader<Observation>\n appendActor(actor: Actor): Promise<void>\n actors(source?: string): Reader<Actor>\n appendPickup(pickup: Pickup): Promise<void>\n pickups(): Reader<Pickup>\n\n /** Dedup keys, see `seenKey`. */\n seenHas(key: string): Promise<boolean>\n /** The item id that owns a key. `undefined` when the key is unknown or was recorded without an owner. */\n seenGet(key: string): Promise<string | undefined>\n /** 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. */\n seenAdd(key: string, itemId?: string): Promise<void>\n seenKeys(): Promise<string[]>\n /** Recompute the seen keys, with their owners, from the stored items (current version of each). */\n rebuildSeenIndex(): Promise<void>\n\n createRun(runId: string, recipe: Recipe, extra?: { connectorModules?: string[]; origin?: \"reparse\" }): Promise<RunRecord>\n getRun(runId: string): Promise<RunRecord | undefined>\n listRuns(): Promise<string[]>\n /** 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. */\n appendTask(runId: string, task: TaskRecord): Promise<void>\n tasks(runId: string): Reader<TaskRecord>\n /** Write the whole root plan of a run in one atomic write. A second call replaces it. */\n writePlan(runId: string, plan: PlanEntry[]): Promise<void>\n readPlan(runId: string): Promise<PlanEntry[] | undefined>\n appendSampling(runId: string, record: SamplingRecord): Promise<void>\n /** 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. */\n appendSamplingBatch(runId: string, records: SamplingRecord[]): Promise<void>\n sampling(runId: string): Reader<SamplingRecord>\n appendEvent(runId: string, event: EventRecord): Promise<void>\n events(runId: string): Reader<EventRecord>\n writeReport(runId: string, report: RunReport): Promise<void>\n readReport(runId: string): Promise<RunReport | undefined>\n\n /** Take the store-wide writer lock. Throws `StoreLockedError` when it is held. */\n acquireLock(): Promise<StoreLock>\n}\n\nexport class StoreLockedError extends Error {\n readonly code = \"STORE_LOCKED\"\n constructor(\n message: string,\n readonly holder?: { pid: number; at: string; host?: string },\n ) {\n super(message)\n this.name = \"StoreLockedError\"\n }\n}\n\n/** The store was written by a newer version than this reader understands. */\nexport class StoreVersionError extends Error {\n readonly code = \"STORE_VERSION\"\n constructor(\n readonly found: number,\n readonly supported: number,\n ) {\n super(`store schema version ${found} is newer than the supported version ${supported}; upgrade @agentproto/collect`)\n this.name = \"StoreVersionError\"\n }\n}\n\n/**\n * Drop the copy a task writes again when it is redone after a crash: records\n * with a `recordKey` are kept once per key, the first write wins (a retry that\n * reads other values for the same raw and index is the same record); records\n * without one always pass. Two distinct readings with equal values have\n * different keys and are both kept.\n */\nexport function dropRedone<T>(source: Reader<T>, tag: (r: T) => string | undefined): Reader<T> {\n return {\n get skipped() {\n return source.skipped\n },\n async *[Symbol.asyncIterator]() {\n const seen = new Set<string>()\n for await (const r of source) {\n const k = tag(r)\n if (k !== undefined) {\n if (seen.has(k)) continue\n seen.add(k)\n }\n yield r\n }\n },\n }\n}\n\n/** Records without a `recordKey` (not written by the engine) are never dropped. */\nexport const observationRedoKey = (o: Observation) => o.recordKey\nexport const pickupRedoKey = (p: Pickup) => p.recordKey\nexport const actorRedoKey = (a: Actor) => a.recordKey\n\n/** Dedup key kinds. Keys are `<kind>:<value>`. */\nexport function seenKey(kind: \"id\" | \"url\" | \"content\", value: string): string {\n if (value.includes(\"\\n\") || value.includes(\"\\t\")) throw new Error(\"a seen key cannot contain a newline or a tab\")\n return `${kind}:${value}`\n}\n\n/** The keys an item contributes to the seen index: native id, canonical URL, content id. */\nexport function itemSeenKeys(item: CollectItem): string[] {\n const keys = [seenKey(\"id\", item.id)]\n if (item.canonicalUrl) keys.push(seenKey(\"url\", item.canonicalUrl))\n if (item.contentId) keys.push(seenKey(\"content\", item.contentId))\n return keys\n}\n\nconst SAFE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/\n\n/** Names that become a path segment (connector, source, run id, extension) are restricted to a safe alphabet. */\nexport function assertSafeName(kind: string, value: string): string {\n if (!SAFE_NAME.test(value) || value.includes(\"..\")) {\n throw new Error(`invalid ${kind} \"${value}\": use letters, digits, \".\", \"_\" and \"-\"`)\n }\n return value\n}\n\n/** Source prefix of an id or ref of the form `source:rest`. */\nexport function sourceOf(idOrRef: string): string {\n const i = idOrRef.indexOf(\":\")\n if (i <= 0) throw new Error(`\"${idOrRef}\" has no source prefix`)\n return assertSafeName(\"source\", idOrRef.slice(0, i))\n}\n\n/** `yyyy-mm` (UTC) of a timestamp. */\nexport function monthOf(timestamp: string): string {\n return new Date(timestamp).toISOString().slice(0, 7)\n}\n\nexport async function sha256Bytes(bytes: Uint8Array): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes as Uint8Array<ArrayBuffer>)\n return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n}\n\n/** JSON with object keys sorted, so equal values give equal text. */\nexport function stableStringify(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(\",\")}]`\n if (value && typeof value === \"object\") {\n const o = value as Record<string, unknown>\n return `{${Object.keys(o)\n .sort()\n .filter((k) => o[k] !== undefined)\n .map((k) => `${JSON.stringify(k)}:${stableStringify(o[k])}`)\n .join(\",\")}}`\n }\n return JSON.stringify(value) ?? \"null\"\n}\n\nexport async function recipeHash(recipe: Recipe): Promise<string> {\n return sha256Hex(stableStringify(recipe))\n}\n\nconst RAW_REF = /^raw\\/([A-Za-z0-9][A-Za-z0-9._-]*)\\/(\\d{4}-\\d{2})\\/([0-9a-f]{64})\\.([A-Za-z0-9][A-Za-z0-9._-]*)\\.gz$/\n\n/** Strict parser of a raw ref. Throws on anything that is not exactly `raw/<connector>/<yyyy-mm>/<sha256>.<ext>.gz`. */\nexport function parseRawRef(ref: string): { connector: string; month: string; hash: string; ext: string } {\n const m = RAW_REF.exec(ref)\n if (!m || ref.includes(\"..\") || ref.includes(\"\\\\\")) throw new Error(`invalid raw ref \"${ref}\"`)\n return { connector: m[1]!, month: m[2]!, hash: m[3]!, ext: m[4]! }\n}\n\n/** Relative path of a stored raw body. */\nexport function rawRef(connector: string, fetchedAt: string, hash: string, ext: string): string {\n const ref = `raw/${assertSafeName(\"connector\", connector)}/${monthOf(fetchedAt)}/${hash}.${assertSafeName(\"extension\", ext)}.gz`\n parseRawRef(ref)\n return ref\n}\n\n/** Build a `Reader` from a generator that reports each skipped line through `onSkip`. */\nexport function makeReader<T>(gen: (onSkip: () => void) => AsyncGenerator<T>): Reader<T> {\n const r = {\n skipped: 0,\n [Symbol.asyncIterator]() {\n r.skipped = 0\n return gen(() => {\n r.skipped++\n })\n },\n }\n return r\n}\n\n/** Drain a reader into an array, with the skipped count. */\nexport async function readAll<T>(reader: Reader<T>): Promise<{ records: T[]; skipped: number }> {\n const records: T[] = []\n for await (const r of reader) records.push(r)\n return { records, skipped: reader.skipped }\n}\n\n/** Keep the last record of each key, in order of first appearance. */\nexport async function* lastWins<T>(source: AsyncIterable<T>, key: (r: T) => string): AsyncGenerator<T> {\n const m = new Map<string, T>()\n for await (const r of source) m.set(key(r), r)\n yield* m.values()\n}\n","/** Version written to `collect.json` at a store root. Bump on any change to the stored shapes. */\nexport const STORE_SCHEMA_VERSION = 1\n"]}
@@ -0,0 +1,98 @@
1
+ import { MetricName } from './chunk-FQLYZIVI.mjs';
2
+ import { z } from 'zod';
3
+
4
+ /**
5
+ * @agentproto/collect
6
+ * Schemas, ids, URL canonicalisation and text fingerprints for collected public content.
7
+ */
8
+ var CollectTask = z.object({
9
+ /** Unique within its connector, and the same for the same recipe. */
10
+ id: z.string().min(1),
11
+ kind: z.string().optional(),
12
+ params: z.record(z.string(), z.unknown()).default({})
13
+ });
14
+ var CounterDeclaration = z.object({
15
+ name: MetricName,
16
+ /** What the number counts, e.g. `count`, `points`, `stars`. */
17
+ unit: z.string().min(1),
18
+ /** `root`: the root message only. `thread`: the whole thread. */
19
+ scope: z.enum(["root", "thread"]),
20
+ /** The platform's own main counter (at most one per connector). */
21
+ primary: z.boolean().default(false)
22
+ });
23
+ var AccessDeclaration = z.discriminatedUnion("level", [
24
+ z.object({ level: z.literal("none") }),
25
+ /** Needs the secret `secret` from the `SecretsPort`. */
26
+ z.object({ level: z.literal("key"), secret: z.string().min(1) }),
27
+ /** Needs a logged-in session on `site`. */
28
+ z.object({ level: z.literal("session"), site: z.string().min(1) })
29
+ ]);
30
+ var Capability = z.enum(["search", "list", "read-by-url", "author-profile", "re-observe"]);
31
+ var Pace = z.object({
32
+ /** Minimum interval between two requests to the same host. */
33
+ delayMs: z.number().int().nonnegative().default(0),
34
+ /** Most tasks this connector may start in one run. */
35
+ maxTasksPerRun: z.number().int().positive().optional()
36
+ });
37
+ var SessionCheck = z.object({
38
+ url: z.string().url(),
39
+ evaluate: z.string().min(1)
40
+ });
41
+ var TransportNameSchema = z.enum(["api", "http", "browser"]);
42
+ var ConnectorDeclaration = z.object({
43
+ id: z.string().regex(/^[a-z0-9][a-z0-9-]*$/, "use lowercase letters, digits and dashes"),
44
+ version: z.string().min(1),
45
+ /** Preference order: the engine tries them in this order. */
46
+ transports: z.array(TransportNameSchema).min(1),
47
+ access: AccessDeclaration.default({ level: "none" }),
48
+ capabilities: z.array(Capability).default([]),
49
+ counters: z.array(CounterDeclaration).default([]),
50
+ pace: Pace.default({ delayMs: 0 }),
51
+ sessionCheck: SessionCheck.optional()
52
+ }).superRefine((d, ctx) => {
53
+ if (new Set(d.transports).size !== d.transports.length) {
54
+ ctx.addIssue({ code: "custom", path: ["transports"], message: "duplicate transport" });
55
+ }
56
+ if (d.counters.filter((c) => c.primary).length > 1) {
57
+ ctx.addIssue({ code: "custom", path: ["counters"], message: "at most one primary counter" });
58
+ }
59
+ if (new Set(d.counters.map((c) => c.name)).size !== d.counters.length) {
60
+ ctx.addIssue({ code: "custom", path: ["counters"], message: "duplicate counter" });
61
+ }
62
+ });
63
+ function defineConnector(definition) {
64
+ const { ext, plan, fetch, parse, ...declaration } = definition;
65
+ const parsed = ConnectorDeclaration.parse(declaration);
66
+ for (const [name, fn] of Object.entries({ plan, fetch, parse })) {
67
+ if (typeof fn !== "function") throw new TypeError(`connector ${parsed.id}: ${name} must be a function`);
68
+ }
69
+ return Object.freeze({ ...parsed, ext, plan, fetch, parse });
70
+ }
71
+ function createConnectorRegistry(initial = []) {
72
+ const map = /* @__PURE__ */ new Map();
73
+ const registry = {
74
+ register(connector) {
75
+ if (map.has(connector.id)) throw new Error(`connector "${connector.id}" is already registered`);
76
+ map.set(connector.id, connector);
77
+ },
78
+ get: (id) => map.get(id),
79
+ list: () => [...map.values()]
80
+ };
81
+ for (const c of initial) registry.register(c);
82
+ return registry;
83
+ }
84
+ var globalRegistry = createConnectorRegistry();
85
+ function registerConnector(connector) {
86
+ globalRegistry.register(connector);
87
+ return connector;
88
+ }
89
+ function getConnector(id) {
90
+ return globalRegistry.get(id);
91
+ }
92
+ function listConnectors() {
93
+ return globalRegistry.list();
94
+ }
95
+
96
+ export { AccessDeclaration, Capability, CollectTask, ConnectorDeclaration, CounterDeclaration, Pace, SessionCheck, TransportNameSchema, createConnectorRegistry, defineConnector, getConnector, listConnectors,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a,EAAA,EAAmC;AAC9D,EAAA,OAAO,cAAA,CAAe,IAAI,EAAE,CAAA;AAC9B;AAEO,SAAS,cAAA,GAA8B;AAC5C,EAAA,OAAO,eAAe,IAAA,EAAK;AAC7B","file":"chunk-SYTQ6RN6.mjs","sourcesContent":["import { z } from \"zod\"\nimport {\n Actor,\n CollectItem,\n MetricName,\n ObservationBase,\n PickupBase,\n type Recipe as RecipeType,\n} from \"./schemas\"\nimport type { FetchTransport, SecretsPort, TransportName } from \"./transport\"\n\n/** A unit of work a connector plans: stable id, plain-JSON parameters. */\nexport const CollectTask = z.object({\n /** Unique within its connector, and the same for the same recipe. */\n id: z.string().min(1),\n kind: z.string().optional(),\n params: z.record(z.string(), z.unknown()).default({}),\n})\nexport type CollectTask = z.input<typeof CollectTask>\n\nexport const CounterDeclaration = z.object({\n name: MetricName,\n /** What the number counts, e.g. `count`, `points`, `stars`. */\n unit: z.string().min(1),\n /** `root`: the root message only. `thread`: the whole thread. */\n scope: z.enum([\"root\", \"thread\"]),\n /** The platform's own main counter (at most one per connector). */\n primary: z.boolean().default(false),\n})\nexport type CounterDeclaration = z.input<typeof CounterDeclaration>\n\nexport const AccessDeclaration = z.discriminatedUnion(\"level\", [\n z.object({ level: z.literal(\"none\") }),\n /** Needs the secret `secret` from the `SecretsPort`. */\n z.object({ level: z.literal(\"key\"), secret: z.string().min(1) }),\n /** Needs a logged-in session on `site`. */\n z.object({ level: z.literal(\"session\"), site: z.string().min(1) }),\n])\nexport type AccessDeclaration = z.infer<typeof AccessDeclaration>\n\nexport const Capability = z.enum([\"search\", \"list\", \"read-by-url\", \"author-profile\", \"re-observe\"])\nexport type Capability = z.infer<typeof Capability>\n\nexport const Pace = z.object({\n /** Minimum interval between two requests to the same host. */\n delayMs: z.number().int().nonnegative().default(0),\n /** Most tasks this connector may start in one run. */\n maxTasksPerRun: z.number().int().positive().optional(),\n})\nexport type Pace = z.infer<typeof Pace>\n\n/**\n * How to tell whether the browser holds an open session on the site of a\n * `session` connector. `collect doctor` opens `url`, then runs `evaluate`, a\n * function body, in the page, wrapped there: an exception is caught in the\n * page and only a fixed code crosses back (`open` when the body returned\n * exactly `true`, `none` for anything else, `error` when it threw). It must\n * answer from what the page shows and never return cookies or tokens. The\n * script is the connector's own trusted code; the read-only rule binds the\n * connector author (no submitting, posting or changing anything).\n */\nexport const SessionCheck = z.object({\n url: z.string().url(),\n evaluate: z.string().min(1),\n})\nexport type SessionCheck = z.infer<typeof SessionCheck>\n\nexport const TransportNameSchema = z.enum([\"api\", \"http\", \"browser\"])\n\n/** The data part of a connector, validated by `defineConnector`. */\nexport const ConnectorDeclaration = z\n .object({\n id: z.string().regex(/^[a-z0-9][a-z0-9-]*$/, \"use lowercase letters, digits and dashes\"),\n version: z.string().min(1),\n /** Preference order: the engine tries them in this order. */\n transports: z.array(TransportNameSchema).min(1),\n access: AccessDeclaration.default({ level: \"none\" }),\n capabilities: z.array(Capability).default([]),\n counters: z.array(CounterDeclaration).default([]),\n pace: Pace.default({ delayMs: 0 }),\n sessionCheck: SessionCheck.optional(),\n })\n .superRefine((d, ctx) => {\n if (new Set(d.transports).size !== d.transports.length) {\n ctx.addIssue({ code: \"custom\", path: [\"transports\"], message: \"duplicate transport\" })\n }\n if (d.counters.filter((c) => c.primary).length > 1) {\n ctx.addIssue({ code: \"custom\", path: [\"counters\"], message: \"at most one primary counter\" })\n }\n if (new Set(d.counters.map((c) => c.name)).size !== d.counters.length) {\n ctx.addIssue({ code: \"custom\", path: [\"counters\"], message: \"duplicate counter\" })\n }\n })\n\nexport type RecipeSource = RecipeType[\"sources\"][number]\n\n/** A raw body a connector fetched. The engine stores it, whatever its status. */\nexport interface FetchedRaw {\n url: string\n /** File extension without the dot, e.g. `json`, `html`. */\n ext: string\n bytes: Uint8Array\n httpStatus?: number\n /** `Content-Type` of the response, kept with the raw so a replay decodes it the same way. */\n contentType?: string\n /** Set when the page is a verification or challenge page. */\n challenge?: boolean\n}\n\nexport interface FetchResult {\n raws: FetchedRaw[]\n /** Next page, linked article, author profile... queued after this task. */\n tasks?: CollectTask[]\n}\n\nexport interface FetchContext {\n secrets: SecretsPort\n signal?: AbortSignal\n /** Current time from the collector's clock, ISO. */\n now: string\n}\n\nexport interface ParseInput {\n connector: string\n task: z.infer<typeof CollectTask>\n raw: {\n /** Store ref of the stored body. */\n ref: string\n url: string\n ext: string\n bytes: Uint8Array\n httpStatus?: number\n /** `Content-Type` the body was fetched with, when the connector recorded it. */\n contentType?: string\n fetchedAt: string\n transport: TransportName\n }\n}\n\ntype Fill<T, K extends string> = Omit<T, K> & Partial<Record<K, string>>\n\n/** An item as a connector returns it: the engine fills what it can compute. */\nexport type ParsedItem = Omit<z.input<typeof CollectItem>, \"id\" | \"firstSeenAt\"> & {\n /** Defaults to `source:` plus a hash of the canonical URL. */\n id?: string\n firstSeenAt?: string\n}\nexport type ParsedObservation = Fill<z.input<typeof ObservationBase>, \"measuredAt\">\nexport type ParsedPickup = Fill<z.input<typeof PickupBase>, \"firstSeenAt\" | \"measuredAt\">\n\nexport interface ParseResult {\n items?: ParsedItem[]\n observations?: ParsedObservation[]\n actors?: Array<z.input<typeof Actor>>\n pickups?: ParsedPickup[]\n}\n\nexport type ConnectorDeclarationInput = z.input<typeof ConnectorDeclaration>\n\n/** Arrays may be readonly, so a `Connector` can be spread into a new definition. */\ntype ReadonlyArrays<T> = { [K in keyof T]: T[K] extends Array<infer U> | undefined ? readonly U[] | Extract<T[K], undefined> : T[K] }\n\nexport interface ConnectorDefinition extends ReadonlyArrays<ConnectorDeclarationInput> {\n /** Validates `ext` of every item this connector returns. */\n ext?: z.ZodType\n /** Deterministic: the same recipe gives the same tasks, with the same ids. No I/O. */\n plan(recipe: RecipeType, sources: RecipeSource[]): CollectTask[]\n /** The only phase that touches the network. */\n fetch(task: z.infer<typeof CollectTask>, transport: FetchTransport, context: FetchContext): Promise<FetchResult>\n /** Pure: a stored raw in, records out. Replayable without network. */\n parse(input: ParseInput): ParseResult | Promise<ParseResult>\n}\n\nexport interface Connector extends Omit<ConnectorDefinition, keyof ConnectorDeclarationInput> {\n readonly id: string\n readonly version: string\n readonly transports: readonly TransportName[]\n readonly access: AccessDeclaration\n readonly capabilities: readonly Capability[]\n readonly counters: ReadonlyArray<z.infer<typeof CounterDeclaration>>\n readonly pace: Pace\n readonly sessionCheck?: SessionCheck\n}\n\n/** Validate the declaration of a connector and return it with its defaults filled. */\nexport function defineConnector(definition: ConnectorDefinition): Connector {\n const { ext, plan, fetch, parse, ...declaration } = definition\n const parsed = ConnectorDeclaration.parse(declaration)\n for (const [name, fn] of Object.entries({ plan, fetch, parse })) {\n if (typeof fn !== \"function\") throw new TypeError(`connector ${parsed.id}: ${name} must be a function`)\n }\n return Object.freeze({ ...parsed, ext, plan, fetch, parse })\n}\n\nexport interface ConnectorRegistry {\n register(connector: Connector): void\n get(id: string): Connector | undefined\n list(): Connector[]\n}\n\n/** An isolated registry (tests, embedding). */\nexport function createConnectorRegistry(initial: Connector[] = []): ConnectorRegistry {\n const map = new Map<string, Connector>()\n const registry: ConnectorRegistry = {\n register(connector) {\n if (map.has(connector.id)) throw new Error(`connector \"${connector.id}\" is already registered`)\n map.set(connector.id, connector)\n },\n get: (id) => map.get(id),\n list: () => [...map.values()],\n }\n for (const c of initial) registry.register(c)\n return registry\n}\n\nconst globalRegistry = createConnectorRegistry()\n\n/** Register a connector (shipped, external or private) in the process-wide registry. */\nexport function registerConnector(connector: Connector): Connector {\n globalRegistry.register(connector)\n return connector\n}\n\nexport function getConnector(id: string): Connector | undefined {\n return globalRegistry.get(id)\n}\n\nexport function listConnectors(): Connector[] {\n return globalRegistry.list()\n}\n"]}