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.
Files changed (113) hide show
  1. package/README.md +31 -18
  2. package/package.json +2 -7
  3. package/packages/build/package.json +1 -1
  4. package/packages/cli/package.json +1 -1
  5. package/packages/cli/src/commands/available.ts +63 -22
  6. package/packages/cli/src/commands/install.ts +86 -28
  7. package/packages/cli/src/index.ts +3 -2
  8. package/packages/cli/src/local.ts +6 -0
  9. package/packages/cli/src/premade.ts +80 -0
  10. package/packages/core/package.json +1 -1
  11. package/packages/hub/package.json +1 -1
  12. package/packages/hub/src/link/process.ts +6 -1
  13. package/packages/sdk/package.json +1 -1
  14. package/packages/web/package.json +1 -1
  15. package/premade/claude.zip +0 -0
  16. package/premade/database.zip +0 -0
  17. package/premade/web.zip +0 -0
  18. package/scripts/dev-env.ts +4 -4
  19. package/scripts/stack.ts +42 -27
  20. package/scripts/start.ts +26 -16
  21. package/systems/api/package.json +1 -1
  22. package/systems/code/package.json +1 -1
  23. package/systems/embedder/package.json +1 -1
  24. package/systems/fs/package.json +1 -1
  25. package/systems/google-calendar/package.json +1 -1
  26. package/systems/input/package.json +1 -1
  27. package/systems/mcp/package.json +1 -1
  28. package/systems/ollama/package.json +1 -1
  29. package/systems/schedule/package.json +1 -1
  30. package/systems/template/package.json +1 -1
  31. package/systems/widgets/package.json +1 -1
  32. package/systems/claude/client/FleetPage.vue +0 -132
  33. package/systems/claude/client/NewSessionForm.vue +0 -62
  34. package/systems/claude/client/SessionList.vue +0 -64
  35. package/systems/claude/client/SessionPage.vue +0 -199
  36. package/systems/claude/client/TaskList.vue +0 -61
  37. package/systems/claude/client/fakes.ts +0 -186
  38. package/systems/claude/client/host.ts +0 -23
  39. package/systems/claude/client/index.ts +0 -15
  40. package/systems/claude/client/logic.ts +0 -270
  41. package/systems/claude/client/state.ts +0 -344
  42. package/systems/claude/package.json +0 -23
  43. package/systems/claude/server/agent-sdk.ts +0 -379
  44. package/systems/claude/server/driver.ts +0 -153
  45. package/systems/claude/server/env.ts +0 -64
  46. package/systems/claude/server/fake-driver.ts +0 -112
  47. package/systems/claude/server/fleet.ts +0 -376
  48. package/systems/claude/server/impl.ts +0 -568
  49. package/systems/claude/server/index.ts +0 -8
  50. package/systems/claude/server/main.ts +0 -38
  51. package/systems/claude/server/preview.ts +0 -76
  52. package/systems/claude/server/questions.ts +0 -117
  53. package/systems/claude/server/transcript.ts +0 -83
  54. package/systems/claude/shared/index.ts +0 -262
  55. package/systems/claude/shared/session.ts +0 -284
  56. package/systems/claude/shared/shapes.ts +0 -106
  57. package/systems/claude/system.json +0 -18
  58. package/systems/claude/tsconfig.json +0 -6
  59. package/systems/database/package.json +0 -25
  60. package/systems/database/server/author.ts +0 -41
  61. package/systems/database/server/authoring.ts +0 -322
  62. package/systems/database/server/catalog.ts +0 -117
  63. package/systems/database/server/compile.ts +0 -332
  64. package/systems/database/server/dialects.ts +0 -17
  65. package/systems/database/server/drivers/database.ts +0 -71
  66. package/systems/database/server/drivers/index.ts +0 -23
  67. package/systems/database/server/drivers/postgres.ts +0 -157
  68. package/systems/database/server/drivers/sqlite.ts +0 -151
  69. package/systems/database/server/drivers/sqlserver.ts +0 -176
  70. package/systems/database/server/env.ts +0 -35
  71. package/systems/database/server/fixture.ts +0 -169
  72. package/systems/database/server/impl.ts +0 -793
  73. package/systems/database/server/index.ts +0 -7
  74. package/systems/database/server/instance.ts +0 -398
  75. package/systems/database/server/main.ts +0 -47
  76. package/systems/database/server/pick.ts +0 -97
  77. package/systems/database/server/queries.ts +0 -390
  78. package/systems/database/server/results.ts +0 -39
  79. package/systems/database/server/schema.ts +0 -59
  80. package/systems/database/server/table-fns.ts +0 -237
  81. package/systems/database/server/types.ts +0 -253
  82. package/systems/database/shared/index.ts +0 -544
  83. package/systems/database/shared/shapes.ts +0 -413
  84. package/systems/database/system.json +0 -14
  85. package/systems/database/tsconfig.json +0 -6
  86. package/systems/web/client/ReadView.vue +0 -110
  87. package/systems/web/client/SearchView.vue +0 -215
  88. package/systems/web/client/StatusChip.vue +0 -38
  89. package/systems/web/client/fakes.ts +0 -48
  90. package/systems/web/client/index.ts +0 -15
  91. package/systems/web/client/view.ts +0 -131
  92. package/systems/web/package.json +0 -22
  93. package/systems/web/server/chrome.ts +0 -121
  94. package/systems/web/server/crawl.ts +0 -333
  95. package/systems/web/server/env.ts +0 -63
  96. package/systems/web/server/guard.ts +0 -60
  97. package/systems/web/server/http.ts +0 -89
  98. package/systems/web/server/impl.ts +0 -203
  99. package/systems/web/server/index.ts +0 -71
  100. package/systems/web/server/loader.ts +0 -104
  101. package/systems/web/server/main.ts +0 -70
  102. package/systems/web/server/mentions.ts +0 -111
  103. package/systems/web/server/problem.ts +0 -72
  104. package/systems/web/server/renderer.ts +0 -243
  105. package/systems/web/server/robots.ts +0 -75
  106. package/systems/web/server/searches.ts +0 -29
  107. package/systems/web/server/tavily.ts +0 -144
  108. package/systems/web/server/testing.ts +0 -165
  109. package/systems/web/server/uploads.ts +0 -33
  110. package/systems/web/shared/index.ts +0 -343
  111. package/systems/web/shared/urls.ts +0 -60
  112. package/systems/web/system.json +0 -15
  113. package/systems/web/tsconfig.json +0 -6
