fnloom 0.1.0 → 0.2.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 +31 -18
- package/package.json +2 -7
- package/packages/build/package.json +1 -1
- package/packages/cli/package.json +1 -1
- package/packages/cli/src/commands/available.ts +63 -22
- package/packages/cli/src/commands/install.ts +86 -28
- package/packages/cli/src/index.ts +3 -2
- package/packages/cli/src/local.ts +6 -0
- package/packages/cli/src/premade.ts +80 -0
- package/packages/core/package.json +1 -1
- package/packages/hub/package.json +1 -1
- package/packages/hub/src/link/process.ts +6 -1
- package/packages/sdk/package.json +1 -1
- package/packages/web/package.json +1 -1
- package/premade/claude.zip +0 -0
- package/premade/database.zip +0 -0
- package/premade/web.zip +0 -0
- package/scripts/dev-env.ts +4 -4
- package/scripts/stack.ts +42 -27
- package/scripts/start.ts +26 -16
- package/systems/api/package.json +1 -1
- package/systems/code/package.json +1 -1
- package/systems/embedder/package.json +1 -1
- package/systems/fs/package.json +1 -1
- package/systems/google-calendar/package.json +1 -1
- package/systems/input/package.json +1 -1
- package/systems/mcp/package.json +1 -1
- package/systems/ollama/package.json +1 -1
- package/systems/schedule/package.json +1 -1
- package/systems/template/package.json +1 -1
- package/systems/widgets/package.json +1 -1
- package/systems/claude/client/FleetPage.vue +0 -132
- package/systems/claude/client/NewSessionForm.vue +0 -62
- package/systems/claude/client/SessionList.vue +0 -64
- package/systems/claude/client/SessionPage.vue +0 -199
- package/systems/claude/client/TaskList.vue +0 -61
- package/systems/claude/client/fakes.ts +0 -186
- package/systems/claude/client/host.ts +0 -23
- package/systems/claude/client/index.ts +0 -15
- package/systems/claude/client/logic.ts +0 -270
- package/systems/claude/client/state.ts +0 -344
- package/systems/claude/package.json +0 -23
- package/systems/claude/server/agent-sdk.ts +0 -379
- package/systems/claude/server/driver.ts +0 -153
- package/systems/claude/server/env.ts +0 -64
- package/systems/claude/server/fake-driver.ts +0 -112
- package/systems/claude/server/fleet.ts +0 -376
- package/systems/claude/server/impl.ts +0 -568
- package/systems/claude/server/index.ts +0 -8
- package/systems/claude/server/main.ts +0 -38
- package/systems/claude/server/preview.ts +0 -76
- package/systems/claude/server/questions.ts +0 -117
- package/systems/claude/server/transcript.ts +0 -83
- package/systems/claude/shared/index.ts +0 -262
- package/systems/claude/shared/session.ts +0 -284
- package/systems/claude/shared/shapes.ts +0 -106
- package/systems/claude/system.json +0 -18
- package/systems/claude/tsconfig.json +0 -6
- package/systems/database/package.json +0 -25
- package/systems/database/server/author.ts +0 -41
- package/systems/database/server/authoring.ts +0 -322
- package/systems/database/server/catalog.ts +0 -117
- package/systems/database/server/compile.ts +0 -332
- package/systems/database/server/dialects.ts +0 -17
- package/systems/database/server/drivers/database.ts +0 -71
- package/systems/database/server/drivers/index.ts +0 -23
- package/systems/database/server/drivers/postgres.ts +0 -157
- package/systems/database/server/drivers/sqlite.ts +0 -151
- package/systems/database/server/drivers/sqlserver.ts +0 -176
- package/systems/database/server/env.ts +0 -35
- package/systems/database/server/fixture.ts +0 -169
- package/systems/database/server/impl.ts +0 -793
- package/systems/database/server/index.ts +0 -7
- package/systems/database/server/instance.ts +0 -398
- package/systems/database/server/main.ts +0 -47
- package/systems/database/server/pick.ts +0 -97
- package/systems/database/server/queries.ts +0 -390
- package/systems/database/server/results.ts +0 -39
- package/systems/database/server/schema.ts +0 -59
- package/systems/database/server/table-fns.ts +0 -237
- package/systems/database/server/types.ts +0 -253
- package/systems/database/shared/index.ts +0 -544
- package/systems/database/shared/shapes.ts +0 -413
- package/systems/database/system.json +0 -14
- package/systems/database/tsconfig.json +0 -6
- package/systems/web/client/ReadView.vue +0 -110
- package/systems/web/client/SearchView.vue +0 -215
- package/systems/web/client/StatusChip.vue +0 -38
- package/systems/web/client/fakes.ts +0 -48
- package/systems/web/client/index.ts +0 -15
- package/systems/web/client/view.ts +0 -131
- package/systems/web/package.json +0 -22
- package/systems/web/server/chrome.ts +0 -121
- package/systems/web/server/crawl.ts +0 -333
- package/systems/web/server/env.ts +0 -63
- package/systems/web/server/guard.ts +0 -60
- package/systems/web/server/http.ts +0 -89
- package/systems/web/server/impl.ts +0 -203
- package/systems/web/server/index.ts +0 -71
- package/systems/web/server/loader.ts +0 -104
- package/systems/web/server/main.ts +0 -70
- package/systems/web/server/mentions.ts +0 -111
- package/systems/web/server/problem.ts +0 -72
- package/systems/web/server/renderer.ts +0 -243
- package/systems/web/server/robots.ts +0 -75
- package/systems/web/server/searches.ts +0 -29
- package/systems/web/server/tavily.ts +0 -144
- package/systems/web/server/testing.ts +0 -165
- package/systems/web/server/uploads.ts +0 -33
- package/systems/web/shared/index.ts +0 -343
- package/systems/web/shared/urls.ts +0 -60
- package/systems/web/system.json +0 -15
- package/systems/web/tsconfig.json +0 -6
|
@@ -1,333 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Crawling a site: `@aeye/resources`' `buildResourceGraph` walks it breadth first from a start page, a few links deep,
|
|
3
|
-
* over the web system's guarded fetch (each request checked against the site's robots.txt first), and every page it
|
|
4
|
-
* reads is kept as a hub resource under one folder (`crawls/<host>-<yyyymmdd-hhmm>`). Each graph node carries the raw
|
|
5
|
-
* bytes and what the fetch found (final URL, status, rendered); the page is held in `FetchedPages` and imported through
|
|
6
|
-
* the hub, which fetches it back through `web/fetch_raw` and finds it waiting, so no page crosses the network twice.
|
|
7
|
-
*/
|
|
8
|
-
import { buildResourceGraph, type ResourceGraph, type ResourceGraphEdge, type ResourceGraphNode, type ResourceLink } from '@aeye/resources';
|
|
9
|
-
import { z } from 'zod';
|
|
10
|
-
import type { ResourceUri } from '@harness/core';
|
|
11
|
-
import { CallFailed, type Infer } from '@harness/sdk';
|
|
12
|
-
import type { CrawledPage, CrawlSkipReason, SkippedPageValue } from '../shared/index.ts';
|
|
13
|
-
import { domainOf, redactUrl } from '../shared/urls.ts';
|
|
14
|
-
import type { FetchedPage, FetchSettings, PageSource } from './index.ts';
|
|
15
|
-
import { titleFor } from './loader.ts';
|
|
16
|
-
import { WebProblem, isAbort } from './problem.ts';
|
|
17
|
-
import { RobotsRules, escapeRegExp } from './robots.ts';
|
|
18
|
-
|
|
19
|
-
/** Pages fetched by a crawl, waiting for the hub to fetch them back; each is handed out once, within its time. */
|
|
20
|
-
export class FetchedPages {
|
|
21
|
-
readonly #pages = new Map<string, { page: FetchedPage; until: number }>();
|
|
22
|
-
readonly #ttl: number;
|
|
23
|
-
readonly #now: () => number;
|
|
24
|
-
|
|
25
|
-
constructor(ttl: number, now: () => number) {
|
|
26
|
-
this.#ttl = ttl;
|
|
27
|
-
this.#now = now;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
/** Hold a page under the URL it was asked by and the one it ended at. */
|
|
31
|
-
put(page: FetchedPage): void {
|
|
32
|
-
this.#sweep();
|
|
33
|
-
const until = this.#now() + this.#ttl;
|
|
34
|
-
for (const url of new Set([page.requestedUrl, page.finalUrl])) { this.#pages.set(url, { page, until }); }
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/** The page held for a URL, removed so a later fetch of it goes to the network. */
|
|
38
|
-
take(url: string): FetchedPage | undefined {
|
|
39
|
-
this.#sweep();
|
|
40
|
-
const held = this.#pages.get(url);
|
|
41
|
-
if (held === undefined) { return undefined; }
|
|
42
|
-
for (const key of new Set([held.page.requestedUrl, held.page.finalUrl])) { this.#pages.delete(key); }
|
|
43
|
-
return held.page;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/** How many URLs are held. */
|
|
47
|
-
get size(): number {
|
|
48
|
-
return this.#pages.size;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
#sweep(): void {
|
|
52
|
-
const now = this.#now();
|
|
53
|
-
for (const [url, held] of this.#pages) { if (held.until <= now) { this.#pages.delete(url); } }
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/** What one crawl does. */
|
|
58
|
-
export interface CrawlPlan {
|
|
59
|
-
readonly start: URL;
|
|
60
|
-
/** Link levels to follow: 0 is the start page only. */
|
|
61
|
-
readonly depth: number;
|
|
62
|
-
readonly sameSite: boolean;
|
|
63
|
-
readonly maxPages: number;
|
|
64
|
-
readonly include: readonly string[];
|
|
65
|
-
readonly exclude: readonly string[];
|
|
66
|
-
readonly fetch: FetchSettings;
|
|
67
|
-
/** The folder the pages are kept under. */
|
|
68
|
-
readonly folder: string;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/** A page the crawl kept (the result's `CrawledPage`, its uri typed). */
|
|
72
|
-
export type CrawlKept = Omit<Infer<typeof CrawledPage>, 'uri'> & { readonly uri: ResourceUri };
|
|
73
|
-
|
|
74
|
-
/** A page the crawl left out (the result's `SkippedPage`). */
|
|
75
|
-
export type CrawlSkip = SkippedPageValue;
|
|
76
|
-
|
|
77
|
-
/** What a crawl found. */
|
|
78
|
-
export interface CrawlReport {
|
|
79
|
-
readonly pages: readonly CrawlKept[];
|
|
80
|
-
readonly skipped: readonly CrawlSkip[];
|
|
81
|
-
/** Every URL the crawl requested, robots.txt and redirects included, in order (credentials redacted). */
|
|
82
|
-
readonly fetched: readonly string[];
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/** Keeps a fetched page as a hub resource; throws to leave it out (a `CallFailed`, say). */
|
|
86
|
-
export type PageImporter = (url: string, folder: string) => Promise<{ uri: ResourceUri; title: string }>;
|
|
87
|
-
|
|
88
|
-
/** What a crawler is built from. */
|
|
89
|
-
export interface CrawlerDeps {
|
|
90
|
-
readonly pages: PageSource;
|
|
91
|
-
readonly held: FetchedPages;
|
|
92
|
-
readonly importPage: PageImporter;
|
|
93
|
-
/** The robots.txt agent token. */
|
|
94
|
-
readonly agent: string;
|
|
95
|
-
/** The most links one crawl looks at. */
|
|
96
|
-
readonly maxLinks: number;
|
|
97
|
-
/** How many pages load at once. */
|
|
98
|
-
readonly concurrency: number;
|
|
99
|
-
/** Called after each page with the share of `maxPages` done. */
|
|
100
|
-
readonly progress: (fraction: number, message: string) => void;
|
|
101
|
-
readonly signal: AbortSignal;
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
/** Files a crawl doesn't treat as pages, by extension. */
|
|
105
|
-
const NOT_PAGES = new Set(['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'avif', 'ico', 'bmp', 'css', 'js', 'mjs', 'map', 'json', 'xml', 'rss', 'atom',
|
|
106
|
-
'zip', 'gz', 'tgz', 'tar', 'rar', '7z', 'exe', 'dmg', 'msi', 'mp3', 'mp4', 'm4a', 'wav', 'ogg', 'webm', 'mov', 'avi', 'woff', 'woff2', 'ttf', 'otf', 'eot']);
|
|
107
|
-
|
|
108
|
-
/** The folder a crawl of `start` at `at` keeps its pages under: `crawls/<host>-<yyyymmdd-hhmm>` (UTC). */
|
|
109
|
-
export function crawlFolder(start: URL, at: number): string {
|
|
110
|
-
const time = new Date(at).toISOString();
|
|
111
|
-
const stamp = `${time.slice(0, 4)}${time.slice(5, 7)}${time.slice(8, 10)}-${time.slice(11, 13)}${time.slice(14, 16)}`;
|
|
112
|
-
return `crawls/${start.host.toLowerCase().replace(/[^a-z0-9.-]/g, '-')}-${stamp}`;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
/**
|
|
116
|
-
* The resource folder the pages are under: the part of their URIs up to the crawl's folder, else the longest folder
|
|
117
|
-
* they share. Empty when no page was kept.
|
|
118
|
-
*/
|
|
119
|
-
export function crawlRoot(uris: readonly string[], folder: string): string {
|
|
120
|
-
const first = uris[0];
|
|
121
|
-
if (first === undefined) { return ''; }
|
|
122
|
-
const at = first.indexOf(`/${folder}/`);
|
|
123
|
-
if (at >= 0) { return first.slice(0, at + folder.length + 1); }
|
|
124
|
-
let shared = first.slice(0, first.lastIndexOf('/'));
|
|
125
|
-
for (const uri of uris) {
|
|
126
|
-
while (shared !== '' && !uri.startsWith(`${shared}/`)) { shared = shared.slice(0, Math.max(0, shared.lastIndexOf('/'))); }
|
|
127
|
-
}
|
|
128
|
-
return shared;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
/**
|
|
132
|
-
* A glob over a link: one with `://` matches the whole URL, one with a `/` the path (and query), one without the
|
|
133
|
-
* path's last segment. `**` matches anything, `*` anything but `/`, `?` one character but `/`.
|
|
134
|
-
*/
|
|
135
|
-
export function globMatches(glob: string, url: URL): boolean {
|
|
136
|
-
const subject = glob.includes('://') ? url.href : glob.includes('/') ? `${url.pathname}${url.search}` : (url.pathname.split('/').at(-1) ?? '');
|
|
137
|
-
const pattern = glob.split(/(\*\*|\*|\?)/).map((part) => (part === '**' ? '.*' : part === '*' ? '[^/]*' : part === '?' ? '[^/]' : escapeRegExp(part))).join('');
|
|
138
|
-
return new RegExp(`^${pattern}$`).test(subject);
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
/** The tag and `rel` words `@aeye/resources` records on each html link. */
|
|
142
|
-
const LinkFacts = z.object({ tag: z.string(), rel: z.array(z.string()).optional() });
|
|
143
|
-
|
|
144
|
-
/** The tag and `rel` words of a link the graph found (`@aeye/resources` puts them in its metadata). */
|
|
145
|
-
function linkFacts(link: ResourceLink): z.infer<typeof LinkFacts> | undefined {
|
|
146
|
-
const facts = LinkFacts.safeParse(link.metadata);
|
|
147
|
-
return facts.success ? facts.data : undefined;
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
/** A link as an absolute http(s) URL without its fragment, against the page it is on; `undefined` for any other link. */
|
|
151
|
-
function webUrlOf(link: ResourceLink, from: string): URL | undefined {
|
|
152
|
-
const value = link.value.trim();
|
|
153
|
-
if (value === '' || !URL.canParse(value, from)) { return undefined; }
|
|
154
|
-
const url = new URL(value, from);
|
|
155
|
-
if (url.protocol !== 'http:' && url.protocol !== 'https:') { return undefined; }
|
|
156
|
-
url.hash = '';
|
|
157
|
-
return url;
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
/** A URL without its fragment (a link's `#part` names a place in the page, not another page). */
|
|
161
|
-
function withoutFragment(url: string): string {
|
|
162
|
-
if (!URL.canParse(url)) { return url; }
|
|
163
|
-
const parsed = new URL(url);
|
|
164
|
-
parsed.hash = '';
|
|
165
|
-
return parsed.href;
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
/** The words a robots refusal carries, so an edge's error says it was robots. */
|
|
169
|
-
const ROBOTS_REFUSAL = 'is disallowed by the site\'s robots.txt';
|
|
170
|
-
|
|
171
|
-
/** Records a page the crawl left out, once per URL. */
|
|
172
|
-
type Skip = (url: URL | string, reason: CrawlSkipReason, detail?: string) => void;
|
|
173
|
-
|
|
174
|
-
/** A crawl's walk. One instance per crawl. */
|
|
175
|
-
export class Crawler {
|
|
176
|
-
readonly #deps: CrawlerDeps;
|
|
177
|
-
readonly #robots = new Map<string, Promise<RobotsRules>>();
|
|
178
|
-
/** Every URL this crawl requested, in order (credentials redacted). */
|
|
179
|
-
readonly #fetched: string[] = [];
|
|
180
|
-
|
|
181
|
-
constructor(deps: CrawlerDeps) {
|
|
182
|
-
this.#deps = deps;
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
/** Walk the site as the plan says. Throws only when the run is cancelled; a page that fails is left out. */
|
|
186
|
-
async run(plan: CrawlPlan): Promise<CrawlReport> {
|
|
187
|
-
const site = domainOf(plan.start);
|
|
188
|
-
const skipped = new Map<string, CrawlSkip>();
|
|
189
|
-
const seen = new Set<string>([plan.start.href]);
|
|
190
|
-
const skip: Skip = (url, reason, detail) => {
|
|
191
|
-
const key = typeof url === 'string' ? url : url.href;
|
|
192
|
-
if (!skipped.has(key)) { skipped.set(key, { url: redactUrl(url), reason, ...(detail === undefined ? {} : { detail }) }); }
|
|
193
|
-
};
|
|
194
|
-
// every page the graph reads is held for the hub and imported at once, while the walk goes on
|
|
195
|
-
const imports: Array<Promise<{ depth: number; kept: CrawlKept } | undefined>> = [];
|
|
196
|
-
const keptUrls = new Set<string>();
|
|
197
|
-
let kept = 0;
|
|
198
|
-
const { registry, options } = this.#deps.pages.crawling(plan.fetch, this.#deps.signal, (url) => this.#check(url, plan.fetch), (url) => { this.#fetched.push(url); });
|
|
199
|
-
|
|
200
|
-
let graph: ResourceGraph;
|
|
201
|
-
try {
|
|
202
|
-
graph = await buildResourceGraph(registry, plan.start.href, {
|
|
203
|
-
...options,
|
|
204
|
-
maxDepth: plan.depth,
|
|
205
|
-
maxResources: plan.maxPages,
|
|
206
|
-
concurrency: this.#deps.concurrency,
|
|
207
|
-
followChildren: false,
|
|
208
|
-
// the site rule is by registrable domain (subdomains count), so it is checked here, not by origin in the graph
|
|
209
|
-
followExternal: true,
|
|
210
|
-
sameOrigin: false,
|
|
211
|
-
keepBytes: true,
|
|
212
|
-
shouldFollow: (link, from) => {
|
|
213
|
-
// only an html page's anchors are pages to follow, and never a nofollow one
|
|
214
|
-
const facts = linkFacts(link);
|
|
215
|
-
if (from.type !== 'html' || facts?.tag !== 'a' || facts.rel?.includes('nofollow') === true) { return false; }
|
|
216
|
-
const url = webUrlOf(link, from.location);
|
|
217
|
-
if (url === undefined || seen.has(url.href) || seen.size >= this.#deps.maxLinks) { return false; }
|
|
218
|
-
seen.add(url.href);
|
|
219
|
-
const reason = this.#leaveOut(url, plan, site);
|
|
220
|
-
if (reason !== undefined) { skip(url, reason); }
|
|
221
|
-
return reason === undefined;
|
|
222
|
-
},
|
|
223
|
-
onNode: (node) => {
|
|
224
|
-
const page = this.#pageOf(node);
|
|
225
|
-
if (page === undefined || keptUrls.has(page.finalUrl)) { return; }
|
|
226
|
-
keptUrls.add(page.finalUrl).add(page.requestedUrl);
|
|
227
|
-
this.#deps.held.put(page);
|
|
228
|
-
imports.push(this.#import(page, plan.folder, node.depth).then((answer) => {
|
|
229
|
-
if ('problem' in answer) { skip(page.requestedUrl, 'failed', answer.problem); return undefined; }
|
|
230
|
-
kept += 1;
|
|
231
|
-
this.#deps.progress(kept / plan.maxPages, `Kept ${kept} of up to ${plan.maxPages}: ${answer.kept.title}`);
|
|
232
|
-
return { depth: node.depth, kept: answer.kept };
|
|
233
|
-
}));
|
|
234
|
-
},
|
|
235
|
-
});
|
|
236
|
-
} catch (error) {
|
|
237
|
-
// the start page itself failed, so the crawl keeps nothing
|
|
238
|
-
if (this.#deps.signal.aborted || !(error instanceof Error) || isAbort(error)) { throw error; }
|
|
239
|
-
await Promise.allSettled(imports);
|
|
240
|
-
const robots = error.message.includes(ROBOTS_REFUSAL);
|
|
241
|
-
skip(plan.start, robots ? 'robots' : 'failed', robots ? undefined : error.message);
|
|
242
|
-
return { pages: [], skipped: [...skipped.values()], fetched: [...this.#fetched] };
|
|
243
|
-
}
|
|
244
|
-
const settled = await Promise.all(imports);
|
|
245
|
-
for (const node of graph.nodes.values()) {
|
|
246
|
-
for (const edge of node.edges) { this.#edgeSkip(edge, node, skip); }
|
|
247
|
-
}
|
|
248
|
-
// in the order the walk reached them: by depth, then as the graph met them
|
|
249
|
-
const pages = settled.flatMap((entry) => (entry === undefined ? [] : [entry])).sort((a, b) => a.depth - b.depth).map((entry) => entry.kept);
|
|
250
|
-
return { pages, skipped: [...skipped.values()], fetched: [...this.#fetched] };
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
/** Why a link the graph didn't load was left out, for the limit and failures (links the crawl chose not to follow are said already). */
|
|
254
|
-
#edgeSkip(edge: ResourceGraphEdge, from: ResourceGraphNode, skip: Skip): void {
|
|
255
|
-
if (edge.loaded) { return; }
|
|
256
|
-
const url = webUrlOf(edge.link, from.location);
|
|
257
|
-
if (url === undefined) { return; }
|
|
258
|
-
if (edge.reason === 'max-resources') { skip(url, 'limit'); return; }
|
|
259
|
-
if (edge.reason === 'error') {
|
|
260
|
-
const robots = edge.error?.includes(ROBOTS_REFUSAL) === true;
|
|
261
|
-
skip(url, robots ? 'robots' : 'failed', robots ? undefined : edge.error);
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
#leaveOut(link: URL, plan: CrawlPlan, site: string): CrawlSkipReason | undefined {
|
|
266
|
-
if (plan.sameSite && domainOf(link) !== site) { return 'other-site'; }
|
|
267
|
-
const extension = /\.([a-z0-9]+)$/i.exec(link.pathname)?.[1]?.toLowerCase();
|
|
268
|
-
if (extension !== undefined && NOT_PAGES.has(extension)) { return 'not-a-page'; }
|
|
269
|
-
if (plan.exclude.some((glob) => globMatches(glob, link))) { return 'excluded'; }
|
|
270
|
-
if (plan.include.length > 0 && !plan.include.some((glob) => globMatches(glob, link))) { return 'not-included'; }
|
|
271
|
-
return undefined;
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
/** A graph node as a fetched page, from the bytes and fetch facts it carries; `undefined` for a node that wasn't fetched. */
|
|
275
|
-
#pageOf(node: ResourceGraphNode): FetchedPage | undefined {
|
|
276
|
-
const fetched = node.fetch;
|
|
277
|
-
const bytes = node.bytes;
|
|
278
|
-
if (fetched === undefined || bytes === undefined) { return undefined; }
|
|
279
|
-
return {
|
|
280
|
-
bytes,
|
|
281
|
-
mime: node.resource.mimeType ?? 'application/octet-stream',
|
|
282
|
-
type: node.type,
|
|
283
|
-
requestedUrl: withoutFragment(fetched.requestedUrl),
|
|
284
|
-
finalUrl: withoutFragment(fetched.url),
|
|
285
|
-
status: fetched.status,
|
|
286
|
-
rendered: fetched.rendered,
|
|
287
|
-
renderError: fetched.renderError,
|
|
288
|
-
title: titleFor(node.type, bytes, fetched.url),
|
|
289
|
-
// the crawl's own list has every hop (its report's `fetched`); a page knows where it began and ended
|
|
290
|
-
fetched: [...new Set([redactUrl(withoutFragment(fetched.requestedUrl)), redactUrl(withoutFragment(fetched.url))])],
|
|
291
|
-
};
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
async #import(page: FetchedPage, folder: string, depth: number): Promise<{ kept: CrawlKept } | { problem: string }> {
|
|
295
|
-
try {
|
|
296
|
-
const imported = await this.#deps.importPage(page.requestedUrl, folder);
|
|
297
|
-
return { kept: { url: redactUrl(page.finalUrl), uri: imported.uri, title: imported.title, depth } };
|
|
298
|
-
} catch (error) {
|
|
299
|
-
if (this.#deps.signal.aborted || isAbort(error) || !(error instanceof Error) || (error instanceof CallFailed && error.error.class === 'cancelled')) { throw error; }
|
|
300
|
-
return { problem: error.message };
|
|
301
|
-
} finally {
|
|
302
|
-
// the hub has fetched it back by now, or never will
|
|
303
|
-
this.#deps.held.take(page.requestedUrl);
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
/** Refuse a request robots.txt disallows (robots.txt itself is always allowed). */
|
|
308
|
-
async #check(url: URL, settings: FetchSettings): Promise<void> {
|
|
309
|
-
if (url.pathname === '/robots.txt') { return; }
|
|
310
|
-
if (!(await this.#rules(url, settings)).allows(url)) { throw new WebProblem('robots', `${redactUrl(url)} ${ROBOTS_REFUSAL}.`); }
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
/** The site's robots.txt rules, read once per origin; one that can't be read allows everything. */
|
|
314
|
-
#rules(url: URL, settings: FetchSettings): Promise<RobotsRules> {
|
|
315
|
-
const known = this.#robots.get(url.origin);
|
|
316
|
-
if (known !== undefined) { return known; }
|
|
317
|
-
const robots = `${url.origin}/robots.txt`;
|
|
318
|
-
const reading = this.#deps.pages.fetch(robots, { ...settings, render: 'never' }, this.#deps.signal).then(
|
|
319
|
-
(page) => {
|
|
320
|
-
this.#fetched.push(...page.fetched);
|
|
321
|
-
return page.mime.startsWith('text/') ? RobotsRules.parse(new TextDecoder().decode(page.bytes), this.#deps.agent) : RobotsRules.ALLOW_ALL;
|
|
322
|
-
},
|
|
323
|
-
(error: unknown) => {
|
|
324
|
-
if (this.#deps.signal.aborted || !(error instanceof WebProblem)) { throw error; }
|
|
325
|
-
// asked for, if refused or failed
|
|
326
|
-
this.#fetched.push(redactUrl(robots));
|
|
327
|
-
return RobotsRules.ALLOW_ALL;
|
|
328
|
-
},
|
|
329
|
-
);
|
|
330
|
-
this.#robots.set(url.origin, reading);
|
|
331
|
-
return reading;
|
|
332
|
-
}
|
|
333
|
-
}
|
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The web system's tunables, an `@ayepi/env` slice. The config the admin sets in the hub (`web.defs.config`) wins over
|
|
3
|
-
* these for the fields it has. Durations are milliseconds.
|
|
4
|
-
*/
|
|
5
|
-
import { env } from '@ayepi/env';
|
|
6
|
-
import { systemFields, systemState } from '@harness/sdk/server';
|
|
7
|
-
import { z } from 'zod';
|
|
8
|
-
import { READ_CHARS_MAX, RENDER_MODES, SEARCH_LIMIT_MAX } from '../shared/index.ts';
|
|
9
|
-
|
|
10
|
-
export const webEnv = env({
|
|
11
|
-
...systemFields(),
|
|
12
|
-
/** The Tavily API key, used when the system's config names none. */
|
|
13
|
-
TAVILY_API_KEY: z.string().min(1).optional(),
|
|
14
|
-
/** Tavily's API. */
|
|
15
|
-
WEB_TAVILY_URL: z.string().default('https://api.tavily.com'),
|
|
16
|
-
/** What one Tavily credit costs, in USD; a basic search uses one, an advanced one two. Reported to the run's budget. */
|
|
17
|
-
WEB_TAVILY_CREDIT: z.number().min(0).default(0.008),
|
|
18
|
-
/** How long one search may take. */
|
|
19
|
-
WEB_SEARCH_TIMEOUT: z.number().int().min(1_000).default(30_000),
|
|
20
|
-
/** Results per search when the caller asks for no number. */
|
|
21
|
-
WEB_SEARCH_LIMIT: z.number().int().min(1).max(SEARCH_LIMIT_MAX).default(5),
|
|
22
|
-
/** The longest snippet a search result keeps, in characters. */
|
|
23
|
-
WEB_SNIPPET_CHARS: z.number().int().min(80).default(600),
|
|
24
|
-
/** When fetched html runs in the headless browser first, unless the config or the call says. */
|
|
25
|
-
WEB_RENDER: z.enum(RENDER_MODES).default('auto'),
|
|
26
|
-
/** Fetch private, loopback and link-local addresses, unless the config says. */
|
|
27
|
-
WEB_ALLOW_PRIVATE: z.boolean().default(false),
|
|
28
|
-
/** The most bytes downloaded per page, unless the config says. */
|
|
29
|
-
WEB_MAX_BYTES: z.number().int().min(1_024).default(20 * 1024 * 1024),
|
|
30
|
-
/** How long one page fetch may take (headers and body), unless the config says. */
|
|
31
|
-
WEB_TIMEOUT: z.number().int().min(1_000).default(30_000),
|
|
32
|
-
/** The most redirects one fetch follows. */
|
|
33
|
-
WEB_REDIRECTS: z.number().int().min(0).max(30).default(10),
|
|
34
|
-
/** The User-Agent pages are fetched with. */
|
|
35
|
-
WEB_USER_AGENT: z.string().default('Mozilla/5.0 (compatible; fnloom-web/1.0; +https://github.com/ClickerMonkey/fnloom)'),
|
|
36
|
-
/** Characters `web/read` returns when the caller asks for no number. */
|
|
37
|
-
WEB_READ_CHARS: z.number().int().min(1).max(READ_CHARS_MAX).default(12_000),
|
|
38
|
-
/** Pages rendered at once; more wait their turn. */
|
|
39
|
-
WEB_RENDER_CONCURRENCY: z.number().int().min(1).max(16).default(2),
|
|
40
|
-
/** How long the browser may take to load a page's document. */
|
|
41
|
-
WEB_RENDER_TIMEOUT: z.number().int().min(1_000).default(20_000),
|
|
42
|
-
/** How long to wait for the page's network to go quiet after it loaded; the page is taken as it is then. */
|
|
43
|
-
WEB_RENDER_IDLE: z.number().int().min(0).default(5_000),
|
|
44
|
-
/** The Chrome to render with; puppeteer's own when absent. */
|
|
45
|
-
WEB_CHROME: z.string().min(1).optional(),
|
|
46
|
-
/** The most options one `@` search for pages shows. */
|
|
47
|
-
WEB_MENTION_LIMIT: z.number().int().min(1).default(10),
|
|
48
|
-
/** The most pages one crawl keeps, whatever the caller asks. */
|
|
49
|
-
WEB_CRAWL_MAX_PAGES: z.number().int().min(1).default(100),
|
|
50
|
-
/** The most links one crawl looks at (kept or left out) before it stops queueing more. */
|
|
51
|
-
WEB_CRAWL_MAX_LINKS: z.number().int().min(1).default(2_000),
|
|
52
|
-
/** How many pages a crawl loads at once. */
|
|
53
|
-
WEB_CRAWL_CONCURRENCY: z.number().int().min(1).max(16).default(4),
|
|
54
|
-
/** Left-out pages a crawl's result lists; the rest are counted. */
|
|
55
|
-
WEB_CRAWL_SKIPPED_SHOWN: z.number().int().min(0).default(30),
|
|
56
|
-
/** How long a page a crawl fetched waits for the hub to fetch it back (through `web/fetch_raw`) before it is fetched again. */
|
|
57
|
-
WEB_CRAWL_CACHE_TTL: z.number().int().min(1_000).default(120_000),
|
|
58
|
-
/** The robots.txt user-agent token crawls are matched by (groups for `*` apply too). */
|
|
59
|
-
WEB_ROBOTS_AGENT: z.string().min(1).default('harness-web'),
|
|
60
|
-
}).add(systemState('web'));
|
|
61
|
-
|
|
62
|
-
/** The web system's settings, resolved. */
|
|
63
|
-
export type WebSettings = ReturnType<typeof webEnv.parse>;
|
|
@@ -1,60 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Which addresses the web system may reach. A fetch (and every redirect, and every request a rendered page makes) is
|
|
3
|
-
* checked with the SDK's address rules (`addressVerdict`, the same rules the hub's own fetch uses), each refusal a
|
|
4
|
-
* `WebProblem`, so a page can't be used to reach the machine the system runs on or its network.
|
|
5
|
-
*/
|
|
6
|
-
import { isIP } from 'node:net';
|
|
7
|
-
import { addressVerdict, type HostLookup } from '@harness/sdk/server';
|
|
8
|
-
import { WebProblem } from './problem.ts';
|
|
9
|
-
|
|
10
|
-
/** Checks URLs before anything fetches them. */
|
|
11
|
-
export interface AddressCheck {
|
|
12
|
-
/** Throws `WebProblem` (`bad-url`, `private-address`, `network`) unless the URL may be fetched. */
|
|
13
|
-
check(url: URL, signal?: AbortSignal): Promise<void>;
|
|
14
|
-
/**
|
|
15
|
-
* The address to connect to for a host, checked as `check` does: what a connection then goes to, so a name that
|
|
16
|
-
* resolves elsewhere a moment later (DNS rebinding) can't move it. Throws `WebProblem` as `check` does.
|
|
17
|
-
*/
|
|
18
|
-
address(host: string, signal?: AbortSignal): Promise<string>;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
/** The address check for one fetch: http(s) only, and no private addresses unless `allowPrivate`. */
|
|
22
|
-
export class AddressGuard implements AddressCheck {
|
|
23
|
-
readonly #lookup: HostLookup;
|
|
24
|
-
readonly #allowPrivate: boolean;
|
|
25
|
-
|
|
26
|
-
constructor(lookup: HostLookup, allowPrivate: boolean) {
|
|
27
|
-
this.#lookup = lookup;
|
|
28
|
-
this.#allowPrivate = allowPrivate;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
async check(url: URL, signal?: AbortSignal): Promise<void> {
|
|
32
|
-
await this.#vetted(url, signal);
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
async address(host: string, signal?: AbortSignal): Promise<string> {
|
|
36
|
-
const given = host.replace(/^\[|\]$/g, '');
|
|
37
|
-
const url = URL.parse(`http://${given.includes(':') ? `[${given}]` : given}/`);
|
|
38
|
-
if (url === null) { throw new WebProblem('bad-url', `${given} isn't a host name.`); }
|
|
39
|
-
// the host as the URL reads it: a number form such as `0x7f.1` or `2130706433` is the address it means
|
|
40
|
-
const bare = url.hostname.replace(/^\[|\]$/g, '');
|
|
41
|
-
const found = await this.#vetted(url, signal);
|
|
42
|
-
if (isIP(bare) !== 0) { return bare; }
|
|
43
|
-
const address = (found ?? await this.#lookup(bare, signal))[0];
|
|
44
|
-
if (address === undefined) { throw new WebProblem('network', `Couldn't look up ${bare}.`); }
|
|
45
|
-
return address;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
/** Check a URL with the SDK's rules; the addresses its host was checked at, when it was looked up. */
|
|
49
|
-
async #vetted(url: URL, signal?: AbortSignal): Promise<readonly string[] | undefined> {
|
|
50
|
-
let found: readonly string[] | undefined;
|
|
51
|
-
const lookup: HostLookup = async (name, given) => { found = await this.#lookup(name, given); return found; };
|
|
52
|
-
const verdict = await addressVerdict(url, { lookup, allowPrivate: this.#allowPrivate }, signal);
|
|
53
|
-
if (verdict.ok) { return found; }
|
|
54
|
-
switch (verdict.refusal) {
|
|
55
|
-
case 'not-http': throw new WebProblem('bad-url', `Only http and https URLs can be fetched, not ${url.protocol.replace(/:$/, '')}.`);
|
|
56
|
-
case 'private': throw new WebProblem('private-address', `${url.hostname} is a private or local address, which this system may not fetch.`);
|
|
57
|
-
case 'unresolved': throw new WebProblem('network', `Couldn't look up ${url.hostname}.`, { cause: verdict.cause });
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
}
|
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The fetch the page loader uses: every hop of a redirect chain is checked by the address guard before it is
|
|
3
|
-
* requested, failures become `WebProblem`s with the right class (a 404 is the caller's, a 503 is worth a retry), and
|
|
4
|
-
* the body is cut off at the byte limit as it streams. `@aeye/resources`' `fetchResource` runs over it and does the
|
|
5
|
-
* rest (type detection, charsets, rendering).
|
|
6
|
-
*/
|
|
7
|
-
import type { FetchFn } from '@aeye/resources';
|
|
8
|
-
import { followRedirects } from '@harness/sdk/server';
|
|
9
|
-
import { redactUrl } from '../shared/urls.ts';
|
|
10
|
-
import type { AddressCheck } from './guard.ts';
|
|
11
|
-
import { WebProblem, isAbort, isTimeout } from './problem.ts';
|
|
12
|
-
|
|
13
|
-
/** How a guarded fetch behaves. */
|
|
14
|
-
export interface GuardedFetchOptions {
|
|
15
|
-
/** The fetch underneath (the global one in production). */
|
|
16
|
-
readonly fetch: FetchFn;
|
|
17
|
-
readonly guard: AddressCheck;
|
|
18
|
-
/** The most redirects followed. */
|
|
19
|
-
readonly redirects: number;
|
|
20
|
-
/** The most body bytes read. */
|
|
21
|
-
readonly maxBytes: number;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
/** Turns what a fetch threw into a `WebProblem` naming `url` (shown as given); aborts of the caller's own signal pass through unchanged. */
|
|
25
|
-
export function fetchProblem(error: unknown, url: string): unknown {
|
|
26
|
-
if (error instanceof WebProblem || isAbort(error)) { return error; }
|
|
27
|
-
if (isTimeout(error)) { return new WebProblem('timeout', `${url} took too long to answer.`, { cause: error }); }
|
|
28
|
-
return new WebProblem('network', `Couldn't reach ${url}.`, { cause: error });
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/** The problem for a response that isn't a success. */
|
|
32
|
-
function statusProblem(response: Response, url: string): WebProblem {
|
|
33
|
-
const said = `${url} answered ${response.status}${response.statusText === '' ? '' : ` ${response.statusText}`}.`;
|
|
34
|
-
return response.status === 429 || response.status >= 500 ? new WebProblem('server-busy', said) : new WebProblem('http-status', said);
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/** A body that errors with `too-large` once more than `maxBytes` have come through. */
|
|
38
|
-
function capped(body: ReadableStream<Uint8Array>, maxBytes: number, url: string): ReadableStream<Uint8Array> {
|
|
39
|
-
let seen = 0;
|
|
40
|
-
return body.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({
|
|
41
|
-
transform(chunk, controller) {
|
|
42
|
-
seen += chunk.byteLength;
|
|
43
|
-
if (seen > maxBytes) {
|
|
44
|
-
controller.error(new WebProblem('too-large', `${url} is over the ${maxBytes}-byte limit.`));
|
|
45
|
-
return;
|
|
46
|
-
}
|
|
47
|
-
controller.enqueue(chunk);
|
|
48
|
-
},
|
|
49
|
-
}));
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/** The final response, located at `url` (a response made by hand has no URL of its own) and with its body capped; `shown` names it in problems. */
|
|
53
|
-
function finalResponse(response: Response, url: string, shown: string, maxBytes: number): Response {
|
|
54
|
-
const body = response.body === null ? null : capped(response.body, maxBytes, shown);
|
|
55
|
-
const located = new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
|
|
56
|
-
Object.defineProperty(located, 'url', { value: response.url === '' ? url : response.url });
|
|
57
|
-
return located;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/**
|
|
61
|
-
* A `FetchFn` that follows redirects itself (the SDK's `followRedirects`, checking each hop with the guard), refuses
|
|
62
|
-
* statuses that aren't a success and bodies whose declared or streamed size passes the limit.
|
|
63
|
-
*/
|
|
64
|
-
export function guardedFetch(options: GuardedFetchOptions): FetchFn {
|
|
65
|
-
return async (input, init) => {
|
|
66
|
-
const { response, url } = await followRedirects(input, init, {
|
|
67
|
-
fetch: options.fetch,
|
|
68
|
-
check: (hop, signal) => options.guard.check(hop, signal),
|
|
69
|
-
redirects: options.redirects,
|
|
70
|
-
problems: {
|
|
71
|
-
// messages reach the LLM and the logs, so a signed or token-bearing URL is named with its credentials redacted
|
|
72
|
-
noLocation: (at) => new WebProblem('redirects', `${redactUrl(at)} redirected without a usable location.`),
|
|
73
|
-
tooMany: (start, limit) => new WebProblem('redirects', `${redactUrl(start)} redirected more than ${limit} times.`),
|
|
74
|
-
failed: (error, at) => fetchProblem(error, redactUrl(at)),
|
|
75
|
-
},
|
|
76
|
-
});
|
|
77
|
-
const shown = redactUrl(url);
|
|
78
|
-
if (!response.ok) {
|
|
79
|
-
void response.body?.cancel().catch(() => undefined);
|
|
80
|
-
throw statusProblem(response, shown);
|
|
81
|
-
}
|
|
82
|
-
const declared = Number.parseInt(response.headers.get('content-length') ?? '', 10);
|
|
83
|
-
if (!Number.isNaN(declared) && declared > options.maxBytes) {
|
|
84
|
-
void response.body?.cancel().catch(() => undefined);
|
|
85
|
-
throw new WebProblem('too-large', `${shown} is ${declared} bytes, over the ${options.maxBytes}-byte limit.`);
|
|
86
|
-
}
|
|
87
|
-
return finalResponse(response, url.href, shown, options.maxBytes);
|
|
88
|
-
};
|
|
89
|
-
}
|