diff --git a/.release-please-manifest.json b/.release-please-manifest.json index d0779411..6d4c016b 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "0.110.0" + ".": "0.111.0" } diff --git a/.stats.yml b/.stats.yml index 40c9d3b0..e8ac4eb6 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1 +1 @@ -configured_endpoints: 165 +configured_endpoints: 169 diff --git a/CHANGELOG.md b/CHANGELOG.md index a45fa6c1..0d1c8026 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## [0.111.0](https://github.com/kernel/kernel-node-sdk/compare/v0.110.0...v0.111.0) (2026-09-22) + + +### Features + +* Allow managed auth logins to disable learned skills ([44a8405](https://github.com/kernel/kernel-node-sdk/commit/44a84053583ee6cc6a9d4dd606e5ea451df84639)) +* Distinguish optimistic managed auth reauth ([3e5f69d](https://github.com/kernel/kernel-node-sdk/commit/3e5f69d8cdeacb19c724492b3f7b1807e5bd4410)) +* Implement Search API v1 providers ([114768a](https://github.com/kernel/kernel-node-sdk/commit/114768a44145ce1eaaf13345bf2f5ae665b7947a)) +* Persist stable managed auth completion timestamps ([5495ce6](https://github.com/kernel/kernel-node-sdk/commit/5495ce64ac30df65e4550101a3e206b1bf011cb5)) +* Publish restricted_route_unavailable and unknown proxy_error codes ([e1593e6](https://github.com/kernel/kernel-node-sdk/commit/e1593e60bd25ccf001acf7ad35ebc46e1c00dffc)) +* Support native prepared Adyen Sessions checkout ([53311cd](https://github.com/kernel/kernel-node-sdk/commit/53311cd171547408c410b4389197abb8b100febc)) + ## [0.110.0](https://github.com/kernel/kernel-node-sdk/compare/v0.109.0...v0.110.0) (2026-09-18) diff --git a/api.md b/api.md index 39e15f21..bca08e38 100644 --- a/api.md +++ b/api.md @@ -654,3 +654,43 @@ Methods: - client.credentialProviders.delete(id) -> void - client.credentialProviders.listItems(id) -> CredentialProviderListItemsResponse - client.credentialProviders.test(id) -> CredentialProviderTestResult + +# Search + +Types: + +- Attempt +- ProviderTarget +- Request +- Result +- Search +- Strategy +- Usage +- Warning + +Methods: + +- client.search.create({ ...params }) -> Search +- client.search.retrieve(id) -> Search + +## Contents + +Types: + +- FetchRequest +- Response + +Methods: + +- client.search.contents.fetch(id, { ...params }) -> void + +## Providers + +Types: + +- Provider +- ProviderListResponse + +Methods: + +- client.search.providers.list({ ...params }) -> ProviderListResponse diff --git a/package.json b/package.json index 222d112c..0930d37e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@onkernel/sdk", - "version": "0.110.0", + "version": "0.111.0", "description": "The official TypeScript library for the Kernel API", "author": "Kernel <>", "types": "dist/index.d.ts", diff --git a/src/client.ts b/src/client.ts index 5c38e448..6055b9b8 100644 --- a/src/client.ts +++ b/src/client.ts @@ -216,6 +216,18 @@ import { ProjectsOffsetPagination, UpdateProjectRequest, } from './resources/projects/projects'; +import { + Attempt, + ProviderTarget, + Request, + Result, + Search, + SearchCreateParams, + SearchResource, + Strategy, + Usage, + Warning, +} from './resources/search/search'; import { Telemetry } from './resources/telemetry/telemetry'; import { Vault, @@ -1104,6 +1116,10 @@ export class Kernel { * Configure external credential providers like 1Password. */ credentialProviders: API.CredentialProviders = new API.CredentialProviders(this); + /** + * Search the web and retrieve content for selected results. + */ + search: API.SearchResource = new API.SearchResource(this); } Kernel.Deployments = Deployments; @@ -1125,6 +1141,7 @@ Kernel.Organization = Organization; Kernel.AuditLogs = AuditLogs; Kernel.APIKeys = APIKeys; Kernel.CredentialProviders = CredentialProviders; +Kernel.SearchResource = SearchResource; export declare namespace Kernel { export type RequestOptions = Opts.RequestOptions; @@ -1358,6 +1375,19 @@ export declare namespace Kernel { type CredentialProviderListParams as CredentialProviderListParams, }; + export { + SearchResource as SearchResource, + type Attempt as Attempt, + type ProviderTarget as ProviderTarget, + type Request as Request, + type Result as Result, + type Search as Search, + type Strategy as Strategy, + type Usage as Usage, + type Warning as Warning, + type SearchCreateParams as SearchCreateParams, + }; + export type AppAction = API.AppAction; export type BrowserExtension = API.BrowserExtension; export type BrowserProfile = API.BrowserProfile; diff --git a/src/resources/auth/connections.ts b/src/resources/auth/connections.ts index 735609af..2fa308bb 100644 --- a/src/resources/auth/connections.ts +++ b/src/resources/auth/connections.ts @@ -314,16 +314,18 @@ export interface ManagedAuth { browser_telemetry?: ManagedAuth.BrowserTelemetry | null; /** - * Whether Kernel can automatically re-authenticate this connection when the - * session expires. Requires a prior successful login plus either a Kernel - * credential or an external credential reference. See `can_reauth_reason` for the - * specific outcome. + * Whether this connection's stored requirements are eligible for unattended + * re-authentication. A true value can represent either fully satisfiable + * requirements or a best-effort attempt. It does not account for whether automatic + * re-authentication is enabled or parent workflow state such as an active flow or + * circuit-breaker cooldown, so it does not guarantee an attempt on the next health + * check. See `can_reauth_reason` for the specific outcome. */ can_reauth?: boolean; /** * Machine-readable reason for the current value of `can_reauth`. Affirmative - * values (re-auth is possible): + * values (requirements are eligible for unattended re-authentication): * * - `external_credential` — an external credential provider is attached * - `cua_has_credential` — CUA flow with a stored credential @@ -332,8 +334,12 @@ export interface ManagedAuth { * - `viable_plans_found` — at least one stored login plan can be replayed * - `no_requirements_recorded` — no recorded credential requirements to fail * against - * - `totp_reauth_allowed` — TOTP is the only recorded requirement and is safe to - * attempt automatically + * - `totp_reauth_allowed` — TOTP is the only recorded requirement and a stored + * secret can generate the code + * - `optimistic_totp_attempt` — TOTP was previously required but no reusable + * secret is stored; the connection remains eligible for a + * circuit-breaker-bounded attempt because the site may not challenge returning + * sessions * - `requirements_satisfiable` — recorded requirements contain no recognized * blocker * @@ -363,6 +369,7 @@ export interface ManagedAuth { | 'viable_plans_found' | 'no_requirements_recorded' | 'totp_reauth_allowed' + | 'optimistic_totp_attempt' | 'requirements_satisfiable' | 'no_prior_successful_login' | 'no_credential' @@ -1298,6 +1305,13 @@ export interface ManagedAuthTimelineEvent { */ browser_session_id?: string; + /** + * When the login/reauth attempt first reached a terminal status. Stable across + * retries and subsequent cleanup writes. Absent for in-progress attempts, health + * checks, and historical attempts without a recorded completion time. + */ + completed_at?: string; + /** * Machine-readable error code. Present when a login/reauth event failed. */ @@ -2478,6 +2492,13 @@ export interface ConnectionLoginParams { * When omitted, the connection's record_session default is used. */ record_session?: boolean; + + /** + * Controls whether this login reads and writes learned domain skills. Automatic + * reauths inherit the selected mode until a later accepted login sets enabled or + * omits this field. Defaults to enabled when omitted. + */ + skill_mode?: 'enabled' | 'disabled'; } export namespace ConnectionLoginParams { diff --git a/src/resources/browsers/telemetry.ts b/src/resources/browsers/telemetry.ts index be14c180..100f182e 100644 --- a/src/resources/browsers/telemetry.ts +++ b/src/resources/browsers/telemetry.ts @@ -4338,9 +4338,11 @@ export namespace BrowserProxyErrorEvent { * Proxy-layer error code: the X-Kernel-Proxy-Error response header value from a * branded 5xx error page served by the metro egress host-proxy. Values mirror what * the proxy emits: destination_blocked, provider_blacklisted, - * provider_unreachable, provider_rejected, origin_tls_timeout, proxy_unavailable, - * upstream_timeout, upstream_dns_failure, upstream_connect_failed. Unknown header - * values are dropped. + * provider_unreachable, provider_rejected, origin_tls_timeout, + * origin_response_incomplete, proxy_unavailable, restricted_route_unavailable, + * upstream_timeout, upstream_dns_failure, upstream_connect_failed. A header value + * the browser image does not recognize is reported as unknown, with the header + * value in raw_code. */ code: | 'destination_blocked' @@ -4348,10 +4350,13 @@ export namespace BrowserProxyErrorEvent { | 'provider_unreachable' | 'provider_rejected' | 'origin_tls_timeout' + | 'origin_response_incomplete' | 'proxy_unavailable' + | 'restricted_route_unavailable' | 'upstream_timeout' | 'upstream_dns_failure' - | 'upstream_connect_failed'; + | 'upstream_connect_failed' + | 'unknown'; /** * CDP request identifier matching the originating request. @@ -4368,6 +4373,14 @@ export namespace BrowserProxyErrorEvent { */ method?: string; + /** + * Sanitized X-Kernel-Proxy-Error header value, present only when code is unknown. + * Surrounding whitespace is removed, the value is lowercased, characters outside + * [a-z0-9_] are replaced with \_, and the result is truncated to at most 64 + * characters. + */ + raw_code?: string; + /** * CDP Network.ResourceType for the request, when known. */ diff --git a/src/resources/index.ts b/src/resources/index.ts index c47f8c54..b0ba8488 100644 --- a/src/resources/index.ts +++ b/src/resources/index.ts @@ -185,6 +185,18 @@ export { type ProxyCheckParams, type ProxyListResponsesOffsetPagination, } from './proxies'; +export { + SearchResource, + type Attempt, + type ProviderTarget, + type Request, + type Result, + type Search, + type Strategy, + type Usage, + type Warning, + type SearchCreateParams, +} from './search/search'; export { Telemetry } from './telemetry/telemetry'; export { VaultProviderConfigs, diff --git a/src/resources/search.ts b/src/resources/search.ts new file mode 100644 index 00000000..262e65cc --- /dev/null +++ b/src/resources/search.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './search/index'; diff --git a/src/resources/search/contents.ts b/src/resources/search/contents.ts new file mode 100644 index 00000000..eda9624a --- /dev/null +++ b/src/resources/search/contents.ts @@ -0,0 +1,327 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as SearchAPI from './search'; +import { APIPromise } from '../../core/api-promise'; +import { buildHeaders } from '../../internal/headers'; +import { RequestOptions } from '../../internal/request-options'; +import { path } from '../../internal/utils/path'; + +/** + * Search the web and retrieve content for selected results. + */ +export class Contents extends APIResource { + /** + * Deferred result-content retrieval is reserved but not available in this release. + * Requests return 404 until the retrieval implementation is shipped. X-Request-Id + * identifies this request separately from the search resource. + * + * @example + * ```ts + * await client.search.contents.fetch('srch_abc123'); + * ``` + */ + fetch(id: string, body: ContentFetchParams, options?: RequestOptions): APIPromise { + return this._client.post(path`/search/${id}/contents`, { + body, + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); + } +} + +export interface FetchRequest { + /** + * Defaults to source:auto when omitted. + */ + content?: FetchRequest.Content; + + /** + * Maximum number of search results to fetch when result_ids is omitted, starting + * from rank 1. Mutually exclusive with result_ids. + */ + limit?: number; + + /** + * Kernel-generated IDs from the referenced retained search, in desired response + * order. They are not provider-standard IDs. Mutually exclusive with limit. + */ + result_ids?: Array; + + /** + * Overall deadline across all selected results. + */ + timeout_ms?: number; +} + +export namespace FetchRequest { + /** + * Defaults to source:auto when omitted. + */ + export interface Content { + /** + * Invalid with source=provider. Supplying browser_id requires source=browser so + * the chosen identity is not bypassed. + */ + browser?: Content.Browser; + + format?: 'markdown' | 'text'; + + /** + * Maximum acceptable age of cached page content, measured from origin retrieval. 0 + * forces a live fetch. Governs the Kernel content cache, which is scoped to the + * caller organization and project and separated by retrieval context; fetches + * through a caller-supplied browser_id bypass that cache. Mapped to the provider + * freshness control when source is provider and the provider supports one; + * otherwise provider content age is reported as unknown via fetched_at. + */ + max_age_hours?: number; + + /** + * Per-result Unicode character limit after extraction. + */ + max_chars?: number; + + /** + * provider uses the search provider's native content retrieval; browser fetches + * each URL through a Kernel browser; auto prefers Kernel browser retrieval and + * falls back to provider-native content when browser retrieval is unavailable or + * unsuitable. Defaults to auto for both inline and deferred retrieval. Deferred + * provider retrieval requires post_hoc capability; an explicit provider source + * without it is a 400. Missing documents produce per-result unavailable outcomes, + * not request failures. + */ + source?: 'auto' | 'provider' | 'browser'; + + /** + * Per-result deadline including capacity acquisition, retrieval, and extraction. + * Also bounded by the overall request deadline. + */ + timeout_ms?: number; + } + + export namespace Content { + /** + * Invalid with source=provider. Supplying browser_id requires source=browser so + * the chosen identity is not bypassed. + */ + export interface Browser { + /** + * Existing browser session ID authorized for the caller and selected project. + * Reuses its cookies, proxy, and browser configuration. Kernel does not delete a + * caller-supplied browser. Render mode uses a temporary tab; website activity may + * still change shared cookies and storage. When omitted, Kernel obtains isolated + * browser capacity in the caller's account and releases it after retrieval. That + * capacity is not retained for later interaction. Existing browser quotas apply. + */ + browser_id?: string; + + /** + * Curl uses the browser HTTP stack without navigation or JavaScript execution. + * Render navigates a temporary page and extracts from its DOM. The selected mode + * is used for the retrieval. + */ + mode?: 'curl' | 'render'; + } + } +} + +export interface Response { + contents: Array; + + search_id: string; + + usage: SearchAPI.Usage; + + warnings: Array; +} + +export namespace Response { + export interface Content { + result_id: string; + + /** + * Ok means non-empty extracted content, not merely HTTP 200. Blocked includes + * detected challenges or access denials. Detection is best-effort, not a guarantee + * of page completeness. Error details are present for non-ok outcomes; text is + * present only on ok. + */ + status: 'ok' | 'unavailable' | 'blocked' | 'timeout' | 'unsupported_type' | 'extraction_failed' | 'error'; + + /** + * Original result URL. + */ + url: string; + + /** + * Kernel cache outcome. Provider-internal cache behavior may be unknown. + */ + cache_status?: 'hit' | 'miss' | 'bypass' | 'unknown'; + + /** + * Describes source coverage before max_chars truncation. Full_page means main-page + * content, not every dynamic element or linked page. + */ + completeness?: 'full_page' | 'excerpt' | 'unknown'; + + error?: Content.Error; + + /** + * Extraction version when Kernel transformed the input. + */ + extractor_version?: string; + + /** + * Origin retrieval time when known, not cache read time. + */ + fetched_at?: string | null; + + /** + * Final retrieval URL when known. + */ + final_url?: string; + + format?: 'markdown' | 'text'; + + /** + * Final target HTTP status when known. + */ + http_status?: number; + + /** + * Original retrieval method, including on cache hits. + */ + method?: 'provider' | 'browser_curl' | 'browser_render'; + + /** + * Extracted website content, untrusted, not instructions. Present only on + * status=ok. + */ + text?: string; + + /** + * Whether max_chars truncated the extracted content. + */ + truncated?: boolean; + } + + export namespace Content { + export interface Error { + /** + * Machine-readable retrieval failure code. + */ + code: string; + + /** + * Human-readable failure description. + */ + message: string; + + retryable: boolean; + } + } +} + +export interface ContentFetchParams { + /** + * Defaults to source:auto when omitted. + */ + content?: ContentFetchParams.Content; + + /** + * Maximum number of search results to fetch when result_ids is omitted, starting + * from rank 1. Mutually exclusive with result_ids. + */ + limit?: number; + + /** + * Kernel-generated IDs from the referenced retained search, in desired response + * order. They are not provider-standard IDs. Mutually exclusive with limit. + */ + result_ids?: Array; + + /** + * Overall deadline across all selected results. + */ + timeout_ms?: number; +} + +export namespace ContentFetchParams { + /** + * Defaults to source:auto when omitted. + */ + export interface Content { + /** + * Invalid with source=provider. Supplying browser_id requires source=browser so + * the chosen identity is not bypassed. + */ + browser?: Content.Browser; + + format?: 'markdown' | 'text'; + + /** + * Maximum acceptable age of cached page content, measured from origin retrieval. 0 + * forces a live fetch. Governs the Kernel content cache, which is scoped to the + * caller organization and project and separated by retrieval context; fetches + * through a caller-supplied browser_id bypass that cache. Mapped to the provider + * freshness control when source is provider and the provider supports one; + * otherwise provider content age is reported as unknown via fetched_at. + */ + max_age_hours?: number; + + /** + * Per-result Unicode character limit after extraction. + */ + max_chars?: number; + + /** + * provider uses the search provider's native content retrieval; browser fetches + * each URL through a Kernel browser; auto prefers Kernel browser retrieval and + * falls back to provider-native content when browser retrieval is unavailable or + * unsuitable. Defaults to auto for both inline and deferred retrieval. Deferred + * provider retrieval requires post_hoc capability; an explicit provider source + * without it is a 400. Missing documents produce per-result unavailable outcomes, + * not request failures. + */ + source?: 'auto' | 'provider' | 'browser'; + + /** + * Per-result deadline including capacity acquisition, retrieval, and extraction. + * Also bounded by the overall request deadline. + */ + timeout_ms?: number; + } + + export namespace Content { + /** + * Invalid with source=provider. Supplying browser_id requires source=browser so + * the chosen identity is not bypassed. + */ + export interface Browser { + /** + * Existing browser session ID authorized for the caller and selected project. + * Reuses its cookies, proxy, and browser configuration. Kernel does not delete a + * caller-supplied browser. Render mode uses a temporary tab; website activity may + * still change shared cookies and storage. When omitted, Kernel obtains isolated + * browser capacity in the caller's account and releases it after retrieval. That + * capacity is not retained for later interaction. Existing browser quotas apply. + */ + browser_id?: string; + + /** + * Curl uses the browser HTTP stack without navigation or JavaScript execution. + * Render navigates a temporary page and extracts from its DOM. The selected mode + * is used for the retrieval. + */ + mode?: 'curl' | 'render'; + } + } +} + +export declare namespace Contents { + export { + type FetchRequest as FetchRequest, + type Response as Response, + type ContentFetchParams as ContentFetchParams, + }; +} diff --git a/src/resources/search/index.ts b/src/resources/search/index.ts new file mode 100644 index 00000000..03323528 --- /dev/null +++ b/src/resources/search/index.ts @@ -0,0 +1,16 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { Contents, type FetchRequest, type Response, type ContentFetchParams } from './contents'; +export { Providers, type Provider, type ProviderListResponse, type ProviderListParams } from './providers'; +export { + SearchResource, + type Attempt, + type ProviderTarget, + type Request, + type Result, + type Search, + type Strategy, + type Usage, + type Warning, + type SearchCreateParams, +} from './search'; diff --git a/src/resources/search/providers.ts b/src/resources/search/providers.ts new file mode 100644 index 00000000..6f96d5a9 --- /dev/null +++ b/src/resources/search/providers.ts @@ -0,0 +1,197 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import { APIPromise } from '../../core/api-promise'; +import { RequestOptions } from '../../internal/request-options'; + +/** + * Search the web and retrieve content for selected results. + */ +export class Providers extends APIResource { + /** + * Lists providers, capabilities, and machine-readable native-option schemas. Auto + * and fallback are strategies, not provider entries. The list is not paginated and + * contains no latency benchmarks. X-Request-Id identifies the request. + * + * @example + * ```ts + * const providers = await client.search.providers.list(); + * ``` + */ + list( + query: ProviderListParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { + return this._client.get('/search/providers', { query, ...options }); + } +} + +export interface Provider { + content: Provider.Content; + + max_results_cap: number; + + params: Provider.Params; + + provider_options: Provider.ProviderOptions; + + slug: string; + + /** + * Provider-specific limitations, conditional filter support, and warnings about + * search modes. + */ + notes?: Array; +} + +export namespace Provider { + export interface Content { + /** + * Can enforce the requested maximum content age. + */ + freshness_control: boolean; + + /** + * Supports content retrieval with the search request. + */ + inline: boolean; + + /** + * Supports content retrieval after the search completes. + */ + post_hoc: boolean; + } + + export interface Params { + country: Params.Country; + + end_date: Params.EndDate; + + exclude_domains: Params.ExcludeDomains; + + include_domains: Params.IncludeDomains; + + language: Params.Language; + + recency: Params.Recency; + + safe_search: Params.SafeSearch; + + start_date: Params.StartDate; + } + + export namespace Params { + export interface Country { + support: 'native' | 'emulated' | 'unsupported'; + + /** + * Translation behavior, limitations, and precision. + */ + notes?: string; + } + + export interface EndDate { + support: 'native' | 'emulated' | 'unsupported'; + + /** + * Translation behavior, limitations, and precision. + */ + notes?: string; + } + + export interface ExcludeDomains { + support: 'native' | 'emulated' | 'unsupported'; + + /** + * Translation behavior, limitations, and precision. + */ + notes?: string; + } + + export interface IncludeDomains { + support: 'native' | 'emulated' | 'unsupported'; + + /** + * Translation behavior, limitations, and precision. + */ + notes?: string; + } + + export interface Language { + support: 'native' | 'emulated' | 'unsupported'; + + /** + * Translation behavior, limitations, and precision. + */ + notes?: string; + } + + export interface Recency { + support: 'native' | 'emulated' | 'unsupported'; + + /** + * Translation behavior, limitations, and precision. + */ + notes?: string; + } + + export interface SafeSearch { + support: 'native' | 'emulated' | 'unsupported'; + + /** + * Translation behavior, limitations, and precision. + */ + notes?: string; + } + + export interface StartDate { + support: 'native' | 'emulated' | 'unsupported'; + + /** + * Translation behavior, limitations, and precision. + */ + notes?: string; + } + } + + export interface ProviderOptions { + /** + * JSON Schema for the provider-native options accepted by POST /search. + */ + schema: { [key: string]: unknown }; + + /** + * OpenAPI component name for the matching typed provider-options schema. + */ + schema_ref: string; + + examples?: Array<{ [key: string]: unknown }>; + } +} + +export type ProviderListResponse = Array; + +export interface ProviderListParams { + /** + * Optional concrete provider slug filter. Omit to list every provider. + */ + slug?: + | 'brave' + | 'exa' + | 'perplexity' + | 'context' + | 'parallel' + | 'valyu' + | 'octen' + | 'you' + | 'tavily' + | 'serpapi'; +} + +export declare namespace Providers { + export { + type Provider as Provider, + type ProviderListResponse as ProviderListResponse, + type ProviderListParams as ProviderListParams, + }; +} diff --git a/src/resources/search/search.ts b/src/resources/search/search.ts new file mode 100644 index 00000000..e5a91878 --- /dev/null +++ b/src/resources/search/search.ts @@ -0,0 +1,1496 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as SearchAPI from './search'; +import * as ContentsAPI from './contents'; +import { ContentFetchParams, Contents as ContentsAPIContents, FetchRequest, Response } from './contents'; +import * as ProvidersAPI from './providers'; +import { Provider, ProviderListParams, ProviderListResponse, Providers } from './providers'; +import { APIPromise } from '../../core/api-promise'; +import { RequestOptions } from '../../internal/request-options'; +import { path } from '../../internal/utils/path'; + +/** + * Search the web and retrieve content for selected results. + */ +export class SearchResource extends APIResource { + contents: ContentsAPI.Contents = new ContentsAPI.Contents(this._client); + providers: ProvidersAPI.Providers = new ProvidersAPI.Providers(this._client); + + /** + * Returns ranked results from one serving provider. The default strategy selects a + * provider that supports the requested options. The fallback strategy tries + * providers in the supplied order. Results are not blended across providers. + * Portable filters may be approximated or omitted according to provider + * capabilities; warnings describe those outcomes unless strict_params is true. + * Native options apply only to their selected provider. + * + * @example + * ```ts + * const search = await client.search.create({ query: 'x' }); + * ``` + */ + create(body: SearchCreateParams, options?: RequestOptions): APIPromise { + return this._client.post('/search', { body, ...options }); + } + + /** + * Returns the retained search resource exactly as it was returned by POST /search: + * results, attempts, warnings, usage, and expires_at. No provider is called and + * nothing is billed. Use it to look up a search by ID for debugging, cost review, + * or to recover result IDs before calling the contents endpoint. Inline content + * fetched at search time is included; content fetched later through the contents + * endpoint is not merged in. Missing, expired, or inaccessible searches + * return 404. + * + * @example + * ```ts + * const search = await client.search.retrieve('srch_abc123'); + * ``` + */ + retrieve(id: string, options?: RequestOptions): APIPromise { + return this._client.get(path`/search/${id}`, options); + } +} + +export interface Attempt { + duration_ms: number; + + outcome: 'success' | 'empty' | 'error' | 'timeout'; + + provider: string; + + error_code?: string; + + retryable?: boolean; +} + +/** + * Provider name paired with its typed native options. + */ +export type ProviderTarget = + | ProviderTarget.SearchBraveTarget + | ProviderTarget.SearchExaTarget + | ProviderTarget.SearchPerplexityTarget + | ProviderTarget.SearchContextTarget + | ProviderTarget.SearchParallelTarget + | ProviderTarget.SearchValyuTarget + | ProviderTarget.SearchOctenTarget + | ProviderTarget.SearchYouTarget + | ProviderTarget.SearchTavilyTarget + | ProviderTarget.SearchSerpAPITarget; + +export namespace ProviderTarget { + export interface SearchBraveTarget { + provider: 'brave'; + + options?: SearchBraveTarget.Options; + } + + export namespace SearchBraveTarget { + export interface Options { + /** + * Provider-native count. Lower-only alias for max_results; cannot raise the + * effective result cap. + */ + count?: number; + + /** + * Request additional snippets from Brave. + */ + extra_snippets?: boolean; + + /** + * Goggles re-ranking definition URL. + */ + goggles?: string; + + /** + * @deprecated Deprecated Brave Goggle identifier. Prefer goggles. + */ + goggles_id?: string; + + /** + * Include Brave's fetch metadata. + */ + include_fetch_metadata?: boolean; + + /** + * Page offset supported by Brave. + */ + offset?: number; + + /** + * Brave search operators. + */ + operators?: string; + + /** + * Comma-separated result types to include, e.g. "web,news". + */ + result_filter?: string; + + /** + * Language of the search, e.g. "en". + */ + search_lang?: string; + + /** + * Apply Brave's query spellcheck. + */ + spellcheck?: boolean; + + /** + * Language for UI strings in the response. + */ + ui_lang?: string; + + /** + * Measurement units. + */ + units?: 'metric' | 'imperial'; + } + } + + export interface SearchExaTarget { + provider: 'exa'; + + options?: SearchExaTarget.Options; + } + + export namespace SearchExaTarget { + export interface Options { + /** + * Provider data-category hint. + */ + category?: string; + + /** + * Provider-native compliance controls. Requires support and authorization on the + * provider account. + */ + compliance?: string; + + /** + * Provider-native content retrieval. Available without requesting Kernel browser + * retrieval; may incur provider retrieval charges. + */ + contents?: Options.Contents; + + /** + * Provider-native cache-age control. Unlike content.max_age_hours, this retains + * Exa semantics, including any native sentinel values. It does not imply a + * cross-provider freshness guarantee. + */ + maxAgeHours?: number; + + /** + * Provider-native count. Lower-only alias for max_results. + */ + numResults?: number; + + /** + * Search mode supported by Exa. + */ + type?: 'auto' | 'fast' | 'instant'; + } + + export namespace Options { + /** + * Provider-native content retrieval. Available without requesting Kernel browser + * retrieval; may incur provider retrieval charges. + */ + export interface Contents { + /** + * Return query-relevant provider excerpts. + */ + highlights?: boolean; + + /** + * Return provider page text. + */ + text?: boolean; + } + } + } + + export interface SearchPerplexityTarget { + provider: 'perplexity'; + + options?: SearchPerplexityTarget.Options; + } + + export namespace SearchPerplexityTarget { + export interface Options { + /** + * MM/DD/YYYY. Filters by last-updated date, not published date. + */ + last_updated_after_filter?: string; + + /** + * MM/DD/YYYY upper bound on last-updated date. + */ + last_updated_before_filter?: string; + + /** + * Provider-native count. Lower-only alias for max_results. + */ + max_results?: number; + + /** + * Values outside the documented range are rejected. + */ + max_tokens?: number; + + /** + * Per-page token cap. + */ + max_tokens_per_page?: number; + + /** + * Provider-native multi-query form, applied only to Perplexity. Other fallback + * providers receive the top-level query. Each query may incur a separate provider + * charge. + */ + query?: Array; + + /** + * Provider context size supported by the selected model. + */ + search_context_size?: 'low' | 'medium' | 'high'; + + /** + * ISO 639-1 language codes, max 20. + */ + search_language_filter?: Array; + } + } + + export interface SearchContextTarget { + provider: 'context'; + + options?: SearchContextTarget.Options; + } + + export namespace SearchContextTarget { + export interface Options { + /** + * ISO 3166-1 alpha-2 country code. + */ + country?: string; + + /** + * Blocklist of result domains. + */ + excludeDomains?: Array; + + /** + * Restrict results to content published within this window. + */ + freshness?: 'last_24_hours' | 'last_week' | 'last_month' | 'last_year'; + + /** + * Allowlist of result domains. + */ + includeDomains?: Array; + + markdownOptions?: Options.MarkdownOptions; + + /** + * Number of results to request from Context.dev. + */ + numResults?: number; + + /** + * Expand the query into multiple parallel variants. + */ + queryFanout?: boolean; + + /** + * Usage tracking tags. + */ + tags?: Array; + + /** + * Context.dev request timeout in milliseconds. + */ + timeoutMS?: number; + } + + export namespace Options { + export interface MarkdownOptions { + enabled?: boolean; + + includeFrames?: boolean; + + includeImages?: boolean; + + includeLinks?: boolean; + + maxAgeMs?: number; + + pdf?: MarkdownOptions.Pdf; + + shortenBase64Images?: boolean; + + timeoutMS?: number; + + useMainContentOnly?: boolean; + + waitForMs?: number; + } + + export namespace MarkdownOptions { + export interface Pdf { + shouldParse?: boolean; + } + } + } + } + + export interface SearchParallelTarget { + provider: 'parallel'; + + options?: SearchParallelTarget.Options; + } + + export namespace SearchParallelTarget { + export interface Options { + /** + * Explicit search settings. Unified search parameters are re-applied to + * overlapping settings; native result counts are lower-only. + */ + advanced_settings?: Options.AdvancedSettings; + + /** + * Client model hint. + */ + client_model?: string; + + /** + * Cap total characters returned. + */ + max_chars_total?: number; + + /** + * Search mode. Basic is used when omitted; each mode can have different latency + * and charges. + */ + mode?: 'turbo' | 'fast' | 'basic' | 'advanced'; + + /** + * The goal behind the search, stated separately from the query. + */ + objective?: string; + + /** + * Provider-native multi-query search. Defaults to [query] for this provider. + */ + search_queries?: Array; + + /** + * Group related searches. + */ + session_id?: string; + } + + export namespace Options { + /** + * Explicit search settings. Unified search parameters are re-applied to + * overlapping settings; native result counts are lower-only. + */ + export interface AdvancedSettings { + excerpt_settings?: AdvancedSettings.ExcerptSettings; + + fetch_policy?: AdvancedSettings.FetchPolicy; + + /** + * Native ISO 3166-1 alpha-2 location preference. + */ + location?: string | null; + + /** + * Native count; lower-only alias for unified max_results. + */ + max_results?: number | null; + + source_policy?: AdvancedSettings.SourcePolicy; + } + + export namespace AdvancedSettings { + export interface ExcerptSettings { + max_chars_per_result?: number | null; + } + + export interface FetchPolicy { + /** + * When false, the provider may return cached content after live fetching fails. + */ + disable_cache_fallback?: boolean; + + /** + * Native live-fetch trigger; minimum 600 seconds. Not the unified hard-freshness + * control. + */ + max_age_seconds?: number | null; + + /** + * Native live-fetch timeout, bounded by the remaining overall deadline. + */ + timeout_seconds?: number | null; + } + + export interface SourcePolicy { + /** + * Native publication-date lower bound. + */ + after_date?: string | null; + + /** + * Native exclusions; the provider ignores these when native include_domains is + * non-empty. + */ + exclude_domains?: Array; + + /** + * Native domain/path restrictions. Explicit unified domain parameters take + * precedence. Combined include/exclude native lists cannot exceed 200 entries. + */ + include_domains?: Array; + } + } + } + } + + export interface SearchValyuTarget { + provider: 'valyu'; + + options?: SearchValyuTarget.Options; + } + + export namespace SearchValyuTarget { + export interface Options { + /** + * Trade depth for latency. + */ + fast_mode?: boolean; + + /** + * Allow historical cached results. + */ + historical_cache?: boolean; + + /** + * Include abstracts for academic sources. + */ + include_abstracts?: boolean; + + /** + * Natural-language retrieval guidance. + */ + instructions?: string; + + /** + * Mark the search as an agent tool call. + */ + is_tool_call?: boolean; + + /** + * Provider-native count. Lower-only alias for max_results. + */ + max_num_results?: number; + + /** + * Provider-native USD-per-thousand-results price ceiling. Forwarded to Valyu. + */ + max_price?: number; + + /** + * Provider-native minimum relevance threshold. Not a normalized cross-provider + * score. + */ + relevance_threshold?: number; + + /** + * Provider result-content length preset. + */ + response_length?: 'short' | 'medium' | 'large' | 'max'; + + /** + * Corpus selector, including all, web, proprietary, and news. Provider corpus + * choice may change billing; Kernel does not force web-only searches. + */ + search_type?: string; + + /** + * Bias retrieval toward these sources. + */ + source_biases?: Array; + + /** + * Return URLs without content. + */ + url_only?: boolean; + } + } + + export interface SearchOctenTarget { + provider: 'octen'; + + options?: SearchOctenTarget.Options; + } + + export namespace SearchOctenTarget { + export interface Options { + count?: number; + + end_time?: string; + + exclude_domains?: Array; + + exclude_text?: Array; + + format?: 'markdown' | 'text'; + + full_content?: Options.FullContent; + + highlight?: Options.Highlight; + + include_domains?: Array; + + include_images?: boolean; + + include_text?: Array; + + language?: Array; + + safesearch?: 'off' | 'strict'; + + start_time?: string; + + time_basis?: 'auto' | 'published' | 'crawled'; + + time_range?: 'day' | 'week' | 'month' | 'year' | 'd' | 'w' | 'm' | 'y'; + + topic?: 'general' | 'news'; + } + + export namespace Options { + export interface FullContent { + enable?: boolean; + + max_tokens?: number; + } + + export interface Highlight { + enable?: boolean; + + max_tokens?: number; + } + } + } + + export interface SearchYouTarget { + provider: 'you'; + + options?: SearchYouTarget.Options; + } + + export namespace SearchYouTarget { + export interface Options { + /** + * Prefer these domains without excluding others. Cannot be combined with + * include_domains if the provider does not accept the combination. + */ + boost_domains?: Array; + + /** + * Provider-native per-section count. Lower-only alias for max_results. Web and + * news sections may produce more rows than Kernel returns. + */ + count?: number; + + /** + * Native extraction timeout in seconds, bounded by the remaining Kernel request + * deadline. + */ + crawl_timeout?: number; + + /** + * Provider-native page extraction. Both modes may incur per-row charges; full_page + * may retrieve web and news rows. + */ + extraction?: Options.Extraction; + + /** + * Request licensed-data output. URL-less knowledge entries are not converted into + * web results; include_raw exposes the full provider response separately. + */ + knowledge?: 'core'; + + /** + * BCP 47 result language from You.com's 51-value enum, e.g. "EN", "JA". Default + * EN. + */ + language?: string; + + /** + * Page offset supported by You.com. + */ + offset?: number; + } + + export namespace Options { + /** + * Provider-native page extraction. Both modes may incur per-row charges; full_page + * may retrieve web and news rows. + */ + export interface Extraction { + extraction_mode: 'highlights' | 'full_page'; + + full_page?: Extraction.FullPage; + } + + export namespace Extraction { + export interface FullPage { + extraction_formats?: Array<'html' | 'markdown'>; + } + } + } + } + + export interface SearchTavilyTarget { + provider: 'tavily'; + + options?: SearchTavilyTarget.Options; + } + + export namespace SearchTavilyTarget { + export interface Options { + /** + * Allow the provider to choose search parameters. May select a different billing + * tier; explicit caller values retain provider-native precedence. + */ + auto_parameters?: boolean; + + /** + * Provider excerpts per source, up to 500 characters each. + */ + chunks_per_source?: number; + + /** + * Require the quoted phrases in the query verbatim, bypassing semantic matches. + */ + exact_match?: boolean; + + /** + * Strictly filter non-matching languages. Requires `language`. + */ + filter_by_language?: boolean; + + /** + * Request the provider's generated answer. Returned as answer on the search + * response, independently of include_raw. + */ + include_answer?: boolean | 'basic' | 'advanced'; + + /** + * Native filter versus ranking boost semantics. Boost influences ranking rather + * than restricting results to the listed domains. Requires include_domains. + */ + include_domains_mode?: 'filter' | 'boost'; + + /** + * Favicon URL per result. + */ + include_favicon?: boolean; + + /** + * Describe each image. Needs include_images. + */ + include_image_descriptions?: boolean; + + /** + * Query-related images plus per-result images. + */ + include_images?: boolean; + + /** + * Request native full-page content. Defaults to markdown when omitted for this + * provider, False disables that native retrieval; it does not disable explicitly + * requested Kernel browser retrieval. + */ + include_raw_content?: boolean | 'markdown' | 'text'; + + /** + * ISO 639-1 code or English language name. Ranking boost unless + * filter_by_language. + */ + language?: string; + + /** + * Provider-native count. Lower-only alias for max_results. + */ + max_results?: number; + + /** + * Provider relevance and latency tier. Some tiers cannot be combined with native + * safe search; conflicts are described in warnings. + */ + search_depth?: 'advanced' | 'basic' | 'fast' | 'ultra-fast'; + + /** + * Provider corpus selector. Publication metadata depends on the selected topic. + */ + topic?: 'general' | 'news' | 'finance'; + } + } + + export interface SearchSerpAPITarget { + provider: 'serpapi'; + + options?: SearchSerpAPITarget.Options; + } + + export namespace SearchSerpAPITarget { + export interface Options { + /** + * SerpApi engine identifier. The Kernel integration currently supports google + * only. + */ + engine: string; + + /** + * Device profile used for the search. + */ + device?: 'desktop' | 'mobile' | 'tablet'; + + /** + * Google duplicate-content filter. + */ + filter?: 0 | 1; + + /** + * Two-letter Google country code. + */ + gl?: string; + + /** + * Google domain to search when using the google engine. + */ + google_domain?: string; + + /** + * Interface language code. + */ + hl?: string; + + /** + * Free-form geographic location used for localized results. + */ + location?: string; + + /** + * Google auto-correction filter. + */ + nfpr?: 0 | 1; + + /** + * When true, bypass SerpApi cached results when supported. + */ + no_cache?: boolean; + + /** + * Number of results requested from the search engine. + */ + num?: number; + + /** + * Safe-search setting for engines that support it. + */ + safe?: 'active' | 'off'; + + /** + * Zero-based result offset for pagination. + */ + start?: number; + + /** + * Google vertical search selector, such as images, video, news, or shopping. + */ + tbm?: string; + + /** + * Google time and search modifiers, including freshness filters. + */ + tbs?: string; + } + } +} + +export interface Request { + /** + * Primary search query. A provider-native multi-query option applies only to that + * provider; other providers in a fallback chain receive this query. + */ + query: string; + + /** + * Optional portable content retrieval. Pass true for defaults or an options + * object. Omission never starts Kernel browser work; provider-supplied content is + * still returned when available, including when requested through native options. + * Both inline and deferred retrieval use the same options schema. + */ + content?: true | Request.SearchContentOptions; + + /** + * ISO 3166-1 alpha-2 search locale preference. + */ + country?: string; + + /** + * Inclusive publication-date upper bound; must not precede start_date. If recency + * is also supplied, recency takes precedence with a warning. Unsupported or + * approximated filtering is reported, or rejected under strict_params. + */ + end_date?: string; + + /** + * Hostname exclusions, with the same best-effort/strict behavior as + * include_domains. Provider-specific combinations that cannot be represented are + * reported via warnings or rejected in strict mode. + */ + exclude_domains?: Array; + + /** + * Hostname inclusion preference, matching a hostname and its subdomains. Empty + * means unrestricted. Translated, emulated, or dropped with a warning according to + * provider capability unless strict_params is true. Native boost modes remain + * advisory and are identified in warnings. + */ + include_domains?: Array; + + /** + * Include untouched per-result payloads and the full serving-provider response in + * raw fields. Off by default; native top-level outputs such as answer remain + * available without it. + */ + include_raw?: boolean; + + /** + * BCP 47 search language preference. + */ + language?: string; + + /** + * Requested result count from 1 through 100. The effective count is clamped to the + * serving provider's cap with a warning. Effective native counts are the lower of + * this limit and supplied provider-native count aliases. Strict mode rejects + * unsupported counts. + */ + max_results?: number; + + /** + * Relative search window. Takes precedence over start_date/end_date with a warning + * if both are set. Provider-native recency behavior is retained, including + * documented hour-to-day widening. Unsupported filters are rejected only in strict + * mode. + */ + recency?: 'hour' | 'day' | 'week' | 'month' | 'year'; + + /** + * Optional safety preference. Omit to use provider defaults. Unsupported values + * are dropped with a warning unless strict_params is true. A search filter is not + * an authorization boundary. + */ + safe_search?: 'off' | 'moderate' | 'strict'; + + /** + * Inclusive publication-date lower bound. If recency is also supplied, recency + * takes precedence with a warning. Provider date semantics, precision, and + * unsupported filters are reported; unknown source dates are not fabricated or + * universally post-filtered. + */ + start_date?: string; + + /** + * Omitted strategy defaults to auto. + */ + strategy?: Strategy; + + /** + * When false, unsupported portable parameters are omitted and approximations are + * described in warnings. When true, every supplied portable parameter must be + * honored exactly. Requests that cannot be served with those parameters are + * rejected. This does not guarantee identical rankings or document timestamps + * across indexes. Authentication and project isolation are always enforced. + */ + strict_params?: boolean; + + /** + * Overall deadline across search attempts and inline retrieval. No new attempt + * starts after the deadline. Completed search results survive inline retrieval + * timeouts. + */ + timeout_ms?: number; +} + +export namespace Request { + export interface SearchContentOptions { + /** + * Invalid with source=provider. Supplying browser_id requires source=browser so + * the chosen identity is not bypassed. + */ + browser?: SearchContentOptions.Browser; + + format?: 'markdown' | 'text'; + + /** + * Maximum acceptable age of cached page content, measured from origin retrieval. 0 + * forces a live fetch. Governs the Kernel content cache, which is scoped to the + * caller organization and project and separated by retrieval context; fetches + * through a caller-supplied browser_id bypass that cache. Mapped to the provider + * freshness control when source is provider and the provider supports one; + * otherwise provider content age is reported as unknown via fetched_at. + */ + max_age_hours?: number; + + /** + * Per-result Unicode character limit after extraction. + */ + max_chars?: number; + + /** + * provider uses the search provider's native content retrieval; browser fetches + * each URL through a Kernel browser; auto prefers Kernel browser retrieval and + * falls back to provider-native content when browser retrieval is unavailable or + * unsuitable. Defaults to auto for both inline and deferred retrieval. Deferred + * provider retrieval requires post_hoc capability; an explicit provider source + * without it is a 400. Missing documents produce per-result unavailable outcomes, + * not request failures. + */ + source?: 'auto' | 'provider' | 'browser'; + + /** + * Per-result deadline including capacity acquisition, retrieval, and extraction. + * Also bounded by the overall request deadline. + */ + timeout_ms?: number; + } + + export namespace SearchContentOptions { + /** + * Invalid with source=provider. Supplying browser_id requires source=browser so + * the chosen identity is not bypassed. + */ + export interface Browser { + /** + * Existing browser session ID authorized for the caller and selected project. + * Reuses its cookies, proxy, and browser configuration. Kernel does not delete a + * caller-supplied browser. Render mode uses a temporary tab; website activity may + * still change shared cookies and storage. When omitted, Kernel obtains isolated + * browser capacity in the caller's account and releases it after retrieval. That + * capacity is not retained for later interaction. Existing browser quotas apply. + */ + browser_id?: string; + + /** + * Curl uses the browser HTTP stack without navigation or JavaScript execution. + * Render navigates a temporary page and extracts from its DOM. The selected mode + * is used for the retrieval. + */ + mode?: 'curl' | 'render'; + } + } +} + +export interface Result { + /** + * Kernel-generated identifier for this result. Stable only within the retained + * search; not standardized across providers. Provider-native IDs, when available, + * remain provider-specific raw fields. + */ + id: string; + + /** + * One-based position in the returned ranking. + */ + rank: number; + + /** + * Provider-returned URL, not assumed canonical. + */ + url: string; + + additional_snippets?: Array; + + /** + * Portable retrieval outcome, or native content supplied by the search provider. + * Identity fields remain on the enclosing result. Native excerpts are labeled + * excerpt rather than full_page. Omission never triggers browser retrieval. + */ + content?: Result.Content; + + /** + * Provider-supplied date or timestamp, preserving available precision. No + * publication date is fabricated. Retains the published field name. + */ + published_date?: string | null; + + /** + * Original provider result, included only with include_raw=true. Provider + * relevance scores are not normalized. Top-level provider data is available in + * Search.raw. + */ + raw?: unknown; + + snippet?: string | null; + + /** + * Provider source name or result URL hostname, when available. + */ + source?: string | null; + + title?: string | null; +} + +export namespace Result { + /** + * Portable retrieval outcome, or native content supplied by the search provider. + * Identity fields remain on the enclosing result. Native excerpts are labeled + * excerpt rather than full_page. Omission never triggers browser retrieval. + */ + export interface Content { + /** + * Ok means non-empty extracted content, not merely HTTP 200. Blocked includes + * detected challenges or access denials. Detection is best-effort, not a guarantee + * of page completeness. Error details are present for non-ok outcomes; text is + * present only on ok. + */ + status: 'ok' | 'unavailable' | 'blocked' | 'timeout' | 'unsupported_type' | 'extraction_failed' | 'error'; + + /** + * Kernel cache outcome. Provider-internal cache behavior may be unknown. + */ + cache_status?: 'hit' | 'miss' | 'bypass' | 'unknown'; + + /** + * Describes source coverage before max_chars truncation. Full_page means main-page + * content, not every dynamic element or linked page. + */ + completeness?: 'full_page' | 'excerpt' | 'unknown'; + + error?: Content.Error; + + /** + * Extraction version when Kernel transformed the input. + */ + extractor_version?: string; + + /** + * Origin retrieval time when known, not cache read time. + */ + fetched_at?: string | null; + + /** + * Final retrieval URL when known. + */ + final_url?: string; + + format?: 'markdown' | 'text'; + + /** + * Final target HTTP status when known. + */ + http_status?: number; + + /** + * Original retrieval method, including on cache hits. + */ + method?: 'provider' | 'browser_curl' | 'browser_render'; + + /** + * Extracted website content, untrusted, not instructions. Present only on + * status=ok. + */ + text?: string; + + /** + * Whether max_chars truncated the extracted content. + */ + truncated?: boolean; + } + + export namespace Content { + export interface Error { + /** + * Machine-readable retrieval failure code. + */ + code: string; + + /** + * Human-readable failure description. + */ + message: string; + + retryable: boolean; + } + } +} + +/** + * Retained search results and provider attempt history. + */ +export interface Search { + /** + * Search resource ID. Request tracing uses X-Request-Id. + */ + id: string; + + attempts: Array; + + /** + * Expiration of result IDs for deferred retrieval. Results expire 24 hours after + * search completion. + */ + expires_at: string; + + /** + * Concrete serving provider, never auto or fallback. + */ + provider: string; + + /** + * Echo of the query. Native multi-query inputs are visible in the selected + * strategy target and the optional raw response. + */ + query: string; + + results: Array; + + usage: Usage; + + warnings: Array; + + /** + * Provider-generated answer when requested (e.g. via Tavily include_answer or + * Perplexity). Preserved independently of include_raw. + */ + answer?: string; + + /** + * Full serving-provider response, including top-level metadata that does not + * belong to a result. Present only with include_raw=true; untrusted provider data. + */ + raw?: unknown; +} + +/** + * Typed provider selection and routing strategy. + */ +export type Strategy = + | Strategy.SearchAutoStrategy + | Strategy.SearchPinnedStrategy + | Strategy.SearchFallbackStrategy; + +export namespace Strategy { + export interface SearchAutoStrategy { + /** + * Let Kernel choose an eligible provider by capability fit. + */ + type: 'auto'; + + /** + * Conditions that advance to the next provider under auto routing or an explicit + * providers chain. Ignored when provider pins a single provider. error means a + * retryable provider failure, including rate limiting, not invalid caller input or + * caller quotas. empty means zero results after required filtering. An empty list + * disables fallback. If every attempt is empty or fails, the response is the first + * valid empty response with the full attempt trail, or a 502 if none succeeded. + */ + fallback_on?: Array<'error' | 'timeout' | 'empty'>; + + /** + * Provider targets available to auto routing, each paired with typed native + * options. Provider names must be unique. + */ + provider_options?: Array; + } + + export interface SearchPinnedStrategy { + /** + * Provider name paired with its typed native options. + */ + provider: SearchAPI.ProviderTarget; + + /** + * Use exactly the selected provider with no cross-provider fallback. + */ + type: 'pinned'; + } + + export interface SearchFallbackStrategy { + /** + * Ordered provider targets. Provider names must be unique. + */ + providers: Array; + + /** + * Try providers in order and advance when fallback_on matches the outcome. + */ + type: 'fallback'; + + /** + * Conditions that advance to the next provider under auto routing or an explicit + * providers chain. Ignored when provider pins a single provider. error means a + * retryable provider failure, including rate limiting, not invalid caller input or + * caller quotas. empty means zero results after required filtering. An empty list + * disables fallback. If every attempt is empty or fails, the response is the first + * valid empty response with the full attempt trail, or a 502 if none succeeded. + */ + fallback_on?: Array<'error' | 'timeout' | 'empty'>; + } +} + +export interface Usage { + /** + * Number of result URLs for which a Kernel browser retrieval was attempted, + * excluding cache-only hits. + */ + content_fetches: number; + + /** + * Number of result entries returned, including failed entries on the contents + * endpoint. + */ + results_count: number; + + /** + * Total customer charge in USD when billing data is available. + */ + cost?: number; +} + +export interface Warning { + /** + * Examples: param_unsupported, preference_unsupported, max_results_clamped, + * domains_truncated, recency_emulated, filter_emulated, date_filter_overridden, + * provider_ineligible, fallback_failed, content_partial. + */ + code: string; + + message: string; + + param?: string; + + provider?: string; + + result_id?: string; +} + +export interface SearchCreateParams { + /** + * Primary search query. A provider-native multi-query option applies only to that + * provider; other providers in a fallback chain receive this query. + */ + query: string; + + /** + * Optional portable content retrieval. Pass true for defaults or an options + * object. Omission never starts Kernel browser work; provider-supplied content is + * still returned when available, including when requested through native options. + * Both inline and deferred retrieval use the same options schema. + */ + content?: true | SearchCreateParams.SearchContentOptions; + + /** + * ISO 3166-1 alpha-2 search locale preference. + */ + country?: string; + + /** + * Inclusive publication-date upper bound; must not precede start_date. If recency + * is also supplied, recency takes precedence with a warning. Unsupported or + * approximated filtering is reported, or rejected under strict_params. + */ + end_date?: string; + + /** + * Hostname exclusions, with the same best-effort/strict behavior as + * include_domains. Provider-specific combinations that cannot be represented are + * reported via warnings or rejected in strict mode. + */ + exclude_domains?: Array; + + /** + * Hostname inclusion preference, matching a hostname and its subdomains. Empty + * means unrestricted. Translated, emulated, or dropped with a warning according to + * provider capability unless strict_params is true. Native boost modes remain + * advisory and are identified in warnings. + */ + include_domains?: Array; + + /** + * Include untouched per-result payloads and the full serving-provider response in + * raw fields. Off by default; native top-level outputs such as answer remain + * available without it. + */ + include_raw?: boolean; + + /** + * BCP 47 search language preference. + */ + language?: string; + + /** + * Requested result count from 1 through 100. The effective count is clamped to the + * serving provider's cap with a warning. Effective native counts are the lower of + * this limit and supplied provider-native count aliases. Strict mode rejects + * unsupported counts. + */ + max_results?: number; + + /** + * Relative search window. Takes precedence over start_date/end_date with a warning + * if both are set. Provider-native recency behavior is retained, including + * documented hour-to-day widening. Unsupported filters are rejected only in strict + * mode. + */ + recency?: 'hour' | 'day' | 'week' | 'month' | 'year'; + + /** + * Optional safety preference. Omit to use provider defaults. Unsupported values + * are dropped with a warning unless strict_params is true. A search filter is not + * an authorization boundary. + */ + safe_search?: 'off' | 'moderate' | 'strict'; + + /** + * Inclusive publication-date lower bound. If recency is also supplied, recency + * takes precedence with a warning. Provider date semantics, precision, and + * unsupported filters are reported; unknown source dates are not fabricated or + * universally post-filtered. + */ + start_date?: string; + + /** + * Omitted strategy defaults to auto. + */ + strategy?: Strategy; + + /** + * When false, unsupported portable parameters are omitted and approximations are + * described in warnings. When true, every supplied portable parameter must be + * honored exactly. Requests that cannot be served with those parameters are + * rejected. This does not guarantee identical rankings or document timestamps + * across indexes. Authentication and project isolation are always enforced. + */ + strict_params?: boolean; + + /** + * Overall deadline across search attempts and inline retrieval. No new attempt + * starts after the deadline. Completed search results survive inline retrieval + * timeouts. + */ + timeout_ms?: number; +} + +export namespace SearchCreateParams { + export interface SearchContentOptions { + /** + * Invalid with source=provider. Supplying browser_id requires source=browser so + * the chosen identity is not bypassed. + */ + browser?: SearchContentOptions.Browser; + + format?: 'markdown' | 'text'; + + /** + * Maximum acceptable age of cached page content, measured from origin retrieval. 0 + * forces a live fetch. Governs the Kernel content cache, which is scoped to the + * caller organization and project and separated by retrieval context; fetches + * through a caller-supplied browser_id bypass that cache. Mapped to the provider + * freshness control when source is provider and the provider supports one; + * otherwise provider content age is reported as unknown via fetched_at. + */ + max_age_hours?: number; + + /** + * Per-result Unicode character limit after extraction. + */ + max_chars?: number; + + /** + * provider uses the search provider's native content retrieval; browser fetches + * each URL through a Kernel browser; auto prefers Kernel browser retrieval and + * falls back to provider-native content when browser retrieval is unavailable or + * unsuitable. Defaults to auto for both inline and deferred retrieval. Deferred + * provider retrieval requires post_hoc capability; an explicit provider source + * without it is a 400. Missing documents produce per-result unavailable outcomes, + * not request failures. + */ + source?: 'auto' | 'provider' | 'browser'; + + /** + * Per-result deadline including capacity acquisition, retrieval, and extraction. + * Also bounded by the overall request deadline. + */ + timeout_ms?: number; + } + + export namespace SearchContentOptions { + /** + * Invalid with source=provider. Supplying browser_id requires source=browser so + * the chosen identity is not bypassed. + */ + export interface Browser { + /** + * Existing browser session ID authorized for the caller and selected project. + * Reuses its cookies, proxy, and browser configuration. Kernel does not delete a + * caller-supplied browser. Render mode uses a temporary tab; website activity may + * still change shared cookies and storage. When omitted, Kernel obtains isolated + * browser capacity in the caller's account and releases it after retrieval. That + * capacity is not retained for later interaction. Existing browser quotas apply. + */ + browser_id?: string; + + /** + * Curl uses the browser HTTP stack without navigation or JavaScript execution. + * Render navigates a temporary page and extracts from its DOM. The selected mode + * is used for the retrieval. + */ + mode?: 'curl' | 'render'; + } + } +} + +SearchResource.Contents = ContentsAPIContents; +SearchResource.Providers = Providers; + +export declare namespace SearchResource { + export { + type Attempt as Attempt, + type ProviderTarget as ProviderTarget, + type Request as Request, + type Result as Result, + type Search as Search, + type Strategy as Strategy, + type Usage as Usage, + type Warning as Warning, + type SearchCreateParams as SearchCreateParams, + }; + + export { + ContentsAPIContents as Contents, + type FetchRequest as FetchRequest, + type Response as Response, + type ContentFetchParams as ContentFetchParams, + }; + + export { + Providers as Providers, + type Provider as Provider, + type ProviderListResponse as ProviderListResponse, + type ProviderListParams as ProviderListParams, + }; +} diff --git a/src/resources/vaults/items.ts b/src/resources/vaults/items.ts index 02d4993d..af7c3b57 100644 --- a/src/resources/vaults/items.ts +++ b/src/resources/vaults/items.ts @@ -259,8 +259,10 @@ export interface AgentcardCheckoutAuthorization { /** * One-use processor-bound checkout preparation. Keep the approval page open - * through token handoff. The amount is display-only and does not constrain the - * merchant's eventual charge. + * through device handoff, including Adyen encryption. The amount is declared by + * the caller and does not constrain the merchant's eventual charge. Adyen device + * approval and browser Authorised responses are not capture or fulfillment + * evidence. */ export interface AgentcardCheckoutPreparation { browser_id: string; @@ -293,7 +295,13 @@ export interface AgentcardCheckoutPreparation { expires_at?: string; } -export type AgentcardPreparedProcessor = 'square' | 'braintree' | 'worldpay' | 'bambora' | 'mercado_pago'; +export type AgentcardPreparedProcessor = + | 'square' + | 'braintree' + | 'worldpay' + | 'bambora' + | 'mercado_pago' + | 'adyen'; /** * Authorize a Link card using its existing purchase specification. Use only after @@ -522,8 +530,10 @@ export namespace CardVaultItemState { /** * One-use processor-bound checkout preparation. Keep the approval page open - * through token handoff. The amount is display-only and does not constrain the - * merchant's eventual charge. + * through device handoff, including Adyen encryption. The amount is declared by + * the caller and does not constrain the merchant's eventual charge. Adyen device + * approval and browser Authorised responses are not capture or fulfillment + * evidence. */ preparation?: ItemsAPI.AgentcardCheckoutPreparation; @@ -997,8 +1007,8 @@ export interface FillVaultItemOperationResult { } /** - * Prepare an unused AgentCard card for a supported tokenization checkout. Deliver - * the returned approval URL and keep the approval page open. Poll the item until + * Prepare an unused AgentCard card for a supported checkout. Deliver the returned + * approval URL and keep the approval page open. Poll the item until * ready_to_submit, then submit native Pay before preparation.expires_at. Readiness * lasts at most 30 seconds. Unused preparations expire automatically. Preparations * are single-use even after failure or expiry; do not automatically retry and @@ -1006,7 +1016,7 @@ export interface FillVaultItemOperationResult { */ export interface PrepareCheckoutVaultItemOperationRequest { /** - * Required when preparing an unused AgentCard card for a supported tokenization + * Required when preparing an unused AgentCard card for a supported checkout * processor. Consent is bound to this browser and declared merchant origin, not a * tab. Wait for the item's ready_to_submit status before native Pay and submit * within its readiness deadline. Unused preparations expire automatically; every @@ -1083,7 +1093,7 @@ export namespace VaultCardFillField { } /** - * Required when preparing an unused AgentCard card for a supported tokenization + * Required when preparing an unused AgentCard card for a supported checkout * processor. Consent is bound to this browser and declared merchant origin, not a * tab. Wait for the item's ready_to_submit status before native Pay and submit * within its readiness deadline. Unused preparations expire automatically; every @@ -1096,8 +1106,8 @@ export interface VaultCheckoutContext { browser_id: string; /** - * Use production or sandbox for Square, Braintree and Worldpay; shared for Bambora - * and Mercado Pago. Shared endpoints do not establish test mode. Merchant + * Use production or sandbox for Square, Braintree, Worldpay and Adyen; shared for + * Bambora and Mercado Pago. Shared endpoints do not establish test mode. Merchant * credentials/configuration determine processor test mode, independently of the * AgentCard credential mode. */ @@ -1110,8 +1120,11 @@ export interface VaultCheckoutContext { merchant_origin: string; /** - * Tokenization processor. Omit for Square compatibility. Non-Square processors - * require multi-processor preparation enablement. + * Checkout processor. Omit for Square compatibility. Adyen supports fresh-card + * Sessions requests on Adyen hosts only. Use public dummy card fields, not vault + * aliases. The unique armed preparation is associated with the subsequent eligible + * request from this browser and declared merchant origin; competing preparations + * are rejected. */ psp?: AgentcardPreparedProcessor; } @@ -1791,7 +1804,7 @@ export declare namespace ItemPerformOperationParams { /** * Body param: Required when preparing an unused AgentCard card for a supported - * tokenization processor. Consent is bound to this browser and declared merchant + * checkout processor. Consent is bound to this browser and declared merchant * origin, not a tab. Wait for the item's ready_to_submit status before native Pay * and submit within its readiness deadline. Unused preparations expire * automatically; every preparation is single-use, including after failure or diff --git a/src/version.ts b/src/version.ts index cad2f126..36c76795 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION = '0.110.0'; // x-release-please-version +export const VERSION = '0.111.0'; // x-release-please-version diff --git a/tests/api-resources/auth/connections.test.ts b/tests/api-resources/auth/connections.test.ts index 23f871c8..b67db534 100644 --- a/tests/api-resources/auth/connections.test.ts +++ b/tests/api-resources/auth/connections.test.ts @@ -257,6 +257,7 @@ describe('resource connections', () => { }, proxy: { id: 'id', name: 'name' }, record_session: true, + skill_mode: 'enabled', }, { path: '/_stainless_unknown_path' }, ), diff --git a/tests/api-resources/search/contents.test.ts b/tests/api-resources/search/contents.test.ts new file mode 100644 index 00000000..124695cf --- /dev/null +++ b/tests/api-resources/search/contents.test.ts @@ -0,0 +1,22 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import Kernel from '@onkernel/sdk'; + +const client = new Kernel({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); + +describe('resource contents', () => { + // Mock server tests are disabled + test.skip('fetch', async () => { + const responsePromise = client.search.contents.fetch('srch_abc123', {}); + const rawResponse = await responsePromise.asResponse(); + expect(rawResponse).toBeInstanceOf(Response); + const response = await responsePromise; + expect(response).not.toBeInstanceOf(Response); + const dataAndResponse = await responsePromise.withResponse(); + expect(dataAndResponse.data).toBe(response); + expect(dataAndResponse.response).toBe(rawResponse); + }); +}); diff --git a/tests/api-resources/search/providers.test.ts b/tests/api-resources/search/providers.test.ts new file mode 100644 index 00000000..01ff0718 --- /dev/null +++ b/tests/api-resources/search/providers.test.ts @@ -0,0 +1,30 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import Kernel from '@onkernel/sdk'; + +const client = new Kernel({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); + +describe('resource providers', () => { + // Mock server tests are disabled + test.skip('list', async () => { + const responsePromise = client.search.providers.list(); + const rawResponse = await responsePromise.asResponse(); + expect(rawResponse).toBeInstanceOf(Response); + const response = await responsePromise; + expect(response).not.toBeInstanceOf(Response); + const dataAndResponse = await responsePromise.withResponse(); + expect(dataAndResponse.data).toBe(response); + expect(dataAndResponse.response).toBe(rawResponse); + }); + + // Mock server tests are disabled + test.skip('list: request options and params are passed correctly', async () => { + // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error + await expect( + client.search.providers.list({ slug: 'brave' }, { path: '/_stainless_unknown_path' }), + ).rejects.toThrow(Kernel.NotFoundError); + }); +}); diff --git a/tests/api-resources/search/search.test.ts b/tests/api-resources/search/search.test.ts new file mode 100644 index 00000000..c0b61a34 --- /dev/null +++ b/tests/api-resources/search/search.test.ts @@ -0,0 +1,77 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import Kernel from '@onkernel/sdk'; + +const client = new Kernel({ + apiKey: 'My API Key', + baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', +}); + +describe('resource search', () => { + // Mock server tests are disabled + test.skip('create: only required params', async () => { + const responsePromise = client.search.create({ query: 'x' }); + const rawResponse = await responsePromise.asResponse(); + expect(rawResponse).toBeInstanceOf(Response); + const response = await responsePromise; + expect(response).not.toBeInstanceOf(Response); + const dataAndResponse = await responsePromise.withResponse(); + expect(dataAndResponse.data).toBe(response); + expect(dataAndResponse.response).toBe(rawResponse); + }); + + // Mock server tests are disabled + test.skip('create: required and optional params', async () => { + const response = await client.search.create({ + query: 'x', + content: true, + country: 'se', + end_date: '2019-12-27', + exclude_domains: ['string'], + include_domains: ['string'], + include_raw: true, + language: 'language', + max_results: 1, + recency: 'hour', + safe_search: 'off', + start_date: '2019-12-27', + strategy: { + type: 'auto', + fallback_on: ['error'], + provider_options: [ + { + provider: 'brave', + options: { + count: 1, + extra_snippets: true, + goggles: 'goggles', + goggles_id: 'goggles_id', + include_fetch_metadata: true, + offset: 0, + operators: 'operators', + result_filter: 'result_filter', + search_lang: 'search_lang', + spellcheck: true, + ui_lang: 'ui_lang', + units: 'metric', + }, + }, + ], + }, + strict_params: true, + timeout_ms: 1000, + }); + }); + + // Mock server tests are disabled + test.skip('retrieve', async () => { + const responsePromise = client.search.retrieve('srch_abc123'); + const rawResponse = await responsePromise.asResponse(); + expect(rawResponse).toBeInstanceOf(Response); + const response = await responsePromise; + expect(response).not.toBeInstanceOf(Response); + const dataAndResponse = await responsePromise.withResponse(); + expect(dataAndResponse.data).toBe(response); + expect(dataAndResponse.response).toBe(rawResponse); + }); +});