@unieai/rabi-web 0.0.0-stage → 0.2.2-rc.5

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/locale/de.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Web",
4
+ "description": "Ein Dienstanbieter, der Websuche und Inhaltserfassung vereint."
5
+ }
6
+ }
package/locale/en.json ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "meta": {
3
+ "title": "web"
4
+ }
5
+ }
package/locale/es.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "web",
4
+ "description": "Un proveedor de servicios que unifica la búsqueda web y la adquisición de contenidos."
5
+ }
6
+ }
package/locale/fr.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "la toile",
4
+ "description": "Un fournisseur de services qui unifie la recherche sur le Web et l'acquisition de contenu."
5
+ }
6
+ }
package/locale/ja.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Web アクセスサービス",
4
+ "description": "Web 検索とコンテンツ取得の提供元を統一して管理します。"
5
+ }
6
+ }
package/locale/pt.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "rede",
4
+ "description": "Um provedor de serviços que unifica a pesquisa na web e a aquisição de conteúdo."
5
+ }
6
+ }
package/locale/ru.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "сеть",
4
+ "description": "Поставщик услуг, который объединяет веб-поиск и получение контента."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "网页访问服务",
4
+ "description": "统一管理网页搜索和内容获取的服务提供方。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@unieai/rabi-web",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "description": "Abstract web access capability seam (ctx.web) for the Rabi Harness — search/fetch provider registry, registration-order-independent selection, request/result vocabulary, and the WebError taxonomy",
4
+ "version": "0.2.2-rc.5",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "type": "module",
9
+ "main": "lib/index.js",
10
+ "types": "lib/types/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./lib/types/index.d.ts",
14
+ "default": "./lib/index.js"
15
+ },
16
+ "./types": {
17
+ "types": "./lib/types/types.d.ts",
18
+ "default": "./lib/types/types.js"
19
+ },
20
+ "./typert": {
21
+ "types": "./lib/typert.host.d.ts",
22
+ "default": "./lib/typert.host.js"
23
+ },
24
+ "./remote": {
25
+ "types": "./lib/typert.remote-client.d.ts",
26
+ "default": "./lib/typert.remote-client.js"
27
+ },
28
+ "./src/*": "./src/*",
29
+ "./package.json": "./package.json",
30
+ "./locale/*.json": "./locale/*.json"
31
+ },
32
+ "files": [
33
+ "locale/*.json",
34
+ "lib/index.js",
35
+ "lib/types/**/*.js",
36
+ "lib/types/**/*.d.ts",
37
+ "lib/types/**/*.d.ts.map",
38
+ "lib/**/*.js.map",
39
+ "lib/typert.host.js",
40
+ "lib/typert.host.d.ts",
41
+ "lib/typert.remote-client.js",
42
+ "lib/typert.remote-client.d.ts",
43
+ "lib/typert.remote-client.d.ts.map",
44
+ "src",
45
+ "README.md"
46
+ ],
47
+ "license": "MIT",
48
+ "peerDependencies": {
49
+ "@unieai/rabi-llm": "0.2.2-rc.5",
50
+ "@unieai/cordis": "4.1.0"
51
+ },
52
+ "dependencies": {
53
+ "@unieai/rabi-package-manifest": "0.2.2-rc.5",
54
+ "@unieai/schemastery": "3.19.0",
55
+ "@unieai/rabi-typert-protocol": "0.2.2-rc.5"
56
+ }
57
+ }
package/src/index.ts ADDED
@@ -0,0 +1,337 @@
1
+ /**
2
+ * Service Definition for the web access capability seam (`ctx.web`): registries and provider-selecting execution for search and
3
+ * fetch. Duplicate ids are rejected. At execution time, a configured provider must exist and
4
+ * be usable; without one, exactly one usable provider is required, except that a search prefers the
5
+ * usable DeepSeek provider assigned to the route of the model request it serves, so selection never
6
+ * depends on registration order.
7
+ * @module @unieai/rabi-web
8
+ */
9
+
10
+ import { Context, type Volatile } from '@unieai/cordis'
11
+ import { Remote, TypertRemoteService } from '@unieai/rabi-typert-protocol'
12
+ import z from '@unieai/schemastery'
13
+ import type {
14
+ WebFetchProvider,
15
+ WebFetchRequest,
16
+ WebFetchResult,
17
+ WebProviderInfo,
18
+ WebProviderList,
19
+ WebSearchProvider,
20
+ WebSearchRequest,
21
+ WebSearchResult,
22
+ } from './types.ts'
23
+ import { WebError } from './types.ts'
24
+
25
+ export {
26
+ WebError,
27
+ } from './types.ts'
28
+ export type {
29
+ WebFetchBody,
30
+ WebFetchProvider,
31
+ WebFetchRequest,
32
+ WebFetchResult,
33
+ WebProviderInfo,
34
+ WebProviderList,
35
+ WebSearchProvider,
36
+ WebSearchRequest,
37
+ WebSearchResult,
38
+ WebSearchSource,
39
+ } from './types.ts'
40
+
41
+ declare module '@unieai/cordis' {
42
+ interface Context {
43
+ web: WebRuntime
44
+ }
45
+ }
46
+
47
+ /** Selection inputs for execution-time provider resolution. */
48
+ interface Selection<P> {
49
+ /** The configured provider id for this capability, if any. */
50
+ readonly configuredId?: string
51
+ /** Providers registered for this capability kind. */
52
+ readonly providers: ReadonlyMap<string, P>
53
+ /** The provider that wins among the usable ones while none is configured, if it is usable. */
54
+ readonly preferredId?: string
55
+ }
56
+
57
+ /** Provider routes of the DeepSeek API-key and account models. */
58
+ const DEEPSEEK_MODEL_ROUTES: ReadonlySet<string> = new Set(['deepseek-official', 'deepseek-account'])
59
+
60
+ /**
61
+ * Search provider preferred for a model request on a DeepSeek model route while none is configured: DeepSeek
62
+ * Messages search, which DeepSeek serves without a per-search charge.
63
+ */
64
+ const DEEPSEEK_ROUTE_SEARCH_PROVIDER = 'deepseek-official'
65
+
66
+ /** Search provider preferred on every other route and outside a model request while none is configured. */
67
+ const OTHER_ROUTE_SEARCH_PROVIDER = 'deepseek-search-api'
68
+
69
+ /**
70
+ * Config for the web seam. `searchProvider` / `fetchProvider` pin which provider
71
+ * wins for each capability; both are optional (a single registered usable
72
+ * provider auto-selects). Each operation reads the current value, so a settings
73
+ * change applies to the next search or fetch without remounting the service.
74
+ * Operational overrides such as environment variables must feed these same
75
+ * fields rather than introduce a hidden priority chain.
76
+ */
77
+ export interface WebRuntimeConfig {
78
+ /**
79
+ * Explicit search provider id. Omitted = the usable DeepSeek provider assigned to the route of the model
80
+ * request, and otherwise auto-select when exactly one usable.
81
+ */
82
+ readonly searchProvider: Volatile<string | undefined>
83
+ /** Explicit fetch provider id. Omitted = auto-select when exactly one usable. */
84
+ readonly fetchProvider: Volatile<string | undefined>
85
+ }
86
+
87
+ /**
88
+ * The web access service. Registered as `ctx.web` (one instance per context)
89
+ * and exposed to Clients as the `web` Remote namespace (`listProviders`).
90
+ *
91
+ * Selection semantics (resolved at execution time, never order-dependent):
92
+ * - A configured id that is registered and `available()` → that provider.
93
+ * - A configured id not registered → `WEB_PROVIDER_CONFIGURED_MISSING`.
94
+ * - A configured id registered but unavailable →
95
+ * `WEB_PROVIDER_CONFIGURED_UNAVAILABLE`.
96
+ * - No search id configured, and the provider assigned to the route of the model request
97
+ * the search serves is usable → that provider: `deepseek-official` (Messages search) on the
98
+ * `deepseek-official` and `deepseek-account` routes, `deepseek-search-api` on every other
99
+ * route and outside a model request.
100
+ * - No id configured, exactly one registered usable provider → that provider.
101
+ * - No id configured, multiple usable providers → `WEB_PROVIDER_AMBIGUOUS`.
102
+ * - No id configured, no usable provider → `WEB_PROVIDER_UNAVAILABLE`.
103
+ */
104
+ export class WebRuntime extends TypertRemoteService {
105
+ /**
106
+ * Provider selection config. Operational env overrides feed the SAME fields:
107
+ * `$RABI_WEB_SEARCH_PROVIDER` / `$RABI_WEB_FETCH_PROVIDER` are equivalent to
108
+ * `searchProvider` / `fetchProvider` and are NOT a hidden priority chain.
109
+ */
110
+ static Config = z.object({
111
+ searchProvider: z.string().volatile(),
112
+ fetchProvider: z.string().volatile(),
113
+ })
114
+
115
+ private searchProviders = new Map<string, WebSearchProvider>()
116
+ private fetchProviders = new Map<string, WebFetchProvider>()
117
+ private readonly searchProviderEnv: string | undefined
118
+ private readonly fetchProviderEnv: string | undefined
119
+
120
+ constructor(ctx: Context, private readonly config: WebRuntimeConfig) {
121
+ super(ctx, 'web')
122
+ this.searchProviderEnv = process.env.RABI_WEB_SEARCH_PROVIDER
123
+ this.fetchProviderEnv = process.env.RABI_WEB_FETCH_PROVIDER
124
+ }
125
+
126
+ /**
127
+ * Register a search provider. `listProviders()` lists it until the
128
+ * registration is disposed, which happens with the calling fiber or through
129
+ * the returned disposer; registration and disposal each emit
130
+ * `web/providers-changed`. Throws {@link WebError} `WEB_DUPLICATE_PROVIDER`
131
+ * if its id is already registered for search.
132
+ * @param provider - the provider; its `id` is the registry key.
133
+ * @returns the disposer that unregisters the provider.
134
+ */
135
+ registerSearchProvider(provider: WebSearchProvider): () => void {
136
+ return this.registerProvider(this.searchProviders, provider)
137
+ }
138
+
139
+ /**
140
+ * Register a fetch provider, with the listing, disposal, and event behavior
141
+ * of {@link WebRuntime.registerSearchProvider}. Throws {@link WebError}
142
+ * `WEB_DUPLICATE_PROVIDER` if its id is already registered for fetch.
143
+ * @param provider - the provider; its `id` is the registry key.
144
+ * @returns the disposer that unregisters the provider.
145
+ */
146
+ registerFetchProvider(provider: WebFetchProvider): () => void {
147
+ return this.registerProvider(this.fetchProviders, provider)
148
+ }
149
+
150
+ private registerProvider<P extends { readonly id: string }>(store: Map<string, P>, provider: P): () => void {
151
+ if (store.has(provider.id)) {
152
+ throw new WebError(`a web provider with id "${provider.id}" is already registered`, 'WEB_DUPLICATE_PROVIDER')
153
+ }
154
+ const emitChanged = (): void => { this.emitProvidersChanged() }
155
+ const dispose = this.ctx.effect(function* () {
156
+ store.set(provider.id, provider)
157
+ emitChanged()
158
+ yield () => {
159
+ store.delete(provider.id)
160
+ emitChanged()
161
+ }
162
+ }, 'web.registerProvider()')
163
+ // ctx.effect's disposer returns Promise<void>; our disposer API is
164
+ // synchronous fire-and-forget — discard the (always-resolved) promise.
165
+ return () => void dispose()
166
+ }
167
+
168
+ /**
169
+ * List every registered search and fetch provider for provider pickers.
170
+ * Availability does not filter the lists.
171
+ * @returns detached `{ id, title, description }` entries per capability, in registration order.
172
+ */
173
+ @Remote
174
+ listProviders(): WebProviderList {
175
+ return {
176
+ search: [...this.searchProviders.values()].map(providerInfo),
177
+ fetch: [...this.fetchProviders.values()].map(providerInfo),
178
+ }
179
+ }
180
+
181
+ /** Emit `web/providers-changed`, containing each listener's failure so none vetoes the mutation. */
182
+ private emitProvidersChanged(): void {
183
+ for (const listener of this.ctx.events.dispatch('emit', ['web/providers-changed'])) {
184
+ try {
185
+ const returned: unknown = listener()
186
+ void Promise.resolve(returned).catch((error: unknown) => { this.warnListenerFailure(error) })
187
+ } catch (error: unknown) {
188
+ this.warnListenerFailure(error)
189
+ }
190
+ }
191
+ }
192
+
193
+ private warnListenerFailure(error: unknown): void {
194
+ this.ctx.logger.warn('web: a web/providers-changed listener failed')
195
+ this.ctx.logger.warn(error)
196
+ }
197
+
198
+ /**
199
+ * Run one search through the selected provider. Resolves the provider at call
200
+ * time with the selection rules above; throws {@link WebError} when the
201
+ * capability cannot run. The seam enforces `request.maxResults` on the result:
202
+ * if the provider over-returns, `sources[]` is truncated and `truncated` set.
203
+ * @param request - the query, the optional result limit, and the route of the model request the search serves.
204
+ * @param signal - optional cancellation signal forwarded to the provider.
205
+ * @returns the provider's results, capped to `request.maxResults`.
206
+ */
207
+ async search(request: WebSearchRequest, signal?: AbortSignal): Promise<WebSearchResult> {
208
+ const result = await this.selectSearchProvider(request.llmProvider).search(request, signal)
209
+ return capSources(result, request.maxResults)
210
+ }
211
+
212
+ /**
213
+ * Whether the provider `search()` would select can authenticate a search made for a
214
+ * model request on the `llmProvider` chat route. Asks only that provider's `ready()`;
215
+ * one without `ready()` counts as ready. Makes no network calls. A selection failure
216
+ * answers true, because `search()` reports that failure as a structured `WebError`.
217
+ * @param llmProvider - the provider route id of the model request, when known.
218
+ * @returns false only when the selected provider reports that it cannot authenticate.
219
+ */
220
+ async searchReady(llmProvider?: string): Promise<boolean> {
221
+ return await selectedProviderReady(() => this.selectSearchProvider(llmProvider), llmProvider)
222
+ }
223
+
224
+ /**
225
+ * Select the search provider with the rules above, throwing the matching {@link WebError}.
226
+ * @param llmProvider - provider route id of the model request the search serves, when known.
227
+ * @returns the provider the search runs through.
228
+ */
229
+ private selectSearchProvider(llmProvider: string | undefined): WebSearchProvider {
230
+ const configuredId = this.config.searchProvider.get() ?? this.searchProviderEnv
231
+ const preferredId = llmProvider !== undefined && DEEPSEEK_MODEL_ROUTES.has(llmProvider)
232
+ ? DEEPSEEK_ROUTE_SEARCH_PROVIDER
233
+ : OTHER_ROUTE_SEARCH_PROVIDER
234
+ return resolveProvider({
235
+ providers: this.searchProviders,
236
+ preferredId,
237
+ ...configuredId !== undefined ? { configuredId } : {},
238
+ })
239
+ }
240
+
241
+ /**
242
+ * Retrieve one URL through the selected provider. Resolves the provider at
243
+ * call time with the selection rules above; throws {@link WebError} when the
244
+ * capability cannot run. A non-2xx response is a result, not a throw.
245
+ * @param request - the URL plus retrieval options.
246
+ * @param signal - optional cancellation signal forwarded to the provider.
247
+ * @returns the retrieval outcome; non-2xx responses resolve descriptively.
248
+ */
249
+ async fetch(request: WebFetchRequest, signal?: AbortSignal): Promise<WebFetchResult> {
250
+ return await this.selectFetchProvider().fetch(request, signal)
251
+ }
252
+
253
+ /**
254
+ * Whether the provider `fetch()` would select can authenticate a fetch made for a
255
+ * model request on the `llmProvider` chat route. Asks only that provider's `ready()`;
256
+ * one without `ready()` counts as ready. Makes no network calls. A selection failure
257
+ * answers true, because `fetch()` reports that failure as a structured `WebError`.
258
+ * @param llmProvider - the provider route id of the model request, when known.
259
+ * @returns false only when the selected provider reports that it cannot authenticate.
260
+ */
261
+ async fetchReady(llmProvider?: string): Promise<boolean> {
262
+ return await selectedProviderReady(() => this.selectFetchProvider(), llmProvider)
263
+ }
264
+
265
+ /** Select the fetch provider with the rules above, throwing the matching {@link WebError}. */
266
+ private selectFetchProvider(): WebFetchProvider {
267
+ const configuredId = this.config.fetchProvider.get() ?? this.fetchProviderEnv
268
+ return resolveProvider({
269
+ providers: this.fetchProviders,
270
+ ...configuredId !== undefined ? { configuredId } : {},
271
+ })
272
+ }
273
+ }
274
+
275
+ /** Project one provider to its picker entry, omitting an absent title or description. */
276
+ function providerInfo(provider: WebSearchProvider | WebFetchProvider): WebProviderInfo {
277
+ return {
278
+ id: provider.id,
279
+ ...provider.title === undefined ? {} : { title: provider.title },
280
+ ...provider.description === undefined ? {} : { description: provider.description },
281
+ }
282
+ }
283
+
284
+ interface ResolvableProvider {
285
+ readonly id: string
286
+ available(): boolean
287
+ ready?(llmProvider: string | undefined): Promise<boolean>
288
+ }
289
+
290
+ /**
291
+ * Ask the provider an operation selects whether it can authenticate for one chat route.
292
+ * @param select - the operation's selection; throws its {@link WebError} when no provider qualifies.
293
+ * @param llmProvider - the provider route id of the model request, when known.
294
+ * @returns the provider's answer; true when it has no `ready()` or selection fails, because the
295
+ * operation reports that failure itself.
296
+ */
297
+ async function selectedProviderReady(select: () => ResolvableProvider, llmProvider: string | undefined): Promise<boolean> {
298
+ let provider: ResolvableProvider
299
+ try { provider = select() }
300
+ catch (_selectionFailure) { return true /* The operation surfaces the same failure when called. */ }
301
+ return await provider.ready?.(llmProvider) ?? true
302
+ }
303
+
304
+ /** Resolve the selected provider or throw the matching {@link WebError}. */
305
+ function resolveProvider<P extends ResolvableProvider>(selection: Selection<P>): P {
306
+ const { configuredId, providers } = selection
307
+ if (configuredId !== undefined) {
308
+ const provider = providers.get(configuredId)
309
+ if (!provider) {
310
+ throw new WebError(`configured web provider "${configuredId}" is not registered`, 'WEB_PROVIDER_CONFIGURED_MISSING')
311
+ }
312
+ if (!provider.available()) {
313
+ throw new WebError(`configured web provider "${configuredId}" is registered but unavailable`, 'WEB_PROVIDER_CONFIGURED_UNAVAILABLE')
314
+ }
315
+ return provider
316
+ }
317
+ const usable = [...providers.values()].filter(provider => provider.available())
318
+ const preferred = usable.find(provider => provider.id === selection.preferredId)
319
+ if (preferred !== undefined) return preferred
320
+ const [single] = usable
321
+ if (single === undefined) {
322
+ throw new WebError('no usable web provider is registered', 'WEB_PROVIDER_UNAVAILABLE')
323
+ }
324
+ if (usable.length > 1) {
325
+ const ids = usable.map(provider => provider.id).join(', ')
326
+ throw new WebError(`multiple usable web providers are registered (${ids}); configure one explicitly`, 'WEB_PROVIDER_AMBIGUOUS')
327
+ }
328
+ return single
329
+ }
330
+
331
+ /** Enforce `maxResults` on a search result: truncate `sources[]` and flag it. */
332
+ function capSources(result: WebSearchResult, maxResults: number | undefined): WebSearchResult {
333
+ if (maxResults === undefined || result.sources.length <= maxResults) return result
334
+ return { ...result, sources: result.sources.slice(0, maxResults), truncated: true }
335
+ }
336
+
337
+ export default WebRuntime
package/src/types.ts ADDED
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Vocabulary for the web capability seam (`ctx.web`). Search and fetch deliberately share one
3
+ * seam so provider selection, cancellation, errors, and product configuration have one owner,
4
+ * while retaining separate request and result types.
5
+ * @module @unieai/rabi-web/types
6
+ */
7
+
8
+ import { HarnessError } from '@unieai/rabi-llm'
9
+ import type { LocalizedText } from '@unieai/rabi-package-manifest'
10
+
11
+ declare module '@unieai/cordis' {
12
+ interface Events {
13
+ /**
14
+ * The set of registered search or fetch providers changed: one provider
15
+ * registered, or its registration was disposed. Payload-free; consumers
16
+ * re-read `ctx.web.listProviders()` (Remote `web/listProviders`) for the
17
+ * new list. Fires after each committed registry mutation. Observer failures
18
+ * are contained and cannot veto the mutation.
19
+ * @mode emit
20
+ */
21
+ 'web/providers-changed'(): void
22
+ }
23
+ }
24
+
25
+ /**
26
+ * What one search-capable backend is asked to search. Each request carries one
27
+ * query; a consumer may issue several requests. `maxResults` is a
28
+ * `rabi-tool-web`-layer bound passed through unchanged and enforced on the way
29
+ * back by the seam (see {@link WebSearchResult}).
30
+ */
31
+ export interface WebSearchRequest {
32
+ readonly query: string
33
+ /**
34
+ * Upper bound on returned sources; the seam truncates to it. Omitted = no
35
+ * bound. `rabi-tool-web` always sets it. A provider whose API supports a
36
+ * result-count control (the DeepSeek Search API's `count`) should apply it
37
+ * at the request layer as a cost/latency optimization; the seam enforces the
38
+ * bound regardless.
39
+ */
40
+ readonly maxResults?: number
41
+ /**
42
+ * Provider route id of the model request this search serves. While no search
43
+ * provider is configured, the seam selects with it, as `searchReady()` selects
44
+ * with its argument. Omitted = the search serves no model request.
45
+ */
46
+ readonly llmProvider?: string
47
+ }
48
+
49
+ /**
50
+ * Normalized search outcome. `content` is optional provider-generated answer
51
+ * text or summary (DeepSeek returns none; a provider whose API generates an
52
+ * answer returns it here).
53
+ * `sources[]` is the portable citation shape. `truncated` is set by the seam
54
+ * when it cut `sources[]` down to `maxResults`.
55
+ */
56
+ export interface WebSearchResult {
57
+ /** Optional provider-generated answer text, search context, or summary. */
58
+ readonly content?: string
59
+ /** Citeable sources, already truncated to the request's `maxResults`. */
60
+ readonly sources: readonly WebSearchSource[]
61
+ /** True when the seam dropped sources to honor `maxResults`. */
62
+ readonly truncated: boolean
63
+ }
64
+
65
+ /**
66
+ * One citeable source. A source always has a URL; `title`, `snippet`, `summary`,
67
+ * and `publishedAt` are optional because not every provider returns them — forcing
68
+ * adapters to invent them would make the seam lie (some providers return
69
+ * URL-only citations). `rabi-tool-web` renders `title ?? hostname(url)` for display.
70
+ */
71
+ export interface WebSearchSource {
72
+ readonly url: string
73
+ readonly title?: string
74
+ /** Short excerpt suited to display. */
75
+ readonly snippet?: string
76
+ /** Longer excerpt suited to model reading; consumers bound its length. */
77
+ readonly summary?: string
78
+ /** Publication/crawl timestamp as a provider-supplied ISO-8601 string. */
79
+ readonly publishedAt?: string
80
+ }
81
+
82
+ /**
83
+ * What one fetch-capable backend is asked to retrieve. The request deliberately
84
+ * omits timeout, format, prompt, and extraction controls: cancellation is a
85
+ * direct execution argument, while presentation and higher-level LLM concerns
86
+ * belong outside safe retrieval.
87
+ */
88
+ export interface WebFetchRequest {
89
+ readonly url: string
90
+ }
91
+
92
+ /**
93
+ * Normalized fetch outcome. A successful network fetch of a non-2xx response is
94
+ * a result, not an error: the status code is part of the fetched resource
95
+ * state. {@link WebError} is reserved for failures to safely retrieve or
96
+ * represent the resource.
97
+ */
98
+ export interface WebFetchResult {
99
+ /** The final URL after allowed redirects (the request URL is in the request). */
100
+ readonly url: string
101
+ /** HTTP status code of the fetched response. */
102
+ readonly statusCode: number
103
+ /** Decoded body, classified by content kind. */
104
+ readonly body: WebFetchBody
105
+ /** True when the provider capped the decoded body. */
106
+ readonly truncated: boolean
107
+ }
108
+
109
+ /**
110
+ * The decoded body of a fetched resource. A CLOSED discriminated union owned by
111
+ * `rabi-web`: the provider decodes the kind and `rabi-tool-web` renders it, so a
112
+ * new kind is a coordinated change across known packages, not a plugin
113
+ * extension. Consumers `switch` on `kind` ending in `default: assertNever(...)`
114
+ * so adding a kind breaks compilation at every consumer until handled. Each arm
115
+ * stays its own object literal even where fields coincide, so an arm can gain
116
+ * fields the others lack.
117
+ */
118
+ export type WebFetchBody =
119
+ | { readonly kind: 'html'; readonly content: string }
120
+ | { readonly kind: 'text'; readonly content: string }
121
+
122
+ /**
123
+ * A search-capable backend. Registered with `ctx.web.registerSearchProvider`.
124
+ * `id` is a stable string, unique within the search capability kind.
125
+ */
126
+ export interface WebSearchProvider {
127
+ readonly id: string
128
+ /** Display name of this provider; consumers display `id` when it is omitted. */
129
+ readonly title?: string
130
+ /**
131
+ * What a provider picker shows under this provider when it is selected: what the provider
132
+ * is suited for and what it costs or cannot do. Translations are keyed by lowercase language
133
+ * id with a required English entry; consumers show nothing when it is omitted.
134
+ */
135
+ readonly description?: LocalizedText
136
+ /** Cheap local usability check; must not make network calls. */
137
+ available(): boolean
138
+ /**
139
+ * Whether a search made for a model request on the `llmProvider` chat route has a
140
+ * credential to send. Checks configuration only and must not make network calls.
141
+ * Omitted = ready.
142
+ * @param llmProvider - the provider route id of the model request, when known.
143
+ * @returns false when that request's searches could not authenticate.
144
+ */
145
+ ready?(llmProvider: string | undefined): Promise<boolean>
146
+ /** Run one search; honor `signal` for cancellation. */
147
+ search(request: WebSearchRequest, signal?: AbortSignal): Promise<WebSearchResult>
148
+ }
149
+
150
+ /**
151
+ * A fetch-capable backend. Registered with `ctx.web.registerFetchProvider`.
152
+ * `id` is a stable string, unique within the fetch capability kind.
153
+ */
154
+ export interface WebFetchProvider {
155
+ readonly id: string
156
+ /** Display name of this provider; consumers display `id` when it is omitted. */
157
+ readonly title?: string
158
+ /**
159
+ * What a provider picker shows under this provider when it is selected: what the provider
160
+ * is suited for and what it costs or cannot do. Translations are keyed by lowercase language
161
+ * id with a required English entry; consumers show nothing when it is omitted.
162
+ */
163
+ readonly description?: LocalizedText
164
+ /** Cheap local usability check; must not make network calls. */
165
+ available(): boolean
166
+ /**
167
+ * Whether a fetch made for a model request on the `llmProvider` chat route has a
168
+ * credential to send. Checks configuration only and must not make network calls.
169
+ * Omitted = ready.
170
+ * @param llmProvider - the provider route id of the model request, when known.
171
+ * @returns false when that request's fetches could not authenticate.
172
+ */
173
+ ready?(llmProvider: string | undefined): Promise<boolean>
174
+ /** Retrieve one URL; honor `signal` for cancellation. */
175
+ fetch(request: WebFetchRequest, signal?: AbortSignal): Promise<WebFetchResult>
176
+ }
177
+
178
+ /** One registered provider as listed by {@link WebProviderList}. */
179
+ export interface WebProviderInfo {
180
+ /** The provider's registry id, the value `searchProvider` / `fetchProvider` select. */
181
+ readonly id: string
182
+ /** The provider's display name; absent when the provider declares none. */
183
+ readonly title?: string
184
+ /** The provider's picker description; absent when the provider declares none. */
185
+ readonly description?: LocalizedText
186
+ }
187
+
188
+ /**
189
+ * Every currently registered search and fetch provider, each list in
190
+ * registration order. Availability does not filter the lists: a registered
191
+ * provider whose `available()` answers false is still listed.
192
+ */
193
+ export interface WebProviderList {
194
+ /** Registered search providers. */
195
+ readonly search: readonly WebProviderInfo[]
196
+ /** Registered fetch providers. */
197
+ readonly fetch: readonly WebProviderInfo[]
198
+ }
199
+
200
+ /**
201
+ * Typed web error with a machine-routable, open-string `code` and chained `cause`.
202
+ * Consumers must tolerate provider-specific codes. Shared codes cover unavailable,
203
+ * missing, unusable, ambiguous, or duplicate providers, cancellation, and provider failure;
204
+ * the local fetch provider additionally distinguishes invalid or blocked URLs, redirects,
205
+ * size and timeout limits, and unsupported content types. Tool execution exposes the code in
206
+ * structured error metadata.
207
+ */
208
+ export class WebError extends HarnessError {}