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,203 +0,0 @@
1
- /**
2
- * The web system's implementation: every fn, mention and lifecycle event the contract declares, wired to the
3
- * server's parts. `createWebImpl` takes every seam (the search provider, the page source, the uploads, the renderers
4
- * and the clock), so tests run it with fakes and no network.
5
- */
6
- import { ResourceReadResult, ResourceRecord, type InputProblem, type ResourceImportArgs, type ResourceReadArgs } from '@harness/core';
7
- import { CallFailed, type FnCtx, type FnTypes, type Outcome, type SystemImpl } from '@harness/sdk';
8
- import { CRAWL_PAGES_DEFAULT, type PageTargetValue, type RenderModeValue, type WebContract } from '../shared/index.ts';
9
- import { parseWebUrl, redactUrl } from '../shared/urls.ts';
10
- import { searchPage } from './searches.ts';
11
- import { Crawler, FetchedPages, crawlFolder, crawlRoot } from './crawl.ts';
12
- import type { WebSettings } from './env.ts';
13
- import type { ContentUploads, FetchSettings, PageSource, SearchArgs, SearchProvider, WebConfig } from './index.ts';
14
- import { PageMentions } from './mentions.ts';
15
- import { WebProblem } from './problem.ts';
16
- import type { Renderers } from './renderer.ts';
17
-
18
- /** Everything the implementation is built from. */
19
- export interface WebDeps {
20
- readonly settings: WebSettings;
21
- readonly search: SearchProvider;
22
- readonly pages: PageSource;
23
- readonly uploads: ContentUploads;
24
- readonly renderers: Renderers;
25
- readonly now: () => number;
26
- }
27
-
28
- /** The implementation and the parts tests and `main` reach into. */
29
- export interface WebServer {
30
- readonly impl: SystemImpl<WebContract['defs']>;
31
- /** Pages crawls fetched, waiting for the hub to fetch them back. */
32
- readonly held: FetchedPages;
33
- }
34
-
35
- /** Tavily credits a search uses: one for a basic search, two for an advanced one. */
36
- export function searchCredits(depth: SearchArgs['depth']): number {
37
- return depth === 'advanced' ? 2 : 1;
38
- }
39
-
40
- /** The `invalid-input` problem for a URL arg that isn't a web address: the caller (often the LLM) fixes it and retries. */
41
- export function urlProblem(url: string): InputProblem {
42
- return { path: 'url', message: `"${url}" isn't an http or https URL; give one like https://example.com/page.` };
43
- }
44
-
45
- /** How a fetch behaves: the call's render mode, then the config's values, then the system's settings. */
46
- export function fetchSettings(config: WebConfig, settings: WebSettings, render: RenderModeValue | undefined): FetchSettings {
47
- return {
48
- render: render ?? config.render ?? settings.WEB_RENDER,
49
- allowPrivate: config.allowPrivate ?? settings.WEB_ALLOW_PRIVATE,
50
- maxBytes: config.maxBytes ?? settings.WEB_MAX_BYTES,
51
- timeout: config.timeout ?? settings.WEB_TIMEOUT,
52
- };
53
- }
54
-
55
- /**
56
- * What a failed page read adds to its error: nothing from the page is confirmed, and what to do instead. A refusal or a
57
- * missing page is never helped by rendering (iteration 3: the note offered render: "always" after a 403).
58
- */
59
- export const READ_FAILED_NOTE = 'The page was not read, so nothing it says is confirmed (a search snippet of it is not either). When the site refused it (401, 403, 406, 451) or has no such page (404, 410), don\'t read it again or render it: use the next result. Otherwise try the next result, or render: "always" for a page built by scripts.';
60
-
61
- /** What a page that read empty says. */
62
- export const READ_EMPTY_NOTE = 'The page read empty, so nothing it says is confirmed: it may be built by scripts (read it again with render: "always") or have no text; try the next result.';
63
-
64
- /**
65
- * Run fn code, turning a `WebProblem` into a failure of its class with its code, a failed hub call into the same
66
- * failure, and an abort of the run's own signal into a cancel. `after` is added to a failure's message (what a
67
- * failed read means and what to do instead).
68
- */
69
- async function attempt<T extends FnTypes>(ctx: Pick<FnCtx<T, WebConfig>, 'fail' | 'cancelled' | 'signal'>, work: () => Promise<Outcome<T>>, after?: string): Promise<Outcome<T>> {
70
- const said = (message: string): string => (after === undefined ? message : `${message} ${after}`);
71
- try {
72
- return await work();
73
- } catch (error) {
74
- if (error instanceof WebProblem) { return ctx.fail(error.errorClass, said(error.message), { code: error.code }); }
75
- if (error instanceof CallFailed) {
76
- if (error.error.class === 'cancelled') { return ctx.cancelled(); }
77
- return ctx.fail(error.error.class, said(error.error.message), error.error.code === undefined ? {} : { code: error.error.code });
78
- }
79
- if (ctx.signal.aborted) { return ctx.cancelled(); }
80
- throw error;
81
- }
82
- }
83
-
84
- /** Build the web implementation. */
85
- export function createWebImpl(deps: WebDeps): WebServer {
86
- const s = deps.settings;
87
- const mentions = new PageMentions(s.WEB_MENTION_LIMIT);
88
- const held = new FetchedPages(s.WEB_CRAWL_CACHE_TTL, deps.now);
89
-
90
- const impl: SystemImpl<WebContract['defs']> = {
91
- fns: {
92
- search: {
93
- run: (args, ctx) => attempt(ctx, async () => {
94
- const results = await deps.search.search(args, { key: ctx.config.tavilyKey ?? s.TAVILY_API_KEY, signal: ctx.signal });
95
- const credits = searchCredits(args.depth);
96
- ctx.budget.spend(credits * s.WEB_TAVILY_CREDIT, `Tavily search (${credits} ${credits === 1 ? 'credit' : 'credits'})`);
97
- // the results are kept as a hub resource, so they can be read again, searched and made into context
98
- const page = searchPage(args.query, results, new Date(deps.now()).toISOString());
99
- const content = await deps.uploads.upload(ctx.signal, new TextEncoder().encode(page.markdown), 'text/markdown');
100
- const importing: ResourceImportArgs = { content, name: page.name };
101
- const record = ResourceRecord.parse(await ctx.fns.importResource(importing));
102
- ctx.log.info('web.search.done', { results: results.results.length, depth: args.depth ?? 'basic', topic: args.topic ?? 'general', answer: results.answer !== undefined, uri: record.uri });
103
- return ctx.done({ ...results, uri: record.uri });
104
- }),
105
- },
106
- fetch_raw: {
107
- run: (args, ctx) => attempt(ctx, async () => {
108
- if (parseWebUrl(args.url) === undefined) { return ctx.invalid([urlProblem(args.url)]); }
109
- const started = deps.now();
110
- const page = held.take(parseWebUrl(args.url)?.href ?? args.url) ?? await deps.pages.fetch(args.url, fetchSettings(ctx.config, s, args.render), ctx.signal);
111
- const content = await deps.uploads.upload(ctx.signal, page.bytes, page.mime);
112
- ctx.log.info('web.fetch.done', {
113
- url: redactUrl(page.finalUrl), status: page.status, mime: page.mime, bytes: page.bytes.byteLength, rendered: page.rendered,
114
- took: deps.now() - started, ...(page.renderError === undefined ? {} : { renderError: page.renderError }),
115
- });
116
- return ctx.done({ content, mime: page.mime, finalUrl: page.finalUrl, status: page.status, rendered: page.rendered, title: page.title });
117
- }),
118
- },
119
- crawl: {
120
- run: (args, ctx) => attempt(ctx, async () => {
121
- const start = parseWebUrl(args.url);
122
- if (start === undefined) { return ctx.invalid([urlProblem(args.url)]); }
123
- start.hash = '';
124
- const folder = crawlFolder(start, deps.now());
125
- const maxPages = Math.min(args.maxPages ?? CRAWL_PAGES_DEFAULT, s.WEB_CRAWL_MAX_PAGES);
126
- const crawler = new Crawler({
127
- pages: deps.pages,
128
- held,
129
- importPage: async (url, into) => {
130
- const importing: ResourceImportArgs = { url, folder: into, ...(args.render === undefined ? {} : { render: args.render }) };
131
- const record = ResourceRecord.parse(await ctx.fns.importResource(importing));
132
- return { uri: record.uri, title: record.stat.name };
133
- },
134
- agent: s.WEB_ROBOTS_AGENT,
135
- maxLinks: s.WEB_CRAWL_MAX_LINKS,
136
- concurrency: s.WEB_CRAWL_CONCURRENCY,
137
- progress: (fraction, message) => { ctx.progress.set(Math.min(1, fraction), message); },
138
- signal: ctx.signal,
139
- });
140
- const report = await crawler.run({
141
- start, folder, maxPages,
142
- depth: args.depth ?? 1,
143
- sameSite: args.sameSite ?? true,
144
- include: args.include ?? [],
145
- exclude: args.exclude ?? [],
146
- fetch: fetchSettings(ctx.config, s, args.render),
147
- });
148
- const root = crawlRoot(report.pages.map((page) => page.uri), folder);
149
- const shown = report.skipped.slice(0, s.WEB_CRAWL_SKIPPED_SHOWN);
150
- ctx.log.info('web.crawl.done', { url: redactUrl(start), root, pages: report.pages.length, skipped: report.skipped.length });
151
- return ctx.done({ root, count: report.pages.length, pages: [...report.pages], skipped: shown, moreSkipped: report.skipped.length - shown.length, fetched: [...report.fetched] });
152
- }),
153
- },
154
- read: {
155
- run: (args, ctx) => attempt(ctx, async () => {
156
- const url = parseWebUrl(args.url);
157
- if (url === undefined) { return ctx.invalid([urlProblem(args.url)]); }
158
- // fetched here, so the run says every URL that went out (redirects too), and held for the hub's import to take
159
- // back through fetch_raw, as a crawl's pages are
160
- const page = await deps.pages.fetch(url.href, fetchSettings(ctx.config, s, args.render), ctx.signal);
161
- held.put(page);
162
- // the hub fns' args and results are the web endpoints' bodies and responses, so core's schemas check both; an
163
- // import's body is a union, which tool args carry as `input`
164
- const importing: ResourceImportArgs = { url: page.requestedUrl, ...(args.render === undefined ? {} : { render: args.render }) };
165
- const record = ResourceRecord.parse(await ctx.fns.importResource(importing));
166
- const reading: ResourceReadArgs = { uri: record.uri, maxChars: args.maxChars ?? s.WEB_READ_CHARS };
167
- const read = ResourceReadResult.parse(await ctx.fns.readResource(reading));
168
- const source = record.source?.from === 'web' ? record.source : undefined;
169
- const finalUrl = source?.finalUrl ?? source?.url ?? url.href;
170
- const rendered = source?.rendered ?? false;
171
- ctx.log.info('web.read.done', { url: redactUrl(finalUrl), uri: record.uri, chars: read.text.length, truncated: read.truncated, rendered });
172
- const note = read.total === 0 ? READ_EMPTY_NOTE : read.note;
173
- return ctx.done({
174
- uri: record.uri, title: record.stat.name, finalUrl, text: read.text, truncated: read.truncated, ...(read.partial === undefined ? {} : { partial: read.partial }),
175
- ...(note === undefined ? {} : { note }), rendered, fetched: [...page.fetched],
176
- });
177
- }, READ_FAILED_NOTE),
178
- },
179
- },
180
- mentions: {
181
- pages: {
182
- search: (query, ctx) => mentions.search(query, ctx),
183
- hover: (target: PageTargetValue, ctx) => mentions.hover(target, ctx),
184
- llm: (target: PageTargetValue) => mentions.llm(target),
185
- },
186
- },
187
- lifecycle: {
188
- started: (ctx) => {
189
- ctx.log.info('web.started', { search: (ctx.config.tavilyKey ?? s.TAVILY_API_KEY) !== undefined, render: ctx.config.render ?? s.WEB_RENDER });
190
- return Promise.resolve();
191
- },
192
- configured: (ctx) => {
193
- ctx.log.info('web.configured', { search: (ctx.config.tavilyKey ?? s.TAVILY_API_KEY) !== undefined, render: ctx.config.render ?? s.WEB_RENDER });
194
- return Promise.resolve();
195
- },
196
- stopping: async (ctx) => {
197
- ctx.log.info('web.stopping', { reason: ctx.reason });
198
- await deps.renderers.close();
199
- },
200
- },
201
- };
202
- return { impl, held };
203
- }
@@ -1,71 +0,0 @@
1
- /**
2
- * The web system's server. Its parts sit behind these interfaces so tests run the implementation with fakes (a fake
3
- * `fetch`, DNS, browser and search): `SearchProvider` (Tavily), `PageSource` (fetching a URL, with rendering) and
4
- * `ContentUploads` (handing fetched bytes to the hub). `createWebImpl` wires them to the contract.
5
- */
6
- import type { ResolveOptions, ResourceRegistry } from '@aeye/resources';
7
- import type { ContentRef } from '@harness/core';
8
- import type { ConfigOf, TypesOf } from '@harness/sdk';
9
- import type { RenderModeValue, SearchFoundValue, WebContract } from '../shared/index.ts';
10
-
11
- /** The web system's config. */
12
- export type WebConfig = ConfigOf<WebContract['defs']>;
13
-
14
- /** The args of `web/search`. */
15
- export type SearchArgs = TypesOf<WebContract['defs']['fns']['search']>['args'];
16
-
17
- /** Searches the web. */
18
- export interface SearchProvider {
19
- /** Results for the args, best first. Throws `WebProblem` (`no-search-key`, `search-refused`, …). */
20
- search(args: SearchArgs, options: { key: string | undefined; signal?: AbortSignal }): Promise<SearchFoundValue>;
21
- }
22
-
23
- /** How one fetch behaves: the config's values where it has them, the system's settings otherwise. */
24
- export interface FetchSettings {
25
- readonly render: RenderModeValue;
26
- readonly allowPrivate: boolean;
27
- readonly maxBytes: number;
28
- readonly timeout: number;
29
- }
30
-
31
- /** A fetched URL. */
32
- export interface FetchedPage {
33
- /** The content: as served for binary, utf-8 for text (and the rendered html for a rendered page). */
34
- readonly bytes: Uint8Array;
35
- readonly mime: string;
36
- /** The type `@aeye/resources` detected (`html`, `pdf`, …), when it found one. */
37
- readonly type: string | undefined;
38
- /** The URL asked for, normalised (`example.com` becomes `https://example.com/`). */
39
- readonly requestedUrl: string;
40
- /** Where the content came from after redirects (and the browser's navigation). */
41
- readonly finalUrl: string;
42
- readonly status: number;
43
- /** Whether the headless browser rendered it. */
44
- readonly rendered: boolean;
45
- /** Why rendering failed under `auto` (the fetched html was kept). */
46
- readonly renderError: string | undefined;
47
- /** Its title, or a label from its URL with credentials redacted. */
48
- readonly title: string;
49
- /** Every URL requested for it, redirects included, in order (credentials redacted): what the run says it fetched. */
50
- readonly fetched: readonly string[];
51
- }
52
-
53
- /** Fetches URLs. */
54
- export interface PageSource {
55
- /** Throws `WebProblem` for a bad URL, a refused address, a failed status, a timeout or a body over the limit. */
56
- fetch(url: string, settings: FetchSettings, signal?: AbortSignal): Promise<FetchedPage>;
57
- /**
58
- * What `@aeye/resources`' graph walks a site with: the registry, and the options every page is fetched with under
59
- * these settings (the guarded fetch, the renderer, the limits), calling `before` ahead of each request (a crawl
60
- * checks robots.txt there; throwing refuses the request), and telling `fetched` each URL requested, redirects included.
61
- */
62
- crawling(settings: FetchSettings, signal: AbortSignal, before: (url: URL) => Promise<void>, fetched: (url: string) => void): { registry: ResourceRegistry; options: ResolveOptions };
63
- }
64
-
65
- /** Hands fetched bytes to the hub for the run that fetched them. */
66
- export interface ContentUploads {
67
- /** Upload bytes for the run whose signal this is; returns their ref. */
68
- upload(signal: AbortSignal, bytes: Uint8Array, mime: string): Promise<ContentRef>;
69
- }
70
-
71
- export { web } from '../shared/index.ts';
@@ -1,104 +0,0 @@
1
- /**
2
- * Fetching a URL for the hub: `@aeye/resources`' `fetchResource` (type detection by content, header, extension and
3
- * text; charsets; the byte cap; the timeout) over the guarded fetch (every redirect hop checked, failures classed),
4
- * with script-built html rendered by the shared headless browser first under `auto`, and the page's title worked out.
5
- * The bytes go to the hub as they are (text as utf-8); the hub converts them.
6
- */
7
- import { fetchResource, htmlToCleanMarkdown, type FetchFn, type ResolveOptions, type ResourceRegistry } from '@aeye/resources';
8
- import type { RenderModeValue } from '../shared/index.ts';
9
- import { labelOf, parseWebUrl, redactUrl } from '../shared/urls.ts';
10
- import type { HostLookup } from '@harness/sdk/server';
11
- import { AddressGuard, type AddressCheck } from './guard.ts';
12
- import { guardedFetch } from './http.ts';
13
- import type { FetchedPage, FetchSettings, PageSource } from './index.ts';
14
- import { WebProblem, isAbort, isTimeout, messageOf } from './problem.ts';
15
- import type { Renderers } from './renderer.ts';
16
-
17
- /** A title for fetched content: an html page's own (`<title>`, `og:title`, the first `<h1>`), else a label from its URL. */
18
- export function titleFor(type: string | undefined, bytes: Uint8Array, url: string): string {
19
- if (type === 'html') {
20
- const title = htmlToCleanMarkdown(new TextDecoder().decode(bytes), { baseUrl: url, links: false, images: false }).title?.replace(/\s+/g, ' ').trim();
21
- if (title !== undefined && title !== '') { return title; }
22
- }
23
- return labelOf(url);
24
- }
25
-
26
- /** What the loader is built from. */
27
- export interface LoaderDeps {
28
- /** What detects types and parses pages (the default `@aeye/resources` registry). */
29
- readonly registry: ResourceRegistry;
30
- readonly fetch: FetchFn;
31
- readonly lookup: HostLookup;
32
- readonly renderers: Renderers;
33
- /** The most redirects one fetch follows. */
34
- readonly redirects: number;
35
- readonly userAgent: string;
36
- }
37
-
38
- /** `PageSource` over `fetchResource`. */
39
- export class PageLoader implements PageSource {
40
- readonly #deps: LoaderDeps;
41
-
42
- constructor(deps: LoaderDeps) {
43
- this.#deps = deps;
44
- }
45
-
46
- crawling(settings: FetchSettings, signal: AbortSignal, before: (url: URL) => Promise<void>, fetched: (url: string) => void): { registry: ResourceRegistry; options: ResolveOptions } {
47
- return { registry: this.#deps.registry, options: this.#options(settings, signal, fetched, before) };
48
- }
49
-
50
- /**
51
- * The options every fetch goes through: the guarded fetch (each hop checked, and each one requested told to
52
- * `fetched`), the renderer under its mode, the limits.
53
- */
54
- #options(settings: FetchSettings, signal: AbortSignal | undefined, fetched: (url: string) => void, before?: (url: URL) => Promise<void>): ResolveOptions {
55
- const guard = new AddressGuard(this.#deps.lookup, settings.allowPrivate);
56
- const render: RenderModeValue = settings.render;
57
- // every URL that goes out, redirects included, is said on the run (credentials redacted)
58
- const told: AddressCheck = { check: async (url, given) => { await guard.check(url, given); fetched(redactUrl(url)); }, address: (host, given) => guard.address(host, given) };
59
- const guarded = guardedFetch({ fetch: this.#deps.fetch, guard: told, redirects: this.#deps.redirects, maxBytes: settings.maxBytes });
60
- // a crawl's links may carry fragments, which are never sent
61
- const fetch: FetchFn = before === undefined ? guarded : async (input, init) => {
62
- const url = parseWebUrl(input);
63
- if (url === undefined) { return await guarded(input, init); }
64
- url.hash = '';
65
- await before(url);
66
- return await guarded(url.href, init);
67
- };
68
- return {
69
- fetch,
70
- headers: { 'user-agent': this.#deps.userAgent },
71
- maxBytes: settings.maxBytes,
72
- timeoutMs: settings.timeout,
73
- render,
74
- ...(render === 'never' ? {} : { renderer: this.#deps.renderers.renderer(guard) }),
75
- ...(signal === undefined ? {} : { signal }),
76
- };
77
- }
78
-
79
- async fetch(input: string, settings: FetchSettings, signal?: AbortSignal): Promise<FetchedPage> {
80
- const url = parseWebUrl(input);
81
- if (url === undefined) { throw new WebProblem('bad-url', `"${input}" isn't an http or https URL.`); }
82
- const fetched: string[] = [];
83
- try {
84
- const page = await fetchResource(url.href, this.#deps.registry, this.#options(settings, signal, (hop) => { fetched.push(hop); }));
85
- const bytes = page.source.input;
86
- return {
87
- bytes,
88
- mime: page.source.mimeType,
89
- type: page.source.type,
90
- requestedUrl: url.href,
91
- finalUrl: page.url,
92
- status: page.status,
93
- rendered: page.renderedBy !== undefined,
94
- renderError: page.renderError,
95
- title: titleFor(page.source.type, bytes, page.url),
96
- fetched,
97
- };
98
- } catch (error) {
99
- if (error instanceof WebProblem || signal?.aborted === true || isAbort(error)) { throw error; }
100
- if (isTimeout(error)) { throw new WebProblem('timeout', `${redactUrl(url)} took longer than ${settings.timeout} ms.`, { cause: error }); }
101
- throw new WebProblem('network', `Couldn't fetch ${redactUrl(url)}: ${messageOf(error)}`, { cause: error });
102
- }
103
- }
104
- }
@@ -1,70 +0,0 @@
1
- /**
2
- * The web system's process: Tavily search, the page loader over the real `fetch` and DNS, the shared headless Chrome
3
- * for script-built pages, built renderers in the state folder, all served to the hub. Chromium runs here, never in
4
- * the hub. `npm run dev` starts it when `TAVILY_API_KEY` is set.
5
- */
6
- import { join } from 'node:path';
7
- import { createDefaultResourceRegistry } from '@aeye/resources/default';
8
- import { loggedHost, rendererFolder, serve, systemLookup } from '@harness/sdk/server';
9
- import { web } from '../shared/index.ts';
10
- import { launchChrome } from './chrome.ts';
11
- import { webEnv } from './env.ts';
12
- import { createWebImpl } from './impl.ts';
13
- import { PageLoader } from './loader.ts';
14
- import { PageTabs } from './renderer.ts';
15
- import { TavilySearch } from './tavily.ts';
16
- import { RunUploads } from './uploads.ts';
17
-
18
- const settings = webEnv.parse();
19
- const { host, log } = loggedHost(web.name);
20
-
21
- const renderers = new PageTabs({
22
- launch: launchChrome({ executablePath: settings.WEB_CHROME }),
23
- concurrency: settings.WEB_RENDER_CONCURRENCY,
24
- timeout: settings.WEB_RENDER_TIMEOUT,
25
- idle: settings.WEB_RENDER_IDLE,
26
- userAgent: settings.WEB_USER_AGENT,
27
- });
28
- const uploads = new RunUploads(settings.HARNESS_SYSTEM_STATE);
29
-
30
- const server = createWebImpl({
31
- settings,
32
- search: new TavilySearch({
33
- url: settings.WEB_TAVILY_URL,
34
- fetch: (input, init) => fetch(input, init),
35
- timeout: settings.WEB_SEARCH_TIMEOUT,
36
- limit: settings.WEB_SEARCH_LIMIT,
37
- snippetChars: settings.WEB_SNIPPET_CHARS,
38
- }),
39
- pages: new PageLoader({
40
- registry: createDefaultResourceRegistry(),
41
- fetch: (input, init) => fetch(input, init),
42
- lookup: systemLookup,
43
- renderers,
44
- redirects: settings.WEB_REDIRECTS,
45
- userAgent: settings.WEB_USER_AGENT,
46
- }),
47
- uploads,
48
- renderers,
49
- now: () => Date.now(),
50
- });
51
-
52
- const built = performance.now();
53
- const clientFolder = await rendererFolder({ main: import.meta.url, outDir: join(settings.HARNESS_SYSTEM_STATE, 'client') });
54
- log.info('web.client.built', { folder: clientFolder, took: Math.round(performance.now() - built) });
55
-
56
- log.info('web.serving', { hub: settings.HARNESS_HUB, search: settings.TAVILY_API_KEY !== undefined, render: settings.WEB_RENDER });
57
- const running = await serve(web, server.impl, {
58
- hub: settings.HARNESS_HUB,
59
- state: settings.HARNESS_SYSTEM_STATE,
60
- client: clientFolder,
61
- files: uploads.factory,
62
- ...(settings.HARNESS_PAIRING_TOKEN === undefined ? {} : { pairingToken: settings.HARNESS_PAIRING_TOKEN }),
63
- }, host);
64
- running.onStatus((status) => { log.info('web.status', { status }); });
65
-
66
- const stop = () => {
67
- renderers.close().finally(() => running.stop()).finally(() => { process.exit(0); }).catch(() => undefined);
68
- };
69
- process.on('SIGINT', stop);
70
- process.on('SIGTERM', stop);
@@ -1,111 +0,0 @@
1
- /**
2
- * The `pages` mention: `@` offers the URL being typed and the pages the hub keeps (`hub://resources/web/…`) that match
3
- * what was typed, searched through the hub as the person mentioning (`ctx.resources.search` on a mention ctx is tied to
4
- * the hub's mention request, so the system only sees what that person may see). Nothing is remembered here: a kept
5
- * page's target carries its resource, and the hover card and the LLM's text read it from the hub. Labels and titles
6
- * never show credential-bearing query parameters.
7
- */
8
- import { HUB_RESOURCE_ROOT, type MentionHover, type ResourceHit, type ResourceUri } from '@harness/core';
9
- import type { MentionCtx, MentionOption } from '@harness/sdk';
10
- import type { PageTargetValue, PageValue } from '../shared/index.ts';
11
- import { domainOf, labelOf, parseWebUrl, redactUrl } from '../shared/urls.ts';
12
-
13
- /** Where the hub keeps the web pages it read: the root a pages search stays inside. */
14
- export const WEB_PAGES_ROOT: ResourceUri = `${HUB_RESOURCE_ROOT}web`;
15
-
16
- /** What the mention needs of its ctx: the hub's resources, read as the person, and the log. */
17
- export type PageMentionCtx = Pick<MentionCtx, 'resources' | 'log'>;
18
-
19
- /** The hover card, as the provider answers it. */
20
- export type PageHover = Omit<MentionHover, 'value'> & { value?: PageValue };
21
-
22
- /** The `Page` value of a URL, as the card's type shows it. */
23
- export function pageValue(url: string, title: string | undefined): PageValue {
24
- return { url, title: title ?? labelOf(url), domain: domainOf(url) };
25
- }
26
-
27
- /** Whether a URI is one of the kept web pages, so a target's `uri` is never read outside them (no `.` or `..` steps out). */
28
- export function isKeptPage(uri: string): uri is ResourceUri {
29
- if (!uri.startsWith(`${WEB_PAGES_ROOT}/`)) { return false; }
30
- return uri.slice(WEB_PAGES_ROOT.length + 1).split('/').every((step) => step !== '' && step !== '.' && step !== '..');
31
- }
32
-
33
- /** The hits one per page (a page's sections each match), best first, at most `limit`. */
34
- export function pagesOf(hits: readonly ResourceHit[], limit: number): ResourceHit[] {
35
- const seen = new Set<string>();
36
- const pages: ResourceHit[] = [];
37
- for (const hit of hits) {
38
- if (seen.has(hit.uri) || !isKeptPage(hit.uri)) { continue; }
39
- seen.add(hit.uri);
40
- pages.push(hit);
41
- if (pages.length === limit) { break; }
42
- }
43
- return pages;
44
- }
45
-
46
- /** The pages mention's behaviour. */
47
- export class PageMentions {
48
- readonly #limit: number;
49
-
50
- constructor(limit: number) {
51
- this.#limit = limit;
52
- }
53
-
54
- /** The URL being typed first, then kept pages matching the text. A failed search still offers the typed URL. */
55
- async search(query: string, ctx: PageMentionCtx): Promise<MentionOption<PageTargetValue>[]> {
56
- const typed = parseWebUrl(query);
57
- const options: MentionOption<PageTargetValue>[] = [];
58
- if (typed !== undefined) {
59
- options.push({ label: labelOf(typed), hint: `Read ${redactUrl(typed)}`, icon: 'globe', target: { url: typed.href } });
60
- }
61
- const text = query.trim();
62
- if (text === '' || options.length >= this.#limit) { return options; }
63
- try {
64
- const hits = await ctx.resources.search(text, { roots: [WEB_PAGES_ROOT], limit: this.#limit });
65
- for (const hit of pagesOf(hits, this.#limit - options.length)) {
66
- options.push({ label: hit.title, hint: hit.preview.slice(0, 80), icon: 'globe', target: { uri: hit.uri, title: hit.title } });
67
- }
68
- } catch (error) {
69
- ctx.log.warn('web.mentions.search_failed', { message: error instanceof Error ? error.message : String(error) });
70
- }
71
- return options;
72
- }
73
-
74
- /** A kept page's card from the hub (`undefined` once it is gone), or a typed URL's card without fetching it. */
75
- async hover(target: PageTargetValue, ctx: PageMentionCtx): Promise<PageHover | undefined> {
76
- if ('uri' in target) {
77
- if (!isKeptPage(target.uri)) { return undefined; }
78
- const stat = await ctx.resources.stat(target.uri);
79
- if (stat === undefined) { return undefined; }
80
- return {
81
- title: stat.name,
82
- subtitle: 'A web page the hub keeps',
83
- fields: stat.modifiedAt === undefined ? [] : [{ label: 'Read', value: new Date(stat.modifiedAt).toISOString().slice(0, 10) }],
84
- open: { resource: stat.uri, title: stat.name },
85
- };
86
- }
87
- const url = parseWebUrl(target.url);
88
- if (url === undefined) { return undefined; }
89
- return {
90
- title: labelOf(url),
91
- subtitle: redactUrl(url),
92
- fields: [{ label: 'Site', value: domainOf(url) }],
93
- body: 'Not read yet. Mentioning it lets the assistant read it with web/read.',
94
- open: { url: url.href, title: labelOf(url) },
95
- value: pageValue(url.href, undefined),
96
- };
97
- }
98
-
99
- /** How the LLM reaches the page: the kept resource, or `web/read` for a URL. */
100
- llm(target: PageTargetValue): Promise<string> {
101
- if ('uri' in target) {
102
- const named = target.title === undefined ? '' : ` "${target.title}"`;
103
- return Promise.resolve(isKeptPage(target.uri)
104
- ? `Web page${named} (the hub resource ${target.uri}). Read it with hub/resource_read ${JSON.stringify({ uri: target.uri })}.`
105
- : `"${target.uri}" isn't a web page the hub keeps.`);
106
- }
107
- const url = parseWebUrl(target.url);
108
- if (url === undefined) { return Promise.resolve(`"${target.url}" isn't a web address.`); }
109
- return Promise.resolve(`Web page ${url.href}. Read it with web/read ${JSON.stringify({ url: url.href })}.`);
110
- }
111
- }
@@ -1,72 +0,0 @@
1
- /**
2
- * Problems a fetch or a search can run into. Server code throws `WebProblem`; the fn layer turns it into a failure of
3
- * the problem's class with its code, so the LLM sees a message it can act on and the hub knows whether to retry.
4
- */
5
- import type { ErrorClass } from '@harness/core';
6
-
7
- /** Every problem, with the error class it fails a run with. */
8
- export const PROBLEMS = {
9
- /** Not an http(s) URL. */
10
- 'bad-url': 'caller',
11
- /** The site's robots.txt disallows the URL (a crawl leaves it out). */
12
- 'robots': 'caller',
13
- /** A private, loopback or link-local address while `allowPrivate` is off. */
14
- 'private-address': 'caller',
15
- /** The server answered with a status that isn't success (4xx). */
16
- 'http-status': 'caller',
17
- /** The server failed (5xx), or asked to come back later (429). */
18
- 'server-busy': 'retry',
19
- /** Over the byte limit. */
20
- 'too-large': 'caller',
21
- /** Too many redirects, or a redirect without a usable location. */
22
- 'redirects': 'caller',
23
- /** It took longer than the timeout. */
24
- 'timeout': 'retry',
25
- /** The network failed: DNS, a refused connection, a reset. */
26
- 'network': 'retry',
27
- /** The headless browser couldn't render the page (in `always` mode; `auto` keeps the fetched html). */
28
- 'render-failed': 'retry',
29
- /** No Tavily key is configured. */
30
- 'no-search-key': 'fatal',
31
- /** Tavily refused the key or the plan's limits. */
32
- 'search-refused': 'fatal',
33
- /** Tavily refused the request as given. */
34
- 'search-invalid': 'caller',
35
- /** Tavily is rate limiting or failing. */
36
- 'search-busy': 'retry',
37
- /** Tavily answered with something that isn't a search response. */
38
- 'search-garbled': 'retry',
39
- } as const satisfies Record<string, ErrorClass>;
40
-
41
- /** A problem's code. */
42
- export type ProblemCode = keyof typeof PROBLEMS;
43
-
44
- /** A problem with a fetch or a search. */
45
- export class WebProblem extends Error {
46
- override readonly name = 'WebProblem';
47
- readonly code: ProblemCode;
48
- constructor(code: ProblemCode, message: string, options?: { cause?: unknown }) {
49
- super(message, options);
50
- this.code = code;
51
- }
52
-
53
- /** The error class a run fails with for this problem. */
54
- get errorClass(): ErrorClass {
55
- return PROBLEMS[this.code];
56
- }
57
- }
58
-
59
- /** The message of anything thrown. */
60
- export function messageOf(error: unknown): string {
61
- return error instanceof Error ? error.message : String(error);
62
- }
63
-
64
- /** True for an abort (a cancelled run's signal), as opposed to a timeout. */
65
- export function isAbort(error: unknown): boolean {
66
- return error instanceof Error && error.name === 'AbortError';
67
- }
68
-
69
- /** True for a timeout signal's abort (`AbortSignal.timeout`). */
70
- export function isTimeout(error: unknown): boolean {
71
- return error instanceof Error && error.name === 'TimeoutError';
72
- }