@@ -1,243 +0,0 @@
1
- /**
2
- * Rendering script-built pages: `PageTabs` is what `@aeye/resources`' url loader calls when a fetched html page looks
3
- * built by scripts (`looksScriptRendered`) or the mode says `always`. One headless browser is shared and launched on
4
- * the first render (and again if it crashes); each render gets its own private browser context and tab, so cookies
5
- * and storage never carry from one page to the next. At most `concurrency` pages render at once. Images, fonts and
6
- * media are never downloaded, and every request a page makes passes the address guard. Each tab's network also goes
7
- * through its own proxy (`tabProxy`), which connects only to the address the guard checked a host at: requests that
8
- * skip the page's interception (WebSocket handshakes, service workers) are held to the same rules, and a name that
9
- * resolves elsewhere after its check (DNS rebinding) can't move a connection. A page is taken once its network goes
10
- * quiet, or when the idle wait runs out, whichever is first.
11
- */
12
- import { AllowlistProxy } from '@harness/sdk/server';
13
- import type { PageRenderer, RenderRequest, RenderedHtml } from '@aeye/resources';
14
- import { redactUrl } from '../shared/urls.ts';
15
- import type { AddressCheck } from './guard.ts';
16
- import { WebProblem, isAbort, messageOf } from './problem.ts';
17
-
18
- /** Request types a rendered page never downloads. */
19
- export const BLOCKED_REQUESTS: ReadonlySet<string> = new Set(['image', 'font', 'media', 'texttrack', 'eventsource', 'websocket', 'manifest', 'ping', 'cspviolationreport']);
20
-
21
- /** What a tab is asked to load. */
22
- export interface TabLoad {
23
- readonly url: string;
24
- /** Headers sent with every request the page makes (the User-Agent is set apart). */
25
- readonly headers: Readonly<Record<string, string>>;
26
- readonly userAgent: string;
27
- /** How long the document may take to load. */
28
- readonly timeout: number;
29
- /** How long to wait for the network to go quiet afterwards. */
30
- readonly idle: number;
31
- /** Whether a request the page makes may go out. */
32
- allow(url: string, type: string): Promise<boolean>;
33
- }
34
-
35
- /** A page after it was loaded and its scripts ran. */
36
- export interface LoadedTab {
37
- readonly html: string;
38
- readonly url: string;
39
- }
40
-
41
- /** Where a tab's network goes: its own proxy, which connects only to checked addresses. */
42
- export interface TabNetwork {
43
- /** The proxy's URL (`http://127.0.0.1:<port>`). */
44
- readonly proxy: string;
45
- }
46
-
47
- /** One tab in its own browser context. */
48
- export interface BrowserTab {
49
- load(request: TabLoad): Promise<LoadedTab>;
50
- /** Close the tab and its context. Safe to call twice. */
51
- close(): Promise<void>;
52
- }
53
-
54
- /** A running headless browser. */
55
- export interface HeadlessBrowser {
56
- /** False once the browser has crashed or been closed. */
57
- readonly connected: boolean;
58
- /** A tab in a new private context whose every connection goes through `network`'s proxy. */
59
- open(network: TabNetwork): Promise<BrowserTab>;
60
- close(): Promise<void>;
61
- }
62
-
63
- /** Starts a headless browser. */
64
- export type LaunchBrowser = () => Promise<HeadlessBrowser>;
65
-
66
- /** How pages are rendered. */
67
- export interface RendererOptions {
68
- readonly launch: LaunchBrowser;
69
- /** Pages rendered at once. */
70
- readonly concurrency: number;
71
- readonly timeout: number;
72
- readonly idle: number;
73
- readonly userAgent: string;
74
- }
75
-
76
- /** Runs work with at most `limit` at once, in the order asked. */
77
- export class Slots {
78
- readonly #limit: number;
79
- readonly #waiting: Array<() => void> = [];
80
- #busy = 0;
81
-
82
- constructor(limit: number) {
83
- this.#limit = limit;
84
- }
85
-
86
- /** How many are running now. */
87
- get busy(): number { return this.#busy; }
88
- /** How many are waiting for a slot. */
89
- get waiting(): number { return this.#waiting.length; }
90
-
91
- async run<T>(work: () => Promise<T>, signal?: AbortSignal): Promise<T> {
92
- await this.#acquire(signal);
93
- try {
94
- return await work();
95
- } finally {
96
- this.#release();
97
- }
98
- }
99
-
100
- #acquire(signal?: AbortSignal): Promise<void> {
101
- signal?.throwIfAborted();
102
- if (this.#busy < this.#limit) {
103
- this.#busy += 1;
104
- return Promise.resolve();
105
- }
106
- return new Promise<void>((resolve, reject) => {
107
- const go = () => {
108
- signal?.removeEventListener('abort', give);
109
- this.#busy += 1;
110
- resolve();
111
- };
112
- const give = () => {
113
- const at = this.#waiting.indexOf(go);
114
- if (at >= 0) { this.#waiting.splice(at, 1); }
115
- reject(signal?.reason instanceof Error ? signal.reason : new DOMException('Aborted', 'AbortError'));
116
- };
117
- this.#waiting.push(go);
118
- signal?.addEventListener('abort', give, { once: true });
119
- });
120
- }
121
-
122
- #release(): void {
123
- this.#busy -= 1;
124
- this.#waiting.shift()?.();
125
- }
126
- }
127
-
128
- /** A guard over a page's requests: blocked types never go out, and each host is checked once per page. */
129
- export function requestFilter(guard: AddressCheck, signal?: AbortSignal): (url: string, type: string) => Promise<boolean> {
130
- const hosts = new Map<string, Promise<boolean>>();
131
- return (url, type) => {
132
- if (BLOCKED_REQUESTS.has(type)) { return Promise.resolve(false); }
133
- if (url.startsWith('data:') || url.startsWith('blob:') || url === 'about:blank') { return Promise.resolve(true); }
134
- if (!URL.canParse(url)) { return Promise.resolve(false); }
135
- const parsed = new URL(url);
136
- const key = `${parsed.protocol}//${parsed.host}`;
137
- const known = hosts.get(key);
138
- if (known !== undefined) { return known; }
139
- const verdict = guard.check(parsed, signal).then(() => true, () => false);
140
- hosts.set(key, verdict);
141
- return verdict;
142
- };
143
- }
144
-
145
- /**
146
- * The proxy a tab's network goes through: any host, connected at the one address `guard` checked it at (private ones
147
- * refused unless the guard allows them), so nothing the page does reaches an address the guard didn't pass.
148
- */
149
- export function tabProxy(guard: AddressCheck, signal?: AbortSignal): AllowlistProxy {
150
- return new AllowlistProxy({ allow: ['*'], onRefused: () => undefined, route: (target) => guard.address(target.host, signal) });
151
- }
152
-
153
- /** Hands out page renderers that share one browser, each checking its pages' requests with its own address guard. */
154
- export interface Renderers {
155
- /** A renderer (`@aeye/resources`' `PageRenderer`) whose pages' requests pass `guard`. */
156
- renderer(guard: AddressCheck): PageRenderer;
157
- /** Close the shared browser, if one was launched. */
158
- close(): Promise<void>;
159
- }
160
-
161
- /** The renderer's id in a fetched source's metadata (`renderedBy`). */
162
- export const RENDERER_ID = 'puppeteer';
163
-
164
- /** Pages rendered in tabs of one shared headless browser. */
165
- export class PageTabs implements Renderers {
166
- readonly #options: RendererOptions;
167
- readonly #slots: Slots;
168
- #browser: Promise<HeadlessBrowser> | undefined;
169
-
170
- constructor(options: RendererOptions) {
171
- this.#options = options;
172
- this.#slots = new Slots(options.concurrency);
173
- }
174
-
175
- /** Pages rendering now and waiting. */
176
- get load(): { busy: number; waiting: number } {
177
- return { busy: this.#slots.busy, waiting: this.#slots.waiting };
178
- }
179
-
180
- renderer(guard: AddressCheck): PageRenderer {
181
- return { id: RENDERER_ID, render: (request) => this.#slots.run(() => this.#render(request, guard), request.signal) };
182
- }
183
-
184
- async close(): Promise<void> {
185
- const browser = this.#browser;
186
- this.#browser = undefined;
187
- if (browser !== undefined) { await (await browser.catch(() => undefined))?.close(); }
188
- }
189
-
190
- async #render(request: RenderRequest, guard: AddressCheck): Promise<RenderedHtml> {
191
- const browser = await this.#shared();
192
- const proxy = tabProxy(guard, request.signal);
193
- let tab: BrowserTab;
194
- try {
195
- tab = await browser.open({ proxy: await proxy.start() });
196
- } catch (error) {
197
- await proxy.close();
198
- throw error;
199
- }
200
- const closeTab = () => { void tab.close(); };
201
- request.signal?.addEventListener('abort', closeTab, { once: true });
202
- try {
203
- const { 'user-agent': agent, ...headers } = Object.fromEntries(Object.entries(request.headers ?? {}).map(([name, value]) => [name.toLowerCase(), value]));
204
- const loaded = await tab.load({
205
- url: request.url,
206
- headers,
207
- userAgent: agent ?? this.#options.userAgent,
208
- timeout: this.#options.timeout,
209
- idle: this.#options.idle,
210
- allow: requestFilter(guard, request.signal),
211
- });
212
- return { html: loaded.html, url: loaded.url };
213
- } catch (error) {
214
- if (request.signal?.aborted === true || isAbort(error) || error instanceof WebProblem) { throw error; }
215
- throw new WebProblem('render-failed', `The browser couldn't render ${redactUrl(request.url)}: ${messageOf(error)}`, { cause: error });
216
- } finally {
217
- request.signal?.removeEventListener('abort', closeTab);
218
- await tab.close();
219
- await proxy.close();
220
- }
221
- }
222
-
223
- /** The shared browser, launched on first use and again after it disconnected. */
224
- async #shared(): Promise<HeadlessBrowser> {
225
- const pending = this.#browser;
226
- if (pending !== undefined) {
227
- const browser = await pending.catch(() => undefined);
228
- if (browser?.connected === true) { return browser; }
229
- // another render already started a new one while this waited
230
- if (this.#browser !== pending) { return this.#shared(); }
231
- }
232
- const launching = this.#options.launch().catch((error: unknown) => {
233
- throw new WebProblem('render-failed', `The headless browser didn't start: ${messageOf(error)}`, { cause: error });
234
- });
235
- this.#browser = launching;
236
- try {
237
- return await launching;
238
- } catch (error) {
239
- if (this.#browser === launching) { this.#browser = undefined; }
240
- throw error;
241
- }
242
- }
243
- }
@@ -1,75 +0,0 @@
1
- /**
2
- * robots.txt for crawls: the rules of the group that names the crawler's agent token (else the `*` group), matched
3
- * the way Google documents it: the longest matching `Allow` or `Disallow` path wins, `Allow` on a tie, `*` matches
4
- * anything and a trailing `$` ends the path. A site with no robots.txt (or one that can't be read) allows everything.
5
- */
6
-
7
- /** One rule of a group. */
8
- interface Rule {
9
- readonly allow: boolean;
10
- readonly path: string;
11
- readonly pattern: RegExp;
12
- }
13
-
14
- /** A site's robots.txt rules for one agent. */
15
- export class RobotsRules {
16
- /** Rules that allow everything (no robots.txt). */
17
- static readonly ALLOW_ALL = new RobotsRules([]);
18
-
19
- readonly #rules: readonly Rule[];
20
-
21
- private constructor(rules: readonly Rule[]) {
22
- this.#rules = rules;
23
- }
24
-
25
- /** Parse a robots.txt for the agent token (`harness-web`). */
26
- static parse(text: string, agent: string): RobotsRules {
27
- const token = agent.toLowerCase();
28
- const groups: Array<{ agents: string[]; rules: Rule[] }> = [];
29
- let current: { agents: string[]; rules: Rule[] } | undefined;
30
- let inAgents = false;
31
- for (const raw of text.split(/\r?\n/)) {
32
- const line = raw.replace(/#.*$/, '').trim();
33
- const colon = line.indexOf(':');
34
- if (colon < 0) { continue; }
35
- const field = line.slice(0, colon).trim().toLowerCase();
36
- const value = line.slice(colon + 1).trim();
37
- if (field === 'user-agent') {
38
- if (current === undefined || !inAgents) { current = { agents: [], rules: [] }; groups.push(current); }
39
- current.agents.push(value.toLowerCase());
40
- inAgents = true;
41
- } else if (field === 'allow' || field === 'disallow') {
42
- inAgents = false;
43
- // an empty Disallow allows everything: it adds no rule
44
- if (current !== undefined && value !== '') { current.rules.push(rule(field === 'allow', value)); }
45
- } else {
46
- inAgents = false;
47
- }
48
- }
49
- const named = groups.filter((group) => group.agents.some((name) => name !== '*' && token.startsWith(name)));
50
- const chosen = named.length > 0 ? named : groups.filter((group) => group.agents.includes('*'));
51
- return new RobotsRules(chosen.flatMap((group) => group.rules));
52
- }
53
-
54
- /** Whether a URL's path (and query) may be fetched. */
55
- allows(url: URL): boolean {
56
- const path = `${url.pathname}${url.search}`;
57
- let best: Rule | undefined;
58
- for (const candidate of this.#rules) {
59
- if (!candidate.pattern.test(path)) { continue; }
60
- if (best === undefined || candidate.path.length > best.path.length || (candidate.path.length === best.path.length && candidate.allow)) { best = candidate; }
61
- }
62
- return best?.allow ?? true;
63
- }
64
- }
65
-
66
- function rule(allow: boolean, path: string): Rule {
67
- const anchored = path.endsWith('$');
68
- const body = (anchored ? path.slice(0, -1) : path).split('*').map(escapeRegExp).join('.*');
69
- return { allow, path, pattern: new RegExp(`^${body}${anchored ? '$' : ''}`) };
70
- }
71
-
72
- /** A string as a literal in a regular expression. */
73
- export function escapeRegExp(text: string): string {
74
- return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
75
- }
@@ -1,29 +0,0 @@
1
- /**
2
- * A web search kept as a hub resource: its results as one markdown page (the query, Tavily's short answer when there
3
- * is one, then each result's title as a link, its snippet and when it was published), so a search can be read again,
4
- * searched and made into context like any page the chat read.
5
- */
6
- import type { SearchFoundValue } from '../shared/index.ts';
7
-
8
- /** The page a search is kept as: its name and markdown. */
9
- export interface SearchPage {
10
- readonly name: string;
11
- readonly markdown: string;
12
- }
13
-
14
- /** Text as one markdown line: no line breaks, and the characters that would start markup escaped. */
15
- function inline(text: string): string {
16
- return text.replace(/\s+/g, ' ').trim().replace(/([\\[\]*_`<>#])/g, '\\$1');
17
- }
18
-
19
- /** The page a search's results are kept as. `at` is when it ran (an ISO date and time). */
20
- export function searchPage(query: string, results: SearchFoundValue, at: string): SearchPage {
21
- const lines = [`# Web search: ${inline(query)}`, '', `Searched ${at}. ${results.results.length} ${results.results.length === 1 ? 'result' : 'results'}, best first.`, ''];
22
- if (results.answer !== undefined) { lines.push('## Short answer', '', inline(results.answer), ''); }
23
- results.results.forEach((hit, index) => {
24
- lines.push(`## ${index + 1}. [${inline(hit.title)}](${hit.url.replace(/[\s()]/g, (char) => encodeURIComponent(char))})`, '');
25
- if (hit.published !== undefined) { lines.push(`Published ${inline(hit.published)}.`, ''); }
26
- lines.push(inline(hit.snippet), '');
27
- });
28
- return { name: `Web search: ${query.replace(/\s+/g, ' ').trim().slice(0, 80)}`, markdown: `${lines.join('\n').trimEnd()}\n` };
29
- }
@@ -1,144 +0,0 @@
1
- /**
2
- * Web search through Tavily's REST API (`POST /search`). The request and response are zod schemas here, so the
3
- * shaping and its tests share one source of truth; a response that doesn't fit is a `search-garbled` problem, never a
4
- * half-read result. Snippets are cleaned (whitespace, markdown leftovers) and cut at a word near the limit.
5
- */
6
- import { clipMarked } from '@harness/core';
7
- import { z } from 'zod';
8
- import { SEARCH_DEPTHS, SEARCH_TOPICS, type SearchFoundValue } from '../shared/index.ts';
9
- import type { SearchArgs, SearchProvider } from './index.ts';
10
- import { WebProblem, isAbort, isTimeout } from './problem.ts';
11
-
12
- /** `POST /search` request. */
13
- export const TavilyRequest = z.object({
14
- query: z.string().min(1),
15
- search_depth: z.enum(SEARCH_DEPTHS),
16
- topic: z.enum(SEARCH_TOPICS),
17
- max_results: z.number().int().min(1),
18
- include_answer: z.boolean(),
19
- days: z.number().int().min(1).optional(),
20
- include_domains: z.array(z.string()).optional(),
21
- exclude_domains: z.array(z.string()).optional(),
22
- });
23
- export type TavilyRequest = z.infer<typeof TavilyRequest>;
24
-
25
- /** One result of `POST /search`. */
26
- export const TavilyResult = z.object({
27
- title: z.string().nullish(),
28
- url: z.string(),
29
- content: z.string().nullish(),
30
- score: z.number().nullish(),
31
- published_date: z.string().nullish(),
32
- });
33
- export type TavilyResult = z.infer<typeof TavilyResult>;
34
-
35
- /** `POST /search` response: the parts the system reads. */
36
- export const TavilyResponse = z.object({
37
- query: z.string().optional(),
38
- answer: z.string().nullish(),
39
- results: z.array(TavilyResult),
40
- response_time: z.union([z.number(), z.string()]).optional(),
41
- });
42
- export type TavilyResponse = z.infer<typeof TavilyResponse>;
43
-
44
- /** An error body: Tavily answers `{ detail: { error } }` or `{ detail }`. */
45
- const TavilyError = z.object({ detail: z.union([z.string(), z.object({ error: z.string() })]) });
46
-
47
- /** How the Tavily client is set up. */
48
- export interface TavilyOptions {
49
- /** `https://api.tavily.com`. */
50
- readonly url: string;
51
- readonly fetch: typeof fetch;
52
- readonly timeout: number;
53
- /** Results when the caller asks for no number. */
54
- readonly limit: number;
55
- /** The longest snippet kept. */
56
- readonly snippetChars: number;
57
- }
58
-
59
- /** How a cut snippet says where the rest is. */
60
- export const SNIPPET_REST = 'read the page with web/read';
61
-
62
- /**
63
- * A snippet: whitespace collapsed, markdown heading and emphasis marks dropped, cut at a word boundary near `max`,
64
- * ending with how much was cut and where the rest is (`clipMarked`).
65
- */
66
- export function cleanSnippet(text: string, max: number): string {
67
- const flat = text.replace(/[#*_`>|]+/g, ' ').replace(/\s+/g, ' ').trim();
68
- return clipMarked(flat, max, { atWord: true, rest: SNIPPET_REST });
69
- }
70
-
71
- /** The request for some search args. */
72
- export function tavilyRequest(args: SearchArgs, defaultLimit: number): TavilyRequest {
73
- return TavilyRequest.parse({
74
- query: args.query,
75
- search_depth: args.depth ?? 'basic',
76
- topic: args.topic ?? 'general',
77
- max_results: args.limit ?? defaultLimit,
78
- include_answer: true,
79
- ...(args.days === undefined ? {} : { days: args.days }),
80
- ...(args.include === undefined || args.include.length === 0 ? {} : { include_domains: args.include }),
81
- ...(args.exclude === undefined || args.exclude.length === 0 ? {} : { exclude_domains: args.exclude }),
82
- });
83
- }
84
-
85
- /** A response as search results: best first, untitled results named by their URL, snippets cleaned. */
86
- export function shapeResults(response: TavilyResponse, snippetChars: number, limit: number): SearchFoundValue {
87
- const results = response.results
88
- .filter((result) => URL.canParse(result.url))
89
- .map((result) => ({
90
- title: (result.title ?? '').trim() || result.url,
91
- url: result.url,
92
- snippet: cleanSnippet(result.content ?? '', snippetChars),
93
- score: Math.max(0, result.score ?? 0),
94
- ...(result.published_date === null || result.published_date === undefined || result.published_date === '' ? {} : { published: result.published_date }),
95
- }))
96
- .sort((a, b) => b.score - a.score)
97
- .slice(0, limit);
98
- const answer = response.answer?.trim();
99
- return { ...(answer === undefined || answer === '' ? {} : { answer }), results };
100
- }
101
-
102
- /** The problem for a refused request. */
103
- async function refusal(response: Response): Promise<WebProblem> {
104
- const parsed = TavilyError.safeParse(await response.json().catch(() => undefined));
105
- const detail = parsed.success ? (typeof parsed.data.detail === 'string' ? parsed.data.detail : parsed.data.detail.error) : response.statusText;
106
- const said = `Tavily answered ${response.status}${detail === '' ? '' : `: ${detail}`}`;
107
- if (response.status === 401 || response.status === 403 || response.status === 432 || response.status === 433) { return new WebProblem('search-refused', said); }
108
- if (response.status === 429 || response.status >= 500) { return new WebProblem('search-busy', said); }
109
- return new WebProblem('search-invalid', said);
110
- }
111
-
112
- /** `SearchProvider` over Tavily. */
113
- export class TavilySearch implements SearchProvider {
114
- readonly #options: TavilyOptions;
115
-
116
- constructor(options: TavilyOptions) {
117
- this.#options = options;
118
- }
119
-
120
- async search(args: SearchArgs, options: { key: string | undefined; signal?: AbortSignal }): Promise<SearchFoundValue> {
121
- if (options.key === undefined) {
122
- throw new WebProblem('no-search-key', 'No Tavily API key is set: an admin sets it in the web system\'s config, or the system\'s TAVILY_API_KEY.');
123
- }
124
- const body = tavilyRequest(args, this.#options.limit);
125
- const timeout = AbortSignal.timeout(this.#options.timeout);
126
- let response: Response;
127
- try {
128
- response = await this.#options.fetch(new URL('/search', this.#options.url), {
129
- method: 'POST',
130
- headers: { 'content-type': 'application/json', authorization: `Bearer ${options.key}` },
131
- body: JSON.stringify(body),
132
- signal: options.signal === undefined ? timeout : AbortSignal.any([options.signal, timeout]),
133
- });
134
- } catch (error) {
135
- if (isAbort(error) && options.signal?.aborted === true) { throw error; }
136
- if (isTimeout(error)) { throw new WebProblem('search-busy', 'Tavily took too long to answer.', { cause: error }); }
137
- throw new WebProblem('search-busy', 'Couldn\'t reach Tavily.', { cause: error });
138
- }
139
- if (!response.ok) { throw await refusal(response); }
140
- const parsed = TavilyResponse.safeParse(await response.json().catch(() => undefined));
141
- if (!parsed.success) { throw new WebProblem('search-garbled', `Tavily's answer wasn't a search response: ${parsed.error.issues[0]?.message ?? 'unreadable'}.`); }
142
- return shapeResults(parsed.data, this.#options.snippetChars, body.max_results);
143
- }
144
- }
@@ -1,165 +0,0 @@
1
- /**
2
- * Test seams for the web server: a scripted `fetch` (answers by URL, records every request), DNS from a table, a fake
3
- * headless browser, and fakes of the search provider and the page source, so the implementation runs with no
4
- * network. Used by the `*.test.ts` files only.
5
- */
6
- import type { FetchFn } from '@aeye/resources';
7
- import type { HostLookup } from '@harness/sdk/server';
8
- import type { SearchFoundValue } from '../shared/index.ts';
9
- import type { FetchedPage, FetchSettings, PageSource, SearchArgs, SearchProvider } from './index.ts';
10
- import type { BrowserTab, HeadlessBrowser, LaunchBrowser, LoadedTab, TabLoad, TabNetwork } from './renderer.ts';
11
-
12
- /** One request the scripted fetch saw. */
13
- export interface SeenRequest {
14
- readonly url: string;
15
- readonly init: RequestInit;
16
- }
17
-
18
- /** An answer to a request: a response (used once), a maker of responses (for URLs asked more than once), or an error to throw. */
19
- export type Answer = Response | Error | ((init: RequestInit) => Response | Promise<Response>);
20
-
21
- /** A `fetch` that answers from a table of URLs (unknown URLs get a 404), recording each request. */
22
- export function scriptedFetch(table: Readonly<Record<string, Answer>>): FetchFn & { readonly seen: SeenRequest[] } {
23
- const seen: SeenRequest[] = [];
24
- const fetchFn = async (input: string, init: RequestInit): Promise<Response> => {
25
- seen.push({ url: input, init });
26
- const answer = table[input];
27
- if (answer === undefined) { return new Response('not here', { status: 404, statusText: 'Not Found' }); }
28
- if (answer instanceof Error) { throw answer; }
29
- if (answer instanceof Response) {
30
- if (answer.bodyUsed) { throw new Error(`${input} was asked for twice; answer it with a function`); }
31
- return answer;
32
- }
33
- return answer(init);
34
- };
35
- return Object.assign(fetchFn, { seen });
36
- }
37
-
38
- /** An html response. */
39
- export function html(body: string, init: ResponseInit = {}): Response {
40
- return new Response(body, { status: 200, ...init, headers: { 'content-type': 'text/html; charset=utf-8', ...headersObject(init.headers) } });
41
- }
42
-
43
- /** A redirect to `location`. */
44
- export function redirect(location: string, status = 302): Response {
45
- return new Response(null, { status, headers: { location } });
46
- }
47
-
48
- function headersObject(headers: HeadersInit | undefined): Record<string, string> {
49
- return headers === undefined ? {} : Object.fromEntries(new Headers(headers).entries());
50
- }
51
-
52
- /** DNS from a table; a name not in it doesn't resolve. */
53
- export function tableLookup(table: Readonly<Record<string, readonly string[]>>): HostLookup & { readonly asked: string[] } {
54
- const asked: string[] = [];
55
- const lookup: HostLookup = (hostname) => {
56
- asked.push(hostname);
57
- const found = table[hostname];
58
- return found === undefined ? Promise.reject(new Error(`ENOTFOUND ${hostname}`)) : Promise.resolve(found);
59
- };
60
- return Object.assign(lookup, { asked });
61
- }
62
-
63
- /** Public addresses for the hosts the tests use. */
64
- export const PUBLIC_DNS = { 'example.com': ['93.184.215.14'], 'www.example.com': ['93.184.215.14'], 'app.example.com': ['93.184.215.15'], 'cdn.example.com': ['93.184.215.16'] } as const;
65
-
66
- /** What a fake tab does with a load: the html (and URL) it ends with, or an error. */
67
- export type TabScript = (request: TabLoad) => Promise<LoadedTab>;
68
-
69
- /** A fake headless browser: each tab runs `script`; it records loads, open tabs and launches. */
70
- export class FakeBrowser implements HeadlessBrowser {
71
- readonly loads: TabLoad[] = [];
72
- /** The network each tab was opened with. */
73
- readonly networks: TabNetwork[] = [];
74
- openTabs = 0;
75
- closedTabs = 0;
76
- connected = true;
77
- closed = false;
78
- readonly #script: TabScript;
79
-
80
- constructor(script: TabScript) {
81
- this.#script = script;
82
- }
83
-
84
- open(network: TabNetwork): Promise<BrowserTab> {
85
- this.networks.push(network);
86
- this.openTabs += 1;
87
- let done = false;
88
- const tab: BrowserTab = {
89
- load: (request) => { this.loads.push(request); return this.#script(request); },
90
- close: () => {
91
- if (!done) { done = true; this.openTabs -= 1; this.closedTabs += 1; }
92
- return Promise.resolve();
93
- },
94
- };
95
- return Promise.resolve(tab);
96
- }
97
-
98
- close(): Promise<void> {
99
- this.closed = true;
100
- this.connected = false;
101
- return Promise.resolve();
102
- }
103
- }
104
-
105
- /** A launcher of fake browsers, counting launches; each launch makes a new one with the same script. */
106
- export function fakeLauncher(script: TabScript): LaunchBrowser & { readonly browsers: FakeBrowser[] } {
107
- const browsers: FakeBrowser[] = [];
108
- const launch: LaunchBrowser = () => {
109
- const browser = new FakeBrowser(script);
110
- browsers.push(browser);
111
- return Promise.resolve(browser);
112
- };
113
- return Object.assign(launch, { browsers });
114
- }
115
-
116
- /** A search provider that answers with `results` and records what it was asked. */
117
- export class FakeSearch implements SearchProvider {
118
- readonly asked: Array<{ args: SearchArgs; key: string | undefined }> = [];
119
- results: SearchFoundValue | Error;
120
-
121
- constructor(results: SearchFoundValue | Error) {
122
- this.results = results;
123
- }
124
-
125
- search(args: SearchArgs, options: { key: string | undefined }): Promise<SearchFoundValue> {
126
- this.asked.push({ args, key: options.key });
127
- return this.results instanceof Error ? Promise.reject(this.results) : Promise.resolve(this.results);
128
- }
129
- }
130
-
131
- /** A page source that answers with `page` (or throws) and records what it was asked. */
132
- export class FakePages implements PageSource {
133
- readonly asked: Array<{ url: string; settings: FetchSettings }> = [];
134
- page: FetchedPage | Error;
135
-
136
- constructor(page: FetchedPage | Error) {
137
- this.page = page;
138
- }
139
-
140
- fetch(url: string, settings: FetchSettings): Promise<FetchedPage> {
141
- this.asked.push({ url, settings });
142
- return this.page instanceof Error ? Promise.reject(this.page) : Promise.resolve(this.page);
143
- }
144
-
145
- crawling(): never {
146
- throw new Error('FakePages answers fetches only; crawl over a PageLoader with a scripted fetch.');
147
- }
148
- }
149
-
150
- /** A fetched html page. */
151
- export function fetchedPage(overrides: Partial<FetchedPage> = {}): FetchedPage {
152
- return {
153
- bytes: new TextEncoder().encode('<html><head><title>Example</title></head><body><p>Hello</p></body></html>'),
154
- mime: 'text/html',
155
- type: 'html',
156
- requestedUrl: 'https://example.com/',
157
- finalUrl: 'https://example.com/',
158
- status: 200,
159
- rendered: false,
160
- renderError: undefined,
161
- title: 'Example',
162
- fetched: [overrides.requestedUrl ?? 'https://example.com/'],
163
- ...overrides,
164
- };
165
- }