@seclai/sdk 1.9.0 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/versions.ts","../src/errors.ts","../src/auth.ts","../src/client.ts"],"sourcesContent":["/**\n * Dated API versions known to this release, for use with the `apiVersion`\n * client option.\n *\n * The set is open: the API adds versions without an SDK release, and\n * {@link ApiVersion} widens to `string`, so a date newer than this release\n * knows about can be passed directly. Treat these as convenience constants\n * rather than an exhaustive list — `getApiVersion()` reports what the server\n * actually supports.\n */\nexport const SeclaiApiVersion = {\n V2026_07_01: \"2026-07-01\",\n V2026_07_27: \"2026-07-27\",\n V2026_08_03: \"2026-08-03\",\n V2026_08_21: \"2026-08-21\",\n V2026_09_28: \"2026-09-28\",\n V2026_09_30: \"2026-09-30\",\n V2026_10_03: \"2026-10-03\",\n V2026_10_05: \"2026-10-05\",\n V2026_10_13: \"2026-10-13\",\n V2026_10_16: \"2026-10-16\",\n V2026_10_18: \"2026-10-18\",\n V2026_10_19: \"2026-10-19\",\n V2026_10_21: \"2026-10-21\",\n V2026_10_28: \"2026-10-28\",\n V2026_11_02: \"2026-11-02\",\n V2026_11_04: \"2026-11-04\",\n /** Baseline applied to an unpinned, header-less caller. */\n Default: \"2026-07-01\",\n /** Newest version known to this SDK release. May lag the server. */\n Latest: \"2026-11-04\",\n} as const;\n\n/**\n * A dated API version. Known values autocomplete; any `YYYY-MM-DD` string still\n * typechecks, but one this release was not built against is rejected at\n * construction unless `allowUnknownApiVersion` is set.\n */\nexport type ApiVersion =\n | (typeof SeclaiApiVersion)[keyof typeof SeclaiApiVersion]\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** Every version this release was built against, oldest first. */\nexport const KNOWN_API_VERSIONS: readonly string[] = Object.entries(SeclaiApiVersion)\n .filter(([k]) => k.startsWith(\"V\"))\n .map(([, v]) => v);\n","/**\n * @module\n *\n * Error classes thrown by the Seclai SDK.\n *\n * All errors extend {@link SeclaiError}, so a single `catch (err instanceof SeclaiError)`\n * handles every SDK error. Narrow to more specific subclasses for finer handling.\n */\n\nimport type { AgentRunResponse } from \"./types\";\n\n/** Base error class for the Seclai SDK. */\nexport class SeclaiError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SeclaiError\";\n }\n}\n\n/** Thrown when the SDK is misconfigured (for example, missing API key). */\nexport class SeclaiConfigurationError extends SeclaiError {\n constructor(message: string) {\n super(message);\n this.name = \"SeclaiConfigurationError\";\n }\n}\n\n/**\n * Thrown when the API returns a non-success status code.\n *\n * @remarks\n * Use {@link SeclaiAPIValidationError} for HTTP 422 validation errors.\n */\nexport class SeclaiAPIStatusError extends SeclaiError {\n /** HTTP status code returned by the API. */\n public readonly statusCode: number;\n /** HTTP method used for the request. */\n public readonly method: string;\n /** Full request URL. */\n public readonly url: string;\n /** Best-effort response body text (if available). */\n public readonly responseText: string | undefined;\n\n constructor(opts: {\n /** Human-readable error message. */\n message: string;\n statusCode: number;\n method: string;\n url: string;\n responseText: string | undefined;\n }) {\n super(opts.message);\n this.name = \"SeclaiAPIStatusError\";\n this.statusCode = opts.statusCode;\n this.method = opts.method;\n this.url = opts.url;\n this.responseText = opts.responseText;\n }\n}\n\n/**\n * Thrown when the API returns a validation error response (typically HTTP 422).\n *\n * The `validationError` field contains the decoded validation payload when available.\n */\nexport class SeclaiAPIValidationError extends SeclaiAPIStatusError {\n /** Parsed validation error payload (best-effort). */\n public readonly validationError: unknown;\n\n constructor(opts: {\n message: string;\n statusCode: number;\n method: string;\n url: string;\n responseText: string | undefined;\n validationError: unknown;\n }) {\n super(opts);\n this.name = \"SeclaiAPIValidationError\";\n this.validationError = opts.validationError;\n }\n}\n\n/**\n * Thrown when a streaming operation fails (e.g. stream ends unexpectedly), or\n * when a run helper stops waiting before the run finished.\n */\nexport class SeclaiStreamingError extends SeclaiError {\n /** The run ID associated with the failed stream, when available. */\n public readonly runId: string | undefined;\n /**\n * Set by `runStreamingAgentAndWait()` and `runAgentAndPoll()` to the latest\n * run they had, if any (when it has `result_reported_at` set, its `output`\n * is the answer). The run may still be in progress, and can still fail.\n */\n public readonly run: AgentRunResponse | undefined;\n\n constructor(message: string, runId?: string, run?: AgentRunResponse) {\n super(message);\n this.name = \"SeclaiStreamingError\";\n this.runId = runId;\n this.run = run;\n }\n}\n","/**\n * @module\n *\n * SSO credential resolution: config file parsing, token caching, and automatic\n * token refresh against AWS Cognito.\n *\n * @internal — not part of the public API surface. Consumed by {@link Seclai}.\n */\nimport type { FetchLike } from \"./client\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Resolved SSO profile settings. */\nexport interface SsoProfile {\n ssoAccountId?: string | undefined;\n ssoRegion: string;\n ssoClientId: string;\n ssoDomain: string;\n}\n\n/** Contents of a single SSO cache file. */\nexport interface SsoCacheEntry {\n accessToken: string;\n refreshToken?: string;\n idToken?: string | undefined;\n expiresAt: string; // ISO-8601\n clientId: string;\n region: string;\n cognitoDomain: string;\n}\n\n// ─── Constants ───────────────────────────────────────────────────────────────\n\nconst DEFAULT_CONFIG_DIR = \".seclai\";\nconst SSO_CACHE_DIR = \"sso/cache\";\nconst CONFIG_FILE = \"config\";\nconst EXPIRY_BUFFER_MS = 30_000; // 30 seconds\nconst DEFAULT_API_KEY_HEADER = \"x-api-key\";\n\n/** Default SSO domain (production Cognito). Override with `SECLAI_SSO_DOMAIN` or config file. */\nexport const DEFAULT_SSO_DOMAIN = \"auth.seclai.com\";\n/** Default SSO client ID (production public client). Override with `SECLAI_SSO_CLIENT_ID` or config file. */\nexport const DEFAULT_SSO_CLIENT_ID = \"4bgf8v9qmc5puivbaqon9n5lmr\";\n/** Default SSO region. Override with `SECLAI_SSO_REGION` or config file. */\nexport const DEFAULT_SSO_REGION = \"us-west-2\";\n\n// ─── Environment helpers ─────────────────────────────────────────────────────\n\nfunction getEnv(name: string): string | undefined {\n const p = (globalThis as any)?.process;\n return p?.env?.[name];\n}\n\nfunction getHomeDir(): string | undefined {\n const p = (globalThis as any)?.process;\n return p?.env?.HOME ?? p?.env?.USERPROFILE;\n}\n\n// ─── SHA-1 hash ──────────────────────────────────────────────────────────────\n\nasync function sha1Hex(input: string): Promise<string> {\n // Prefer Node.js crypto when available\n try {\n // @ts-expect-error -- resolved at runtime; no @types/node in this package\n const { createHash } = await import(\"node:crypto\");\n return createHash(\"sha1\").update(input).digest(\"hex\");\n } catch {\n // Fall back to Web Crypto API\n const encoded = new TextEncoder().encode(input);\n const buffer = await crypto.subtle.digest(\"SHA-1\", encoded);\n return Array.from(new Uint8Array(buffer))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n }\n}\n\n/**\n * Compute the cache filename for a given domain + clientId.\n *\n * @param domain - The Cognito domain (e.g. `\"auth.example.com\"`).\n * @param clientId - The Cognito app client ID.\n * @returns SHA-1 hex digest of `\"domain|clientId\"`.\n */\nexport async function cacheFileName(domain: string, clientId: string): Promise<string> {\n return sha1Hex(`${domain}|${clientId}`);\n}\n\n// ─── INI parser ──────────────────────────────────────────────────────────────\n\n/**\n * Minimal INI parser matching AWS config format:\n * - `[default]` section\n * - `[profile <name>]` sections\n * - `key = value` pairs\n * - Lines starting with `#` or `;` are comments\n *\n * @param content - Raw INI file content.\n * @returns Map of section names to key-value pairs.\n */\nexport function parseIni(content: string): Record<string, Record<string, string>> {\n const sections: Record<string, Record<string, string>> = {};\n let currentSection: string | null = null;\n\n for (const rawLine of content.split(/\\r?\\n/)) {\n const line = rawLine.trim();\n\n if (!line || line.startsWith(\"#\") || line.startsWith(\";\")) continue;\n\n const sectionMatch = line.match(/^\\[(.+)\\]$/);\n if (sectionMatch) {\n const raw = sectionMatch[1]!.trim();\n // `[default]` stays as \"default\", `[profile foo]` becomes \"foo\"\n currentSection = raw.startsWith(\"profile \")\n ? raw.slice(\"profile \".length).trim()\n : raw;\n sections[currentSection] ??= {};\n continue;\n }\n\n if (currentSection !== null) {\n const eqIdx = line.indexOf(\"=\");\n if (eqIdx > 0) {\n const key = line.slice(0, eqIdx).trim();\n const value = line.slice(eqIdx + 1).trim();\n sections[currentSection]![key] = value;\n }\n }\n }\n\n return sections;\n}\n\n// ─── File system (Node.js only) ──────────────────────────────────────────────\n\ninterface FsModule {\n readFileSync(path: string, encoding: string): string;\n writeFileSync(path: string, data: string, options?: { mode?: number }): void;\n mkdirSync(path: string, options?: { recursive?: boolean; mode?: number }): void;\n existsSync(path: string): boolean;\n unlinkSync(path: string): void;\n renameSync(oldPath: string, newPath: string): void;\n}\n\ninterface PathModule {\n join(...parts: string[]): string;\n}\n\nlet _fs: FsModule | null = null;\nlet _path: PathModule | null = null;\n\nasync function getFs(): Promise<FsModule> {\n if (!_fs) {\n // @ts-expect-error -- resolved at runtime; no @types/node in this package\n _fs = (await import(\"node:fs\")) as unknown as FsModule;\n }\n return _fs;\n}\n\nasync function getPath(): Promise<PathModule> {\n if (!_path) {\n // @ts-expect-error -- resolved at runtime; no @types/node in this package\n _path = (await import(\"node:path\")) as unknown as PathModule;\n }\n return _path;\n}\n\n// ─── Config dir resolution ───────────────────────────────────────────────────\n\n/**\n * Resolve the config directory path.\n *\n * @param override - Explicit directory path (highest priority).\n * @returns Resolved absolute path to the config directory.\n * @throws {Error} If the home directory cannot be determined and no override is provided.\n */\nexport async function resolveConfigDir(override?: string): Promise<string> {\n if (override) return override;\n\n const envDir = getEnv(\"SECLAI_CONFIG_DIR\");\n if (envDir) return envDir;\n\n const home = getHomeDir();\n if (!home) {\n throw new Error(\"Cannot determine home directory. Set SECLAI_CONFIG_DIR.\");\n }\n\n const pathMod = await getPath();\n return pathMod.join(home, DEFAULT_CONFIG_DIR);\n}\n\n// ─── Profile resolution ─────────────────────────────────────────────────────\n\n/**\n * Load and resolve an SSO profile from the config file.\n * Non-default profiles inherit unset keys from `[default]`.\n * All profiles fall back to built-in defaults and environment variable overrides.\n *\n * **Node.js only** — this function uses `node:fs` and `node:path` internally\n * and will throw in browser/edge-worker runtimes.\n *\n * @param configDir - Resolved config directory path.\n * @param profileName - Profile name to look up (`\"default\"` or a named profile).\n * @returns The resolved profile. Always returns a valid profile using built-in defaults.\n */\nexport async function loadSsoProfile(\n configDir: string,\n profileName: string,\n): Promise<SsoProfile> {\n const fs = await getFs();\n const pathMod = await getPath();\n\n let merged: Record<string, string> = {};\n\n const configPath = pathMod.join(configDir, CONFIG_FILE);\n if (fs.existsSync(configPath)) {\n const content = fs.readFileSync(configPath, \"utf-8\");\n const sections = parseIni(content);\n\n const defaultSection = sections[\"default\"] ?? {};\n const profileSection = profileName === \"default\" ? defaultSection : sections[profileName];\n\n if (profileSection) {\n merged = profileName === \"default\" ? profileSection : { ...defaultSection, ...profileSection };\n }\n }\n\n // Environment variables override config file values\n const ssoDomain = getEnv(\"SECLAI_SSO_DOMAIN\") ?? merged[\"sso_domain\"] ?? DEFAULT_SSO_DOMAIN;\n const ssoClientId = getEnv(\"SECLAI_SSO_CLIENT_ID\") ?? merged[\"sso_client_id\"] ?? DEFAULT_SSO_CLIENT_ID;\n const ssoRegion = getEnv(\"SECLAI_SSO_REGION\") ?? merged[\"sso_region\"] ?? DEFAULT_SSO_REGION;\n const ssoAccountId = merged[\"sso_account_id\"] || undefined;\n\n return { ssoAccountId, ssoRegion, ssoClientId, ssoDomain };\n}\n\n// ─── Cache I/O ───────────────────────────────────────────────────────────────\n\n/**\n * Read a cached SSO token from disk.\n *\n * @param configDir - Resolved config directory path.\n * @param profile - SSO profile (used to derive the cache filename).\n * @returns The cached entry, or `null` if not found or unreadable.\n */\n/** Resolve the full path to a profile's SSO cache file. */\nasync function resolveCachePath(\n configDir: string,\n profile: SsoProfile,\n): Promise<string> {\n const pathMod = await getPath();\n const hash = await cacheFileName(profile.ssoDomain, profile.ssoClientId);\n return pathMod.join(configDir, SSO_CACHE_DIR, `${hash}.json`);\n}\n\nexport async function readSsoCache(\n configDir: string,\n profile: SsoProfile,\n): Promise<SsoCacheEntry | null> {\n const fs = await getFs();\n\n const cachePath = await resolveCachePath(configDir, profile);\n\n if (!fs.existsSync(cachePath)) return null;\n\n try {\n const raw = fs.readFileSync(cachePath, \"utf-8\");\n return JSON.parse(raw) as SsoCacheEntry;\n } catch {\n return null;\n }\n}\n\n/**\n * Write a cached SSO token to disk atomically.\n * Creates the cache directory if it doesn't exist.\n *\n * @param configDir - Resolved config directory path.\n * @param profile - SSO profile (used to derive the cache filename).\n * @param entry - Token data to persist.\n */\nexport async function writeSsoCache(\n configDir: string,\n profile: SsoProfile,\n entry: SsoCacheEntry,\n): Promise<void> {\n const fs = await getFs();\n const pathMod = await getPath();\n\n const cacheDir = pathMod.join(configDir, SSO_CACHE_DIR);\n fs.mkdirSync(cacheDir, { recursive: true, mode: 0o700 });\n\n const cachePath = await resolveCachePath(configDir, profile);\n const tmpPath = `${cachePath}.tmp`;\n\n fs.writeFileSync(tmpPath, JSON.stringify(entry, null, 2), { mode: 0o600 });\n // On Windows, renameSync fails if destination exists — delete first (best-effort)\n if (fs.existsSync(cachePath)) {\n try { fs.unlinkSync(cachePath); } catch { /* let renameSync throw if needed */ }\n }\n fs.renameSync(tmpPath, cachePath);\n}\n\n/**\n * Delete a cached SSO token file.\n *\n * @param configDir - Resolved config directory path.\n * @param profile - SSO profile (used to derive the cache filename).\n */\nexport async function deleteSsoCache(\n configDir: string,\n profile: SsoProfile,\n): Promise<void> {\n const fs = await getFs();\n\n const cachePath = await resolveCachePath(configDir, profile);\n\n if (fs.existsSync(cachePath)) {\n fs.unlinkSync(cachePath);\n }\n}\n\n// ─── Token validation ────────────────────────────────────────────────────────\n\n/**\n * Check if a cached token is still valid (with 30s buffer).\n *\n * @param entry - The cached token entry to check.\n * @returns `true` if the token expires more than 30 seconds in the future.\n */\nexport function isTokenValid(entry: SsoCacheEntry): boolean {\n const expiresAt = new Date(entry.expiresAt).getTime();\n return Date.now() + EXPIRY_BUFFER_MS < expiresAt;\n}\n\n// ─── Token refresh ───────────────────────────────────────────────────────────\n\n/**\n * Refresh an access token using a Cognito refresh_token grant.\n *\n * @param profile - SSO profile with Cognito domain and client ID.\n * @param refreshTokenValue - The refresh token to exchange.\n * @param fetcher - A `fetch`-compatible function for making HTTP requests.\n * @returns A fresh {@link SsoCacheEntry} with the new tokens.\n * @throws {Error} If the Cognito token endpoint returns a non-OK status.\n */\nexport async function refreshToken(\n profile: SsoProfile,\n refreshTokenValue: string,\n fetcher: FetchLike,\n): Promise<SsoCacheEntry> {\n const tokenUrl = `https://${profile.ssoDomain}/oauth2/token`;\n\n const body = new URLSearchParams({\n grant_type: \"refresh_token\",\n client_id: profile.ssoClientId,\n refresh_token: refreshTokenValue,\n });\n\n const response = await fetcher(tokenUrl, {\n method: \"POST\",\n headers: { \"content-type\": \"application/x-www-form-urlencoded\" },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n throw new Error(`Token refresh failed (HTTP ${response.status}): ${text}`);\n }\n\n const data = (await response.json()) as {\n access_token: string;\n id_token?: string;\n refresh_token?: string;\n expires_in: number;\n };\n\n const expiresAt = new Date(Date.now() + data.expires_in * 1000).toISOString();\n\n return {\n accessToken: data.access_token,\n refreshToken: data.refresh_token ?? refreshTokenValue,\n idToken: data.id_token ?? undefined,\n expiresAt,\n clientId: profile.ssoClientId,\n region: profile.ssoRegion,\n cognitoDomain: profile.ssoDomain,\n };\n}\n\n// ─── Credential chain resolver ───────────────────────────────────────────────\n\n/** Options for resolving the credential chain. */\nexport interface CredentialChainOptions {\n /** Explicit API key (highest priority). */\n apiKey?: string | undefined;\n /** Explicit static bearer token. */\n accessToken?: string | undefined;\n /** Dynamic bearer token provider. */\n accessTokenProvider?: (() => string | Promise<string>) | undefined;\n /** Name of the profile from ~/.seclai/config. */\n profile?: string | undefined;\n /** Override config directory path. */\n configDir?: string | undefined;\n /** Whether to auto-refresh expired SSO tokens. Defaults to true. */\n autoRefresh?: boolean | undefined;\n /** Account ID override (takes precedence over profile's sso_account_id). */\n accountId?: string | undefined;\n /** Header name for API key auth. */\n apiKeyHeader?: string | undefined;\n /** fetch implementation for token refresh. */\n fetch?: FetchLike | undefined;\n}\n\n/**\n * Resolved authentication state used throughout the client lifecycle.\n * Created once by {@link resolveCredentialChain} and passed to\n * {@link resolveAuthHeaders} on every request.\n */\nexport interface AuthState {\n mode: \"apiKey\" | \"bearerStatic\" | \"bearerProvider\" | \"sso\";\n apiKey?: string;\n apiKeyHeader: string;\n accessToken?: string;\n accessTokenProvider?: () => string | Promise<string>;\n accountId?: string | undefined;\n ssoProfile?: SsoProfile;\n configDir?: string;\n autoRefresh: boolean;\n fetcher?: FetchLike | undefined;\n /** @internal Coalesces concurrent SSO token refresh attempts. */\n _refreshPromise?: Promise<string> | undefined;\n}\n\n/**\n * Resolve the credential chain and return an AuthState.\n * This is called once at client construction time.\n *\n * Resolution order:\n * 1. Explicit `apiKey` option\n * 2. Explicit `accessToken` option\n * 3. Explicit `accessTokenProvider` option\n * 4. `SECLAI_API_KEY` environment variable\n * 5. SSO profile from `~/.seclai/config`\n *\n * @param opts - Credential chain options.\n * @returns Resolved authentication state.\n * @throws {Error} If no credentials are found.\n */\nexport async function resolveCredentialChain(\n opts: CredentialChainOptions,\n): Promise<AuthState> {\n const apiKeyHeader = opts.apiKeyHeader ?? DEFAULT_API_KEY_HEADER;\n\n // 1. Explicit apiKey option\n if (opts.apiKey) {\n return {\n mode: \"apiKey\",\n apiKey: opts.apiKey,\n apiKeyHeader,\n accountId: opts.accountId,\n autoRefresh: false,\n };\n }\n\n // 2. Explicit accessToken (mutual exclusion already checked by caller)\n if (opts.accessToken) {\n return {\n mode: \"bearerStatic\",\n accessToken: opts.accessToken,\n apiKeyHeader,\n accountId: opts.accountId,\n autoRefresh: false,\n };\n }\n\n // 3. Explicit accessTokenProvider\n if (opts.accessTokenProvider) {\n return {\n mode: \"bearerProvider\",\n accessTokenProvider: opts.accessTokenProvider,\n apiKeyHeader,\n accountId: opts.accountId,\n autoRefresh: false,\n };\n }\n\n // 4. SECLAI_API_KEY env var\n const envApiKey = getEnv(\"SECLAI_API_KEY\");\n if (envApiKey) {\n return {\n mode: \"apiKey\",\n apiKey: envApiKey,\n apiKeyHeader,\n accountId: opts.accountId,\n autoRefresh: false,\n };\n }\n\n // 5. Profile-based SSO resolution\n try {\n const configDir = await resolveConfigDir(opts.configDir);\n const profileName = opts.profile ?? getEnv(\"SECLAI_PROFILE\") ?? \"default\";\n const ssoProfile = await loadSsoProfile(configDir, profileName);\n\n return {\n mode: \"sso\",\n apiKeyHeader,\n accountId: opts.accountId ?? ssoProfile.ssoAccountId,\n ssoProfile,\n configDir,\n autoRefresh: opts.autoRefresh !== false,\n fetcher: opts.fetch,\n };\n } catch {\n // Config dir not found — fall through\n }\n\n // 6. Nothing found\n throw new Error(\n \"Missing credentials. Provide apiKey, accessToken, set SECLAI_API_KEY, or run `seclai auth login`.\",\n );\n}\n\n/**\n * Resolve authentication headers from the current AuthState.\n * Called per-request to handle dynamic token providers and SSO cache refresh.\n *\n * @param state - The resolved authentication state.\n * @returns Headers object with the appropriate auth header(s) set.\n */\nexport async function resolveAuthHeaders(\n state: AuthState,\n): Promise<Record<string, string>> {\n const headers: Record<string, string> = {};\n\n switch (state.mode) {\n case \"apiKey\":\n headers[state.apiKeyHeader] = state.apiKey!;\n break;\n\n case \"bearerStatic\":\n headers[\"authorization\"] = `Bearer ${state.accessToken!}`;\n break;\n\n case \"bearerProvider\": {\n const token = await Promise.resolve(state.accessTokenProvider!());\n headers[\"authorization\"] = `Bearer ${token}`;\n break;\n }\n\n case \"sso\": {\n const token = await resolveSsoToken(state);\n headers[\"authorization\"] = `Bearer ${token}`;\n break;\n }\n }\n\n if (state.accountId) {\n headers[\"x-account-id\"] = state.accountId;\n }\n\n return headers;\n}\n\n/** Resolve a valid SSO token, refreshing from cache if needed. */\nasync function resolveSsoToken(state: AuthState): Promise<string> {\n const profile = state.ssoProfile!;\n const configDir = state.configDir!;\n\n const cached = await readSsoCache(configDir, profile);\n\n if (cached && isTokenValid(cached)) {\n return cached.accessToken;\n }\n\n if (cached?.refreshToken && state.autoRefresh) {\n // Coalesce concurrent refresh attempts\n if (state._refreshPromise) {\n return state._refreshPromise;\n }\n\n const fetcher = state.fetcher ?? (globalThis.fetch as FetchLike | undefined);\n if (!fetcher) {\n throw new Error(\"No fetch implementation available for token refresh.\");\n }\n\n state._refreshPromise = (async () => {\n try {\n const refreshed = await refreshToken(profile, cached.refreshToken!, fetcher);\n await writeSsoCache(configDir, profile, refreshed);\n return refreshed.accessToken;\n } finally {\n state._refreshPromise = undefined;\n }\n })();\n return state._refreshPromise;\n }\n\n throw new Error(\n `SSO token expired. Run \\`seclai auth login\\` to re-authenticate.`,\n );\n}\n","/**\n * @module\n *\n * Main SDK client for the Seclai API.\n *\n * Exports the {@link Seclai} class which provides typed convenience methods for\n * every API endpoint, plus low-level {@link Seclai.request | request()} and\n * {@link Seclai.requestRaw | requestRaw()} escape hatches, streaming helpers,\n * and automatic pagination.\n */\nimport {\n SeclaiAPIStatusError,\n SeclaiAPIValidationError,\n SeclaiConfigurationError,\n SeclaiError,\n SeclaiStreamingError,\n} from \"./errors\";\nimport type { ApiVersion } from \"./versions\";\nimport { KNOWN_API_VERSIONS } from \"./versions\";\nimport type { AuthState } from \"./auth\";\nimport { resolveCredentialChain, resolveAuthHeaders } from \"./auth\";\nimport type {\n AgentRunEvent,\n AddEmailDomainInput,\n AgentAttachmentRefsApiResponse,\n AcceptedAttachmentsResponse,\n SetAcceptedAttachmentsInput,\n ContentAttachmentsListResponse,\n ContentAttachmentDetailResponse,\n EmailSourceRejectionListResponse,\n AgentCallerApiResponse,\n AgentDefinitionImportErrorResponse,\n AgentDefinitionResponse,\n AgentEmailOptOutListResponse,\n AgentExportResponse,\n AgentImportPreviewRequest,\n AgentImportPreviewResponse,\n AgentListResponse,\n AgentRunListResponse,\n AgentRunRequest,\n AgentRunResponse,\n AgentRunStreamRequest,\n AgentSummaryResponse,\n AgentUsingCloudDriveResponse,\n CloudDriveProviderResponse,\n CloudDriveRejectionResponse,\n CloudDriveResponse,\n CloudDriveUpdateRequest,\n EmbeddingModelListResponse,\n ListSourceContentsOptions,\n RerankerModelListResponse,\n SourceContentStatusListResponse,\n SourceContentStatusResponse,\n AgentTraceSearchRequest,\n AgentTraceSearchResponse,\n AiAssistantAcceptRequest,\n AiAssistantAcceptResponse,\n AiAssistantFeedbackRequest,\n AiAssistantFeedbackResponse,\n AiAssistantGenerateRequest,\n AiAssistantGenerateResponse,\n AiConversationHistoryResponse,\n AddCommentRequest,\n AddConversationTurnRequest,\n BlockEmailSenderRequest,\n BlockedEmailSenderListResponse,\n BlockedEmailSenderResponse,\n CancelQueuedRunsResponse,\n ChangeStatusRequest,\n CompatibleRunListResponse,\n CompactionTestResponse,\n ContentDetailResponse,\n ContentEmbeddingsListResponse,\n ContentFileUploadResponse,\n CreateAgentRequest,\n CreateAlertConfigRequest,\n CreateEvaluationCriteriaRequest,\n CreateEvaluationResultRequest,\n CreateExportRequest,\n CreateKnowledgeBaseBody,\n CreateMemoryBankBody,\n CreateSolutionRequest,\n CreateSourceBody,\n DmarcSummaryResponse,\n EmailDomainResponse,\n EmailDomainsListResponse,\n EmailTriggerConfigResponse,\n EstimateExportRequest,\n EstimateExportResponse,\n EvaluationCriteriaResponse,\n EvaluationCriteriaListResponse,\n ApiVersionResponse,\n AlertDetailResponse,\n AlertCommentResponse,\n AlertSubscriberResponse,\n UnreadCountResponse,\n ModelRecommendationsResponse,\n ModelRecommendationResponse,\n ExperimentListResponse,\n ExperimentSummaryResponse,\n ExperimentDetailResponse,\n CreateExperimentResponse,\n CancelExperimentResponse,\n SearchResponse,\n SearchResultResponse,\n OkResponse,\n AlertResponse,\n AlertConfigResponse,\n ModelAlertResponse,\n AlertListResponse,\n AlertConfigListResponse,\n ModelAlertListResponse,\n EvaluationResultListResponse,\n EvaluationResultResponse,\n EvaluationResultSummaryResponse,\n EvaluationResultWithCriteriaListResponse,\n EvaluationRunSummaryListResponse,\n ExportListResponse,\n ExportResponse,\n FileUploadResponse,\n GenerateAgentStepsRequest,\n GenerateAgentStepsResponse,\n GenerateStepConfigRequest,\n GenerateStepConfigResponse,\n GovernanceAiAcceptResponse,\n GovernanceAiAssistantRequest,\n GovernanceAiAssistantResponse,\n GovernanceConversationResponse,\n InboundEmailRejectionResponse,\n InboundEmailStatusResponse,\n InlineTextReplaceRequest,\n InlineTextUploadRequest,\n KnowledgeBaseListResponse,\n KnowledgeBaseResponse,\n LinkResourcesRequest,\n ListOptions,\n MarkAiSuggestionRequest,\n MarkConversationTurnRequest,\n MemoryBankAcceptRequest,\n MemoryBankAiAssistantRequest,\n MemoryBankAiAssistantResponse,\n MemoryBankLastConversationResponse,\n MeResponse,\n MemoryBankListResponse,\n MemoryBankResponse,\n NonManualEvaluationSummaryResponse,\n OrganizationAlertPreferenceListResponse,\n OrganizationAlertPreferenceResponse,\n PlaygroundCreateRequest,\n CreateExperimentInput,\n PromptModelResponse,\n ProviderGroupResponse,\n RemoveEmailDomainResponse,\n ResumeInboundResponse,\n SendTestEmailResponse,\n SetAutoBlockModeRequest,\n SetEmailTriggerConfigRequest,\n SolutionConversationResponse,\n SolutionListResponse,\n SolutionResponse,\n SortableListOptions,\n SourceEmbeddingMigrationResponse,\n SourceListResponse,\n SourceResponse,\n StandaloneTestCompactionRequest,\n StartSourceEmbeddingMigrationRequest,\n TestCompactionRequest,\n TestDraftEvaluationRequest,\n TestDraftEvaluationResponse,\n UnlinkResourcesRequest,\n UpdateAgentDefinitionRequest,\n UpdateAgentRequest,\n UpdateAlertConfigRequest,\n UpdateEvaluationCriteriaRequest,\n UpdateKnowledgeBaseBody,\n UpdateMemoryBankBody,\n UpdateOrganizationAlertPreferenceRequest,\n UpdateSolutionRequest,\n UpdateSourceBody,\n UploadAgentInputApiResponse,\n AgentExampleListResponse,\n ListAgentExamplesOptions,\n SetSlackTriggerConfigRequest,\n SlackTriggerConfigResponse,\n SetMetadataKeysRequest,\n MetadataKeysResponse,\n KnowledgeBaseMetadataKeyStatsResponse,\n ListSolutionsOptions,\n ListMemoryBanksOptions,\n ListEvaluationResultsOptions,\n ListAgentEvaluationResultsOptions,\n ListEvaluationRunsOptions,\n ListCompatibleRunsOptions,\n DateRangeOptions,\n OffsetPageOptions,\n ListAlertsOptions,\n ListAlertConfigsOptions,\n ListOrganizationAlertPreferencesOptions,\n ListModelAlertsOptions,\n ModelRecommendationsOptions,\n} from \"./types\";\n\n/** Default API base URL (can be overridden with `baseUrl` or `SECLAI_API_URL`). */\nexport const SECLAI_API_URL = \"https://api.seclai.com\";\n\n/** A `fetch`-compatible function (e.g. `globalThis.fetch` or `undici.fetch`). */\nexport type FetchLike = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\n/**\n * Token provider: a synchronous or asynchronous function that returns an\n * access token string. Called on every request to allow automatic refresh.\n */\nexport type AccessTokenProvider = () => string | Promise<string>;\n\n/** Configuration for the {@link Seclai} client. */\nexport interface SeclaiOptions {\n /** API key used for authentication. Defaults to `process.env.SECLAI_API_KEY` when available. */\n apiKey?: string;\n /**\n * Static bearer access token **or** a provider function that returns one.\n * Mutually exclusive with `apiKey`.\n */\n accessToken?: string | AccessTokenProvider;\n /** API base URL. Defaults to `process.env.SECLAI_API_URL` when available, else {@link SECLAI_API_URL}. */\n baseUrl?: string;\n /** Header name to use for the API key. Defaults to `x-api-key`. */\n apiKeyHeader?: string;\n /** Extra headers to include on every request. */\n defaultHeaders?: Record<string, string>;\n /** Optional `fetch` implementation for environments without a global `fetch`. */\n fetch?: FetchLike;\n /**\n * SSO profile name to load from `~/.seclai/config`.\n * Defaults to `process.env.SECLAI_PROFILE`, then `\"default\"`.\n */\n profile?: string;\n /**\n * Override the config directory path (default: `SECLAI_CONFIG_DIR` env var or `~/.seclai/`).\n */\n configDir?: string;\n /**\n * Whether to auto-refresh expired SSO tokens. Defaults to `true`.\n * Set to `false` in environments that should not write to disk.\n */\n autoRefresh?: boolean;\n /**\n * Target organization account ID. Sent as `X-Account-Id` header.\n * Overrides the profile's `sso_account_id` when using SSO auth.\n */\n accountId?: string;\n /**\n * Dated API version (`YYYY-MM-DD`) sent as the `Seclai-Version` header, opting\n * this client into backward-incompatible API changes released on or before\n * that date.\n *\n * Left unset the header is omitted and the account's pinned baseline applies,\n * so responses keep their current shapes and upgrading the SDK alone never\n * changes the wire contract. Pin the account instead with\n * {@link Seclai.updateApiVersion}, and read what a request resolves to with\n * {@link Seclai.getApiVersion}.\n *\n * From `2026-07-27` the API rejects undeclared query parameters with a 422\n * rather than ignoring them, and list endpoints return the canonical\n * `{data, pagination}` envelope.\n */\n apiVersion?: ApiVersion;\n /**\n * Permit an {@link apiVersion} this release was not built against.\n *\n * Off by default. A newer API version can change response shapes, and this\n * client would decode them incorrectly rather than reject them — a\n * request-side mistake answers 422, but a reshaped response just mis-decodes,\n * silently. Prefer upgrading the package.\n */\n allowUnknownApiVersion?: boolean;\n}\n\n// ─── Internal Helpers ────────────────────────────────────────────────────────\n\nfunction getEnv(name: string): string | undefined {\n const p = (globalThis as any)?.process;\n return p?.env?.[name];\n}\n\nfunction buildURL(baseUrl: string, path: string, query?: Record<string, unknown>): URL {\n // Ensure baseUrl ends with \"/\" so new URL() preserves its path component.\n const base = baseUrl.endsWith(\"/\") ? baseUrl : `${baseUrl}/`;\n // Strip leading \"/\" from path so it's treated as relative to base.\n const relative = path.startsWith(\"/\") ? path.slice(1) : path;\n const url = new URL(relative, base);\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) continue;\n if (Array.isArray(value)) {\n // A repeatable parameter: one `key=value` pair per element.\n for (const item of value) url.searchParams.append(key, String(item));\n continue;\n }\n url.searchParams.set(key, String(value));\n }\n }\n return url;\n}\n\n/**\n * One page as a fetcher handed to {@link Seclai.paginate} may return it: a list\n * method's `{data, pagination}` envelope or flat `{data, total, page, limit}`,\n * a bare array, or `{items, pagination}` with a `total_pages` count.\n */\nexport type PaginatedPage<T> =\n | T[]\n | {\n data?: T[] | null;\n pagination?: { pages?: number; has_next?: boolean } | null;\n total?: number;\n limit?: number;\n }\n | { items: T[]; pagination?: { page: number; total_pages: number } };\n\n/**\n * The items of a version-gated list whose method is declared as an array: a\n * bare array by default, under `data` from 2026-07-27.\n */\nfunction listItems<T>(res: unknown): T[] {\n if (Array.isArray(res)) return res as T[];\n if (res !== null && typeof res === \"object\" && \"data\" in res) {\n const data = (res as { data: unknown }).data;\n if (Array.isArray(data)) return data as T[];\n if (data === null) return [];\n }\n throw notAList();\n}\n\n/** An empty list would read as \"no results\" for a body that is not a list at all. */\nfunction notAList(): SeclaiError {\n return new SeclaiError(\n \"Expected a list response: an array, or an object carrying the items under `data` or the endpoint's own key.\",\n );\n}\n\n/**\n * A version-gated list as its declared object type. The items are under `key`\n * by default (or the body is a bare array) and under `data` from 2026-07-27,\n * where `flat` counters arrive inside `pagination`; both are restored to where\n * the type declares them, and `data`/`pagination` stay when the API sent them.\n */\nfunction keyedList<T extends object>(\n res: unknown,\n key: keyof T & string,\n flat: readonly (\"total\" | \"page\" | \"limit\")[] = [],\n): T {\n if (Array.isArray(res)) return { [key]: res } as T;\n if (res === null || typeof res !== \"object\") throw notAList();\n const body: Record<string, unknown> = { ...(res as Record<string, unknown>) };\n if (Array.isArray(body.data)) body[key] = body.data;\n else if (\"data\" in body && body.data === null) body[key] = [];\n else if (!Array.isArray(body[key])) throw notAList();\n const pagination = body.pagination as Record<string, unknown> | null | undefined;\n for (const field of flat) {\n if (body[field] === undefined && pagination?.[field] !== undefined) body[field] = pagination[field];\n }\n return body as T;\n}\n\n/** The flat counters of a list type that declares `total`, `page` and `limit`. */\nconst PAGE_COUNTERS = [\"total\", \"page\", \"limit\"] as const;\n\n/**\n * Merge header layers into one value per header. A later layer wins, and names\n * compare case-insensitively, so an override replaces instead of adding a\n * second spelling for `fetch` to join.\n */\nfunction mergeHeaders(...layers: (Record<string, string> | undefined)[]): Record<string, string> {\n const byName = new Map<string, [string, string]>();\n for (const layer of layers) {\n for (const [name, value] of Object.entries(layer ?? {})) {\n // A nullish value from untyped JavaScript means \"not set\", not a header.\n if (value === undefined || value === null) continue;\n const lower = name.toLowerCase();\n byName.delete(lower);\n byName.set(lower, [name, value]);\n }\n }\n return Object.fromEntries(byName.values());\n}\n\n/** The spelling under which `headers` carries `name` — the last one, which is the one a merge keeps. */\nfunction headerKey(headers: Record<string, string> | undefined, name: string): string | undefined {\n return Object.keys(headers ?? {})\n .filter((key) => key.toLowerCase() === name)\n .pop();\n}\n\nasync function safeText(response: Response): Promise<string | undefined> {\n try {\n return await response.clone().text();\n } catch {\n return undefined;\n }\n}\n\nasync function safeJson(response: Response): Promise<unknown | undefined> {\n try {\n return await response.clone().json();\n } catch {\n return undefined;\n }\n}\n\ntype SseMessage = { event?: string; data?: string };\n\nfunction createSseParser(onMessage: (msg: SseMessage) => void) {\n let buffer = \"\";\n let eventName: string | undefined;\n let dataLines: string[] = [];\n\n function dispatch() {\n if (!eventName && dataLines.length === 0) return;\n const msg: SseMessage = { data: dataLines.join(\"\\n\") };\n if (eventName !== undefined) msg.event = eventName;\n onMessage(msg);\n eventName = undefined;\n dataLines = [];\n }\n\n function feed(textChunk: string) {\n buffer += textChunk;\n while (true) {\n const newlineIdx = buffer.indexOf(\"\\n\");\n if (newlineIdx === -1) return;\n\n let line = buffer.slice(0, newlineIdx);\n buffer = buffer.slice(newlineIdx + 1);\n\n if (line.endsWith(\"\\r\")) line = line.slice(0, -1);\n\n if (line === \"\") {\n dispatch();\n continue;\n }\n\n if (line.startsWith(\":\")) continue;\n\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n let value = colon === -1 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) value = value.slice(1);\n\n if (field === \"event\") {\n eventName = value;\n } else if (field === \"data\") {\n dataLines.push(value);\n }\n }\n }\n\n return { feed, end: dispatch };\n}\n\nfunction anySignal(signals: Array<AbortSignal | undefined>): AbortSignal | undefined {\n const present = signals.filter(Boolean) as AbortSignal[];\n if (present.length === 0) return undefined;\n if (present.length === 1) return present[0];\n const controller = new AbortController();\n const onAbort = () => controller.abort();\n for (const s of present) {\n if (s.aborted) {\n controller.abort();\n break;\n }\n s.addEventListener(\"abort\", onAbort, { once: true });\n }\n return controller.signal;\n}\n\nfunction toBlob(\n file: Blob | Uint8Array | ArrayBuffer | BufferSource,\n mimeType?: string,\n): Blob {\n if (file instanceof Blob) return file;\n const opts = mimeType ? { type: mimeType } : undefined;\n if (file instanceof ArrayBuffer) return new Blob([new Uint8Array(file)], opts);\n return new Blob([file as unknown as BlobPart], opts);\n}\n\nconst MIME_TYPES: Record<string, string> = {\n txt: \"text/plain\", html: \"text/html\", htm: \"text/html\", md: \"text/markdown\",\n csv: \"text/csv\", xml: \"text/xml\", json: \"application/json\",\n pdf: \"application/pdf\", doc: \"application/msword\",\n docx: \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n ppt: \"application/vnd.ms-powerpoint\",\n pptx: \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n xls: \"application/vnd.ms-excel\",\n xlsx: \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n msg: \"application/vnd.ms-outlook\", zip: \"application/zip\",\n epub: \"application/epub+zip\",\n png: \"image/png\", jpg: \"image/jpeg\", jpeg: \"image/jpeg\", gif: \"image/gif\",\n bmp: \"image/bmp\", tiff: \"image/tiff\", webp: \"image/webp\",\n mp3: \"audio/mpeg\", wav: \"audio/wav\", m4a: \"audio/mp4\", flac: \"audio/flac\",\n ogg: \"audio/ogg\", mp4: \"video/mp4\", mov: \"video/quicktime\", avi: \"video/x-msvideo\",\n};\n\nfunction inferMimeType(fileName: string | undefined): string | undefined {\n if (!fileName) return undefined;\n const ext = fileName.split(\".\").pop()?.toLowerCase();\n return ext ? MIME_TYPES[ext] : undefined;\n}\n\n// ─── Client ──────────────────────────────────────────────────────────────────\n\n/**\n * Seclai JavaScript/TypeScript client.\n *\n * Provides typed methods for every Seclai API endpoint, plus higher-level\n * abstractions for streaming, polling, and pagination.\n *\n * @example\n * ```ts\n * import { Seclai } from \"@seclai/sdk\";\n *\n * const client = new Seclai({ apiKey: \"sk-...\" });\n *\n * // List agents\n * const { data: agents } = await client.listAgents();\n *\n * // Run an agent\n * const run = await client.runAgent(\"agent-id\", { input: \"Hello!\" });\n *\n * // Stream an agent run\n * for await (const event of client.runStreamingAgent(\"agent-id\", { input: \"Hello!\" })) {\n * console.log(event.event, event.data);\n * }\n * ```\n */\nexport class Seclai {\n private readonly baseUrl: string;\n private readonly defaultHeaders: Record<string, string>;\n private readonly allowUnknownApiVersion: boolean;\n private readonly fetcher: FetchLike;\n private _authState: AuthState | null = null;\n private _authInitPromise: Promise<void> | null = null;\n private _authInitError: SeclaiConfigurationError | null = null;\n\n /**\n * Create a new Seclai client.\n *\n * Credentials are resolved via a chain (first match wins):\n * 1. Explicit `apiKey` option\n * 2. Explicit `accessToken` option (static string or provider function)\n * 3. `SECLAI_API_KEY` environment variable\n * 4. SSO profile from `~/.seclai/config` + cached tokens in `~/.seclai/sso/cache/`\n *\n * @param opts - Client configuration.\n * @throws {@link SeclaiConfigurationError} If no `fetch` implementation is available.\n * @throws {@link SeclaiConfigurationError} If both `apiKey` and `accessToken` are provided.\n */\n constructor(opts: SeclaiOptions = {}) {\n // Validate mutual exclusion\n if (opts.apiKey && opts.accessToken) {\n throw new SeclaiConfigurationError(\n \"Provide either apiKey or accessToken, not both.\"\n );\n }\n\n const fetcher = opts.fetch ?? (globalThis.fetch as FetchLike | undefined);\n if (!fetcher) {\n throw new SeclaiConfigurationError(\n \"No fetch implementation available. Provide opts.fetch or run in an environment with global fetch.\"\n );\n }\n\n this.baseUrl = opts.baseUrl ?? getEnv(\"SECLAI_API_URL\") ?? SECLAI_API_URL;\n\n // `defaultHeaders` is applied last so an explicit header wins, which means\n // it can carry its own Seclai-Version; the guard reads the merged result,\n // the value the client will send.\n this.allowUnknownApiVersion = opts.allowUnknownApiVersion ?? false;\n const merged = mergeHeaders(\n opts.apiVersion ? { \"Seclai-Version\": opts.apiVersion } : undefined,\n opts.defaultHeaders,\n );\n const defaultKey = headerKey(opts.defaultHeaders, \"seclai-version\");\n this.assertKnownApiVersion(merged, defaultKey ? `defaultHeaders['${defaultKey}']` : \"apiVersion\");\n this.defaultHeaders = merged;\n this.fetcher = fetcher;\n\n // Resolve credential chain (may be async for SSO profile loading)\n const accessTokenProvider =\n typeof opts.accessToken === \"function\" ? opts.accessToken : undefined;\n const accessTokenStatic =\n typeof opts.accessToken === \"string\" ? opts.accessToken : undefined;\n\n this._authInitPromise = resolveCredentialChain({\n apiKey: opts.apiKey,\n accessToken: accessTokenStatic,\n accessTokenProvider,\n profile: opts.profile,\n configDir: opts.configDir,\n autoRefresh: opts.autoRefresh,\n accountId: opts.accountId,\n apiKeyHeader: opts.apiKeyHeader,\n fetch: fetcher,\n }).then((state) => {\n this._authState = state;\n }).catch((err) => {\n this._authInitError = new SeclaiConfigurationError(\n err instanceof Error ? err.message : String(err)\n );\n });\n }\n\n /** Ensure the credential chain has been resolved. */\n private async ensureAuth(): Promise<AuthState> {\n if (this._authInitPromise) {\n await this._authInitPromise;\n this._authInitPromise = null;\n }\n if (this._authInitError) {\n throw this._authInitError;\n }\n if (!this._authState) {\n throw new SeclaiConfigurationError(\n \"Missing credentials. Provide apiKey, accessToken, set SECLAI_API_KEY, or run `seclai auth login`.\"\n );\n }\n return this._authState;\n }\n\n /** Throw unless the `Seclai-Version` in `headers` is one this release was built against. */\n private assertKnownApiVersion(headers: Record<string, string>, via: string): void {\n const key = headerKey(headers, \"seclai-version\");\n if (key === undefined || this.allowUnknownApiVersion) return;\n const version = headers[key] ?? \"\";\n if (KNOWN_API_VERSIONS.includes(version)) return;\n throw new SeclaiConfigurationError(\n `Unknown API version '${version}' (via ${via}). This release was ` +\n `built against ${KNOWN_API_VERSIONS.join(\", \")}. A newer API version can ` +\n `change response shapes, which this client would decode incorrectly rather ` +\n `than reject. Upgrade the package, or set allowUnknownApiVersion to ` +\n `proceed anyway.`,\n );\n }\n\n /**\n * The headers one request sends: `layers` merged in order, later winning,\n * with the resulting `Seclai-Version` checked against the known versions.\n */\n private requestHeaders(\n layers: (Record<string, string> | undefined)[],\n perRequest?: Record<string, string>,\n ): Record<string, string> {\n const headers = mergeHeaders(...layers);\n const requestKey = headerKey(perRequest, \"seclai-version\");\n this.assertKnownApiVersion(headers, requestKey ? `headers['${requestKey}']` : \"defaultHeaders\");\n return headers;\n }\n\n /** Resolve auth headers for the current request. */\n private async authHeaders(): Promise<Record<string, string>> {\n const state = await this.ensureAuth();\n return resolveAuthHeaders(state);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Low-level request\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Make a raw HTTP request to the Seclai API.\n *\n * This is a low-level escape hatch. For most operations, prefer the typed convenience methods.\n *\n * @param method - HTTP method (e.g. `\"GET\"`, `\"POST\"`).\n * @param path - Request path relative to `baseUrl` (e.g. `\"/sources/\"`).\n * @param opts - Query params, JSON body, per-request headers, and optional AbortSignal.\n * @returns Parsed JSON for JSON responses, raw text for non-JSON responses, or `null` for empty bodies.\n * @throws {@link SeclaiAPIValidationError} For validation errors (typically HTTP 422).\n * @throws {@link SeclaiAPIStatusError} For other non-success HTTP status codes.\n */\n async request(\n method: string,\n path: string,\n opts?: {\n query?: Record<string, unknown>;\n json?: unknown;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n }\n ): Promise<unknown | string | null> {\n const url = buildURL(this.baseUrl, path, opts?.query);\n\n const authHeaders = await this.authHeaders();\n let body: BodyInit | undefined;\n if (opts?.json !== undefined) body = JSON.stringify(opts.json);\n // A caller's content type, default or per-request, replaces the JSON one.\n const headers = this.requestHeaders(\n [\n body === undefined ? undefined : { \"content-type\": \"application/json\" },\n this.defaultHeaders,\n opts?.headers,\n authHeaders,\n ],\n opts?.headers,\n );\n\n const init: RequestInit = { method, headers };\n if (body !== undefined) {\n init.body = body;\n }\n if (opts?.signal) {\n init.signal = opts.signal;\n }\n const response = await this.fetcher(url, init);\n\n if (response.status === 204) return null;\n\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n const isJson = contentType.includes(\"application/json\");\n\n if (!response.ok) {\n const responseText = await safeText(response);\n if (response.status === 422) {\n const validation = await safeJson(response);\n throw new SeclaiAPIValidationError({\n message: \"Validation error\",\n statusCode: response.status,\n method,\n url: url.toString(),\n responseText,\n validationError: validation,\n });\n }\n throw new SeclaiAPIStatusError({\n message: `Request failed with status ${response.status}`,\n statusCode: response.status,\n method,\n url: url.toString(),\n responseText,\n });\n }\n\n if (!response.body) return null;\n\n if (isJson) {\n return (await response.json()) as unknown;\n }\n return await response.text();\n }\n\n /**\n * Make a raw HTTP request and return the raw `Response` object (for binary downloads, etc.).\n *\n * @param method - HTTP method.\n * @param path - Request path relative to `baseUrl`.\n * @param opts - Query params, JSON body, per-request headers, and optional AbortSignal.\n * @returns The raw `Response` object.\n * @throws {SeclaiAPIValidationError} On HTTP 422 responses.\n * @throws {SeclaiAPIStatusError} On other non-2xx responses.\n */\n async requestRaw(\n method: string,\n path: string,\n opts?: {\n query?: Record<string, unknown>;\n json?: unknown;\n headers?: Record<string, string>;\n signal?: AbortSignal | undefined;\n }\n ): Promise<Response> {\n const url = buildURL(this.baseUrl, path, opts?.query);\n\n const authHeaders = await this.authHeaders();\n let body: BodyInit | undefined;\n if (opts?.json !== undefined) body = JSON.stringify(opts.json);\n // A caller's content type, default or per-request, replaces the JSON one.\n const headers = this.requestHeaders(\n [\n body === undefined ? undefined : { \"content-type\": \"application/json\" },\n this.defaultHeaders,\n opts?.headers,\n authHeaders,\n ],\n opts?.headers,\n );\n\n const init: RequestInit = { method, headers };\n if (body !== undefined) init.body = body;\n if (opts?.signal) init.signal = opts.signal;\n\n const response = await this.fetcher(url, init);\n\n if (!response.ok) {\n const responseText = await safeText(response);\n if (response.status === 422) {\n const validation = await safeJson(response);\n throw new SeclaiAPIValidationError({\n message: \"Validation error\",\n statusCode: response.status,\n method,\n url: url.toString(),\n responseText,\n validationError: validation,\n });\n }\n throw new SeclaiAPIStatusError({\n message: `Request failed with status ${response.status}`,\n statusCode: response.status,\n method,\n url: url.toString(),\n responseText,\n });\n }\n\n return response;\n }\n\n /** Shared multipart upload helper. */\n private async uploadFile(\n path: string,\n opts: {\n file: Blob | Uint8Array | ArrayBuffer | BufferSource;\n title?: string;\n metadata?: Record<string, unknown>;\n fileName?: string;\n mimeType?: string;\n signal?: AbortSignal;\n },\n ): Promise<unknown> {\n const url = buildURL(this.baseUrl, path);\n\n const authHeaders = await this.authHeaders();\n const headers = this.requestHeaders([this.defaultHeaders, authHeaders]);\n // Let fetch set the multipart Content-Type with its boundary.\n const contentType = headerKey(headers, \"content-type\");\n if (contentType !== undefined) delete headers[contentType];\n\n const form = new FormData();\n const mimeType = opts.mimeType ?? inferMimeType(opts.fileName);\n const blob = toBlob(opts.file, mimeType);\n form.set(\"file\", blob, opts.fileName ?? \"upload\");\n\n if (opts.title !== undefined) form.set(\"title\", opts.title);\n if (opts.metadata !== undefined) form.set(\"metadata\", JSON.stringify(opts.metadata));\n\n const init: RequestInit = { method: \"POST\", headers, body: form };\n if (opts.signal) init.signal = opts.signal;\n\n const response = await this.fetcher(url, init);\n\n if (!response.ok) {\n const responseText = await safeText(response);\n if (response.status === 422) {\n const validation = await safeJson(response);\n throw new SeclaiAPIValidationError({\n message: \"Validation error\",\n statusCode: response.status,\n method: \"POST\",\n url: url.toString(),\n responseText,\n validationError: validation,\n });\n }\n throw new SeclaiAPIStatusError({\n message: `Request failed with status ${response.status}`,\n statusCode: response.status,\n method: \"POST\",\n url: url.toString(),\n responseText,\n });\n }\n\n return await response.json();\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Identity\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Get the authenticated user's identity.\n *\n * Returns the personal `account_id` plus every organization the user belongs\n * to — each with its own `id`, display `name`, and `account_id`. Use it to\n * discover the account IDs that can be passed as the client's `accountId`\n * option (sent as the `X-Account-Id` header) to target an org context.\n *\n * @returns The current user's account ID and organization memberships.\n */\n async getMe(): Promise<MeResponse> {\n return (await this.request(\"GET\", \"/me\")) as MeResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // API Version\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Read the API version this request resolved to, and the versions available.\n *\n * Resolution order is the `Seclai-Version` header, then the account pin, then\n * the default — so `effective_version` reflects the client's `apiVersion`\n * option when that is set.\n *\n * @returns The pinned, effective, default and latest versions.\n */\n async getApiVersion(): Promise<ApiVersionResponse> {\n return (await this.request(\"GET\", \"/version\")) as ApiVersionResponse;\n }\n\n /**\n * Pin the account to a dated API version, or clear the pin.\n *\n * Owner/admin only. The pin applies to later header-less requests; a\n * `Seclai-Version` header still overrides it, so `effective_version` in the\n * response describes this request rather than the pin just written.\n *\n * @param version - A `YYYY-MM-DD` date to pin to, or `null` to clear the pin.\n * @returns The updated version state.\n */\n async updateApiVersion(version: string | null): Promise<ApiVersionResponse> {\n return (await this.request(\"PUT\", \"/version\", { json: { version } })) as ApiVersionResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agents — CRUD\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List agents.\n *\n * @param opts - Pagination options.\n * @returns Paginated list of agents.\n */\n async listAgents(opts: ListOptions = {}): Promise<AgentListResponse> {\n return (await this.request(\"GET\", \"/agents\", {\n query: { page: opts.page, limit: opts.limit },\n })) as AgentListResponse;\n }\n\n /**\n * List the agent gallery: example agents to start from.\n *\n * Pass an entry's `key` as `agent_template` to {@link createAgent}, with\n * `resource_bindings` for the resources it needs.\n *\n * @param opts - Text search, use-case filter and pagination.\n * @returns A page of gallery entries.\n */\n async listAgentExamples(opts: ListAgentExamplesOptions = {}): Promise<AgentExampleListResponse> {\n return (await this.request(\"GET\", \"/agents/examples\", {\n query: { query: opts.query, use_case: opts.useCase, page: opts.page, limit: opts.limit },\n })) as AgentExampleListResponse;\n }\n\n /**\n * Create a new agent.\n *\n * @param body - Agent creation payload (name, trigger type, template, etc.).\n * @returns Summary of the created agent.\n */\n async createAgent(body: CreateAgentRequest): Promise<AgentSummaryResponse> {\n return (await this.request(\"POST\", \"/agents\", { json: body })) as AgentSummaryResponse;\n }\n\n /**\n * Get agent details including its definition.\n *\n * @param agentId - Agent identifier.\n * @returns Full agent metadata.\n */\n async getAgent(agentId: string): Promise<AgentSummaryResponse> {\n return (await this.request(\"GET\", `/agents/${agentId}`)) as AgentSummaryResponse;\n }\n\n /**\n * Update an agent.\n *\n * @param agentId - Agent identifier.\n * @param body - Fields to update.\n * @returns Updated agent summary.\n */\n async updateAgent(agentId: string, body: UpdateAgentRequest): Promise<AgentSummaryResponse> {\n return (await this.request(\"PUT\", `/agents/${agentId}`, { json: body })) as AgentSummaryResponse;\n }\n\n /**\n * Delete an agent.\n *\n * @param agentId - Agent identifier.\n */\n async deleteAgent(agentId: string): Promise<void> {\n await this.request(\"DELETE\", `/agents/${agentId}`);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agents — Enable / Disable\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Pause (disable) an agent so it stops firing from every trigger path.\n *\n * API runs return HTTP 409, inbound email is turned away, and scheduled /\n * content triggers are skipped.\n *\n * Fails with HTTP 409 when other live agents still call this one via a\n * `call_agent` step — use {@link getAgentCallers} to list them, and disable\n * those first.\n *\n * @param agentId - Agent identifier.\n * @returns The updated agent summary.\n */\n async disableAgent(agentId: string): Promise<AgentSummaryResponse> {\n return (await this.request(\"POST\", `/agents/${agentId}/disable`)) as AgentSummaryResponse;\n }\n\n /**\n * Resume (enable) a paused agent.\n *\n * Clears the disable state whether the agent was paused manually or\n * auto-paused by the inbound-email overload safeguard.\n *\n * @param agentId - Agent identifier.\n * @returns The updated agent summary.\n */\n async enableAgent(agentId: string): Promise<AgentSummaryResponse> {\n return (await this.request(\"POST\", `/agents/${agentId}/enable`)) as AgentSummaryResponse;\n }\n\n /**\n * List the live agents that call this agent via a `call_agent` step.\n *\n * These must be disabled before this agent can be paused.\n *\n * @param agentId - Agent identifier.\n * @returns The calling agents.\n */\n async getAgentCallers(agentId: string): Promise<AgentCallerApiResponse[]> {\n return listItems<AgentCallerApiResponse>(await this.request(\"GET\", `/agents/${agentId}/callers`));\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent Export / Import\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Export an agent definition as a portable JSON snapshot.\n *\n * @param agentId - Agent identifier.\n * @param download - When true (default), the server sets Content-Disposition: attachment.\n * @returns The exported agent snapshot.\n */\n async exportAgent(agentId: string, download = true): Promise<AgentExportResponse> {\n return (await this.request(\"GET\", `/agents/${agentId}/export`, {\n query: { download },\n })) as AgentExportResponse;\n }\n\n /**\n * Validate an `agent_definition` payload (same shape as {@link exportAgent})\n * without creating or modifying any agent.\n *\n * Use this before {@link createAgent} or {@link updateAgent} with an\n * `agent_definition` to surface `unresolved_refs` — workflow references to\n * knowledge bases, memory banks, source connections, or sub-agents that\n * don't exist in the target account. Pass the returned ids back in\n * `entity_remap` on the commit call to substitute them.\n *\n * @param body - The preview payload (`{ agent_definition: ... }`).\n * @returns Summary of the validated payload (step counts, schedules,\n * alert configs, evaluation criteria, governance policies, and any\n * `unresolved_refs`).\n * @throws {SeclaiAPIValidationError} On HTTP 422 — the body is an\n * {@link AgentDefinitionImportErrorResponse} with 1-indexed\n * line/column-anchored errors against a canonical `source` echo.\n */\n async previewImportAgent(body: AgentImportPreviewRequest): Promise<AgentImportPreviewResponse> {\n return (await this.request(\"POST\", \"/agents/preview-import\", { json: body })) as AgentImportPreviewResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent Definitions\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Get an agent's full definition (steps, model config, etc.).\n *\n * @param agentId - Agent identifier.\n * @returns The agent definition.\n */\n async getAgentDefinition(agentId: string): Promise<AgentDefinitionResponse> {\n return (await this.request(\"GET\", `/agents/${agentId}/definition`)) as AgentDefinitionResponse;\n }\n\n /**\n * Update an agent's definition.\n *\n * @param agentId - Agent identifier.\n * @param body - Updated definition payload.\n * @returns Updated agent definition.\n */\n async updateAgentDefinition(agentId: string, body: UpdateAgentDefinitionRequest): Promise<AgentDefinitionResponse> {\n return (await this.request(\"PUT\", `/agents/${agentId}/definition`, { json: body })) as AgentDefinitionResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent Runs\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Start an agent run.\n *\n * @param agentId - Agent identifier.\n * @param body - Run request payload (`input`, `metadata`, `priority`, etc.).\n * @returns The created agent run.\n */\n async runAgent(agentId: string, body: AgentRunRequest): Promise<AgentRunResponse> {\n return (await this.request(\"POST\", `/agents/${agentId}/runs`, { json: body })) as AgentRunResponse;\n }\n\n /**\n * List runs for a specific agent.\n *\n * @param agentId - Agent identifier.\n * @param opts - Pagination and filter options.\n * @returns Paginated list of runs.\n */\n async listAgentRuns(\n agentId: string,\n opts: ListOptions & { status?: string } = {},\n ): Promise<AgentRunListResponse> {\n return (await this.request(\"GET\", `/agents/${agentId}/runs`, {\n query: { page: opts.page, limit: opts.limit, status: opts.status },\n })) as AgentRunListResponse;\n }\n\n /**\n * Search agent runs (traces) across all agents.\n *\n * @param body - Search query and filters.\n * @returns Search results with matching runs.\n */\n async searchAgentRuns(body: AgentTraceSearchRequest): Promise<AgentTraceSearchResponse> {\n return (await this.request(\"POST\", \"/agents/runs/search\", { json: body })) as AgentTraceSearchResponse;\n }\n\n /**\n * Get details of a specific agent run.\n *\n * @param runId - Run identifier.\n * @param opts - Optional flags.\n * @returns Agent run details.\n */\n async getAgentRun(\n runId: string,\n opts?: { includeStepOutputs?: boolean },\n ): Promise<AgentRunResponse> {\n return (await this.request(\"GET\", `/agents/runs/${runId}`, opts?.includeStepOutputs ? {\n query: { include_step_outputs: true },\n } : undefined)) as AgentRunResponse;\n }\n\n /**\n * Cancel an agent run.\n *\n * @deprecated This never deleted anything — the endpoint it calls is documented\n * as \"Cancel an agent run\", and the API has no delete-a-run operation. It also\n * discards the returned run state. Use {@link cancelAgentRun} instead.\n *\n * @param runId - Run identifier.\n */\n async deleteAgentRun(runId: string): Promise<void> {\n await this.cancelAgentRun(runId);\n }\n\n /**\n * Cancel a running agent run.\n *\n * Cancellation is `DELETE` on the run resource — the API exposes no\n * `POST .../cancel` route, and no operation that deletes a run. Rejected when\n * the run has already reached a terminal state.\n *\n * @param runId - Run identifier.\n * @returns Updated run (with cancelled status).\n */\n async cancelAgentRun(runId: string): Promise<AgentRunResponse> {\n return (await this.request(\"DELETE\", `/agents/runs/${runId}`)) as AgentRunResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent Runs — Streaming\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Run an agent in streaming mode (SSE) and wait for the final result.\n *\n * Consumes the entire SSE stream and returns only the terminal `done` payload.\n * For real-time event access, use {@link runStreamingAgent} instead. The body\n * takes no `include_reasoning`, and one passed anyway is not sent: this method\n * returns no `stream_reasoning` events.\n *\n * A `result` event carries the run's answer in `output` once\n * `result_reported_at` is set, and can arrive while later steps still run.\n * Pass `returnOnResult: true` to return that `result` snapshot as soon as it\n * arrives, without waiting for `done`. Such a run may still be in progress:\n * its `status` is not terminal and the run can still fail, so check\n * `result_reported_at`, not `status`.\n *\n * If `timeoutMs` elapses, this throws {@link SeclaiStreamingError} with the\n * latest snapshot in `run`: the `result` snapshot if one arrived, else the\n * `init` snapshot. An abort from `signal` rethrows the abort error.\n *\n * By default, a stream that ends before `done` returns the latest snapshot\n * when its status is not `pending`, so the run returned may not have\n * finished: check `status` and `result_reported_at`. A stream that breaks\n * throws the fetch error. Pass `throwOnIncomplete: true` to throw\n * {@link SeclaiStreamingError} with the snapshot in `run` in both cases\n * instead; it is recommended, and becomes the default in the next major\n * version.\n *\n * @param agentId - Agent identifier.\n * @param body - Streaming run request payload, without `include_reasoning`.\n * @param opts - Timeout, abort signal and `returnOnResult` options.\n * @returns The run from the `done` event; with `returnOnResult`, the\n * `result` snapshot; without `throwOnIncomplete`, possibly an unfinished\n * snapshot (see above).\n * @throws {@link SeclaiStreamingError} If `timeoutMs` elapses, or, with\n * `throwOnIncomplete`, the stream ends or breaks, before the run finished.\n * Its `run` holds the latest snapshot.\n *\n * @example\n * ```ts\n * try {\n * const run = await client.runStreamingAgentAndWait(\"agent-id\", { input: \"Hello\" }, { throwOnIncomplete: true });\n * console.log(run.output);\n * } catch (err) {\n * if (err instanceof SeclaiStreamingError && err.run?.result_reported_at) {\n * console.log(\"Answer (run not finished):\", err.run.output);\n * } else throw err;\n * }\n * ```\n */\n async runStreamingAgentAndWait(\n agentId: string,\n body: Omit<AgentRunStreamRequest, \"include_reasoning\">,\n opts?: {\n timeoutMs?: number;\n signal?: AbortSignal;\n /**\n * Return the `result` snapshot as soon as a `result` event arrives (its\n * answer is in `output`), without waiting for `done` (default: false).\n */\n returnOnResult?: boolean;\n /**\n * Throw {@link SeclaiStreamingError}, with the latest snapshot in `run`,\n * whenever the stream ends or breaks before `done`, or the server answers\n * with plain JSON for a run that has not finished, instead of returning\n * an unfinished run or throwing the fetch error (default: false). This\n * becomes the default in the next major version.\n */\n throwOnIncomplete?: boolean;\n },\n ): Promise<AgentRunResponse> {\n // Not sent even from untyped callers: the reasoning events are discarded here.\n const { include_reasoning: _ignored, ...runBody } = body as AgentRunStreamRequest;\n const url = buildURL(this.baseUrl, `/agents/${agentId}/runs/stream`);\n\n const authHdrs = await this.authHeaders();\n const headers = this.requestHeaders([\n this.defaultHeaders,\n authHdrs,\n { accept: \"text/event-stream\", \"content-type\": \"application/json\" },\n ]);\n\n const timeoutMs = opts?.timeoutMs ?? 60_000;\n const timeoutController = new AbortController();\n let timedOut = false;\n const timeoutId = setTimeout(() => {\n timedOut = true;\n timeoutController.abort();\n }, timeoutMs);\n\n const signal = anySignal([opts?.signal, timeoutController.signal]);\n\n let lastSeen: AgentRunResponse | undefined;\n let reported: AgentRunResponse | undefined;\n\n try {\n const init: RequestInit = { method: \"POST\", headers, body: JSON.stringify(runBody) };\n if (signal) init.signal = signal;\n\n const response = await this.fetcher(url, init);\n\n // Handle error responses\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n const isJson = contentType.includes(\"application/json\");\n\n if (!response.ok) {\n const responseText = await safeText(response);\n if (response.status === 422) {\n const validation = await safeJson(response);\n throw new SeclaiAPIValidationError({\n message: \"Validation error\",\n statusCode: response.status,\n method: \"POST\",\n url: url.toString(),\n responseText,\n validationError: validation,\n });\n }\n throw new SeclaiAPIStatusError({\n message: `Request failed with status ${response.status}`,\n statusCode: response.status,\n method: \"POST\",\n url: url.toString(),\n responseText,\n });\n }\n\n // If server returned JSON instead of SSE\n if (isJson) {\n const run = (await response.json()) as AgentRunResponse;\n const status = (run as any).status;\n const finished =\n status === \"completed\" || status === \"failed\" || status === \"cancelled\" ||\n Boolean(opts?.returnOnResult && run.result_reported_at);\n if (opts?.throwOnIncomplete && !finished) {\n const state = run.result_reported_at ? \"A result had been reported; see `run`.\" : \"No result had been reported.\";\n throw new SeclaiStreamingError(`The server answered with JSON for a run that has not finished. ${state}`, run.run_id, run);\n }\n return run;\n }\n\n if (!response.body) {\n throw new SeclaiConfigurationError(\n \"Streaming response body is not available in this environment. Provide a fetch implementation that supports ReadableStream bodies.\"\n );\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n\n let final: AgentRunResponse | undefined;\n\n const parser = createSseParser((msg) => {\n if (!msg.data) return;\n if (msg.event === \"init\" || msg.event === \"result\" || msg.event === \"done\") {\n try {\n const parsed = JSON.parse(msg.data) as AgentRunResponse;\n lastSeen = parsed;\n if (msg.event === \"result\") reported = parsed;\n if (msg.event === \"done\") final = parsed;\n } catch { /* ignore malformed JSON */ }\n }\n });\n\n let readFailure: string | undefined;\n try {\n while (!final && !(opts?.returnOnResult && reported)) {\n const { value, done } = await reader.read();\n if (done) break;\n if (value) parser.feed(decoder.decode(value, { stream: true }));\n }\n } catch (err) {\n // The caller asked to stop: keep the abort error. Without\n // throwOnIncomplete, a broken read throws the fetch error, as released.\n if (opts?.signal?.aborted || (!opts?.throwOnIncomplete && !timedOut)) throw err;\n readFailure = err instanceof Error ? err.message : String(err);\n }\n\n // Flush the decoder, and dispatch an event whose complete lines were read\n // but whose terminating blank line has not arrived. Text after the last\n // newline is not parsed.\n parser.feed(decoder.decode());\n parser.end();\n\n if (final) return final;\n if (opts?.returnOnResult && reported) {\n reader.cancel().catch(() => {});\n return reported;\n }\n // Released behaviour without throwOnIncomplete: the stream ended early.\n if (!opts?.throwOnIncomplete && !timedOut && lastSeen?.status && lastSeen.status !== \"pending\") {\n return lastSeen;\n }\n\n const run = reported ?? lastSeen;\n const state = reported ? \"A result had been reported; see `run`.\" : \"No result had been reported.\";\n const reason = timedOut\n ? `Timed out after ${timeoutMs}ms before the streaming agent run finished.`\n : readFailure !== undefined\n ? `Stream failed before the run finished: ${readFailure}.`\n : \"Stream ended before receiving a 'done' event.\";\n throw new SeclaiStreamingError(`${reason} ${state}`, run?.run_id, run);\n } catch (err) {\n if (timedOut && !opts?.signal?.aborted && !(err instanceof SeclaiStreamingError)) {\n throw new SeclaiStreamingError(\n `Timed out after ${timeoutMs}ms waiting for streaming agent run to complete.`,\n lastSeen?.run_id,\n reported ?? lastSeen,\n );\n }\n throw err;\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n /**\n * Run an agent in streaming mode and yield each SSE event as it arrives.\n *\n * This is an `AsyncGenerator` suitable for real-time UIs that want to render\n * step progress as it happens.\n *\n * @param agentId - Agent identifier.\n * @param body - Streaming run request payload.\n * @param opts - Timeout and abort signal options.\n * @yields {@link AgentRunEvent} for each SSE message.\n *\n * @example\n * ```ts\n * for await (const event of client.runStreamingAgent(\"agent-id\", { input: \"Hello!\" })) {\n * // `result` carries the answer in `output`, possibly before later steps finish.\n * if (event.event === \"result\") {\n * console.log(\"Answer:\", (event.data as AgentRunResponse).output);\n * }\n * if (event.event === \"done\") {\n * console.log(\"Final:\", event.data);\n * }\n * }\n * ```\n */\n async *runStreamingAgent(\n agentId: string,\n body: AgentRunStreamRequest,\n opts?: { timeoutMs?: number; signal?: AbortSignal },\n ): AsyncGenerator<AgentRunEvent, void, undefined> {\n const url = buildURL(this.baseUrl, `/agents/${agentId}/runs/stream`);\n\n const authHdrs = await this.authHeaders();\n const headers = this.requestHeaders([\n this.defaultHeaders,\n authHdrs,\n { accept: \"text/event-stream\", \"content-type\": \"application/json\" },\n ]);\n\n const timeoutMs = opts?.timeoutMs ?? 60_000;\n const timeoutController = new AbortController();\n let timedOut = false;\n const timeoutId = setTimeout(() => {\n timedOut = true;\n timeoutController.abort();\n }, timeoutMs);\n\n const signal = anySignal([opts?.signal, timeoutController.signal]);\n\n try {\n const init: RequestInit = { method: \"POST\", headers, body: JSON.stringify(body) };\n if (signal) init.signal = signal;\n\n const response = await this.fetcher(url, init);\n\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n const isJson = contentType.includes(\"application/json\");\n\n if (!response.ok) {\n const responseText = await safeText(response);\n if (response.status === 422) {\n const validation = await safeJson(response);\n throw new SeclaiAPIValidationError({\n message: \"Validation error\",\n statusCode: response.status,\n method: \"POST\",\n url: url.toString(),\n responseText,\n validationError: validation,\n });\n }\n throw new SeclaiAPIStatusError({\n message: `Request failed with status ${response.status}`,\n statusCode: response.status,\n method: \"POST\",\n url: url.toString(),\n responseText,\n });\n }\n\n // If server returned JSON instead of SSE, yield it as a single \"done\" event\n if (isJson) {\n const data = (await response.json()) as AgentRunResponse;\n yield { event: \"done\", data };\n return;\n }\n\n if (!response.body) {\n throw new SeclaiConfigurationError(\n \"Streaming response body is not available in this environment.\"\n );\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n const events: AgentRunEvent[] = [];\n\n const parser = createSseParser((msg) => {\n if (!msg.data) return;\n let data: unknown;\n try {\n data = JSON.parse(msg.data);\n } catch {\n data = msg.data;\n }\n events.push({ event: msg.event ?? \"message\", data });\n });\n\n while (true) {\n const { value, done } = await reader.read();\n if (value) parser.feed(decoder.decode(value, { stream: true }));\n\n // Yield all events that were parsed from this chunk\n while (events.length > 0) {\n yield events.shift()!;\n }\n\n if (done) break;\n }\n parser.end();\n\n // Yield any remaining events from end()\n while (events.length > 0) {\n yield events.shift()!;\n }\n } catch (err) {\n if (timedOut) {\n throw new SeclaiStreamingError(\n `Timed out after ${timeoutMs}ms waiting for streaming agent run to complete.`\n );\n }\n throw err;\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent Runs — Polling\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Run an agent and poll until it reaches a terminal status.\n *\n * This is useful in environments where SSE streaming is unavailable.\n *\n * A run's answer can be ready before its last step finishes: once\n * `result_reported_at` is set, `output` holds the answer. Pass\n * `returnOnResult: true` to return as soon as a run has it set, the run\n * `runAgent()` returns included. With `includeStepOutputs`, when that run\n * would end the poll and `signal` is not aborted, it is fetched again at\n * once for its step outputs.\n * Such a run may still be in progress: its `status` is not terminal and the\n * run can still fail, so check `result_reported_at`, not `status`.\n *\n * When `timeoutMs` elapses first, this throws {@link SeclaiStreamingError}\n * with the latest run it has (the `runAgent()` response if no poll ran) in\n * `run`. If that run has `result_reported_at`\n * set, its `output` is the answer.\n *\n * `signal` is checked at the top of each poll, after the check for a run\n * that ends the poll. A run that has ended the poll by then, whether the\n * start run or a polled one, is returned even after an abort; the start run\n * then comes back without step outputs, even when `includeStepOutputs` is\n * set. Otherwise an abort throws `SeclaiError(\"Polling aborted.\")`, which is\n * not an `AbortError` and does not carry `signal.reason`.\n *\n * @param agentId - Agent identifier.\n * @param body - Run request payload.\n * @param opts - Polling configuration and abort signal.\n * @returns The terminal agent run, or, with `returnOnResult`, the first run\n * with `result_reported_at` set.\n * @throws {@link SeclaiStreamingError} If `timeoutMs` elapses before the run\n * finished. Its `run` holds the latest run it has (the `runAgent()`\n * response if no poll ran).\n * @throws {@link SeclaiError} `\"Polling aborted.\"` If `signal` is aborted and,\n * at the next poll's check, the run has not ended the poll. It is not an\n * `AbortError` and does not carry `signal.reason`.\n */\n async runAgentAndPoll(\n agentId: string,\n body: AgentRunRequest,\n opts?: {\n /** Polling interval in ms (default: 2000). */\n pollIntervalMs?: number;\n /** Maximum time to wait in ms (default: 300000 = 5 min). */\n timeoutMs?: number;\n /** Include per-step outputs in the final result. */\n includeStepOutputs?: boolean;\n /**\n * Return as soon as a run, the `runAgent()` response included, has\n * `result_reported_at` set (its answer is in `output`), without waiting\n * for later steps to finish (default: false).\n */\n returnOnResult?: boolean;\n signal?: AbortSignal;\n },\n ): Promise<AgentRunResponse> {\n const pollInterval = opts?.pollIntervalMs ?? 2_000;\n const timeout = opts?.timeoutMs ?? 300_000;\n const startTime = Date.now();\n\n const run = await this.runAgent(agentId, body);\n const runId = (run as any).id ?? (run as any).run_id;\n if (!runId) throw new SeclaiError(\"Agent run response did not contain an id.\");\n\n // The initial response is checked too: a fast run can already be done. It\n // carries no step outputs, so when they are asked for and it would end the\n // poll, fetch the run first.\n let current = run;\n if (opts?.includeStepOutputs) {\n const status = (run as any).status;\n if (status === \"completed\" || status === \"failed\" || status === \"cancelled\" ||\n (opts.returnOnResult && run.result_reported_at)) {\n // After an abort, skip the fetch: the loop returns the start response.\n if (!opts.signal?.aborted) current = await this.getAgentRun(runId, { includeStepOutputs: true });\n }\n }\n while (true) {\n const status = (current as any).status;\n if (status === \"completed\" || status === \"failed\" || status === \"cancelled\") {\n return current;\n }\n if (opts?.returnOnResult && current.result_reported_at) return current;\n\n if (opts?.signal?.aborted) throw new SeclaiError(\"Polling aborted.\");\n if (Date.now() - startTime > timeout) {\n const state = current.result_reported_at ? \"A result had been reported; see `run`.\" : \"No result had been reported.\";\n throw new SeclaiStreamingError(`Polling timed out after ${timeout}ms. ${state}`, runId, current);\n }\n\n await new Promise((r) => setTimeout(r, pollInterval));\n\n current = await this.getAgentRun(runId,\n opts?.includeStepOutputs ? { includeStepOutputs: true } : undefined,\n );\n }\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent Run Evaluation Results\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List evaluation results for a specific agent run.\n *\n * @param agentId - Agent identifier.\n * @param runId - Run identifier.\n * @param opts - Pagination options.\n * @returns Paginated list of evaluation results.\n */\n async listRunEvaluationResults(\n agentId: string,\n runId: string,\n opts: ListOptions = {},\n ): Promise<EvaluationResultWithCriteriaListResponse> {\n return keyedList<EvaluationResultWithCriteriaListResponse>(\n await this.request(\"GET\", `/agents/${agentId}/runs/${runId}/evaluation-results`, {\n query: { page: opts.page, limit: opts.limit },\n }),\n \"data\",\n PAGE_COUNTERS,\n );\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent Input Uploads\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Upload a file to use as input for a `dynamic_input` agent run. Any other\n * agent rejects the upload with HTTP 400. Files are limited to 200 MB.\n *\n * From API version `2026-10-16` a file of any type is accepted and is `ready`\n * at once: pass its `id` as `input_upload_id` to {@link runAgent}.\n * Earlier versions accept only a fixed list of extensions and write each\n * file's extracted text into the run's `input`, so poll\n * {@link getAgentInputUploadStatus} until `status` is `ready` before running.\n *\n * @param agentId - Agent identifier.\n * @param opts - File payload and optional metadata.\n * @returns Upload response with the upload ID and status.\n */\n async uploadAgentInput(\n agentId: string,\n opts: {\n file: Blob | Uint8Array | ArrayBuffer | BufferSource;\n fileName?: string;\n mimeType?: string;\n },\n ): Promise<UploadAgentInputApiResponse> {\n return (await this.uploadFile(`/agents/${agentId}/upload-input`, opts)) as UploadAgentInputApiResponse;\n }\n\n /**\n * Get the status of an agent input upload.\n *\n * @param agentId - Agent identifier.\n * @param uploadId - Upload identifier.\n * @returns Upload status and metadata.\n */\n async getAgentInputUploadStatus(agentId: string, uploadId: string): Promise<UploadAgentInputApiResponse> {\n return (await this.request(\"GET\", `/agents/${agentId}/input-uploads/${uploadId}`)) as UploadAgentInputApiResponse;\n }\n\n /**\n * Get the static attachment-reference contract for an agent — what files (if\n * any) its definition expects on a run.\n *\n * Call this before staging uploads to learn whether the agent accepts files\n * at all (`requires_uploads`) and which specific filenames, indexes, or glob\n * patterns its templates reference. A run-time upload batch that doesn't\n * satisfy every declared selector is rejected with HTTP 400.\n *\n * @param agentId - Agent identifier.\n * @returns The agent's attachment-reference contract.\n */\n async getAgentAttachmentReferences(agentId: string): Promise<AgentAttachmentRefsApiResponse> {\n return (await this.request(\"GET\", `/agents/${agentId}/attachment-references`)) as AgentAttachmentRefsApiResponse;\n }\n\n /**\n * Download a file attachment emitted by a step in an agent run.\n *\n * Returns the raw `Response` so you can stream or save the binary data.\n *\n * @param runId - Run identifier.\n * @param attachmentId - URL-safe-base64-encoded `storage_key` of the attachment\n * (as surfaced in run output manifests and webhook/email payloads).\n * @param opts - Optional `downloadName` filename hint for the download\n * disposition, and `signal`, which cancels the request; with a standard `fetch` this\n * includes reading the body, so `AbortSignal.timeout(ms)` bounds the whole\n * transfer.\n * @returns Raw response with the attachment bytes.\n */\n async downloadAgentRunAttachment(\n runId: string,\n attachmentId: string,\n opts: { downloadName?: string; signal?: AbortSignal } = {},\n ): Promise<Response> {\n return await this.requestRaw(\"GET\", `/v2/agent-runs/${runId}/attachments/${attachmentId}`, {\n query: { download_name: opts.downloadName },\n signal: opts.signal,\n });\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent AI Assistant (Steps Generation)\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Generate agent workflow steps from natural language using AI.\n *\n * @param agentId - Agent identifier.\n * @param body - Generation request with user instructions.\n * @returns AI-generated step configuration.\n */\n async generateAgentSteps(agentId: string, body: GenerateAgentStepsRequest): Promise<GenerateAgentStepsResponse> {\n return (await this.request(\"POST\", `/agents/${agentId}/ai-assistant/generate-steps`, { json: body })) as GenerateAgentStepsResponse;\n }\n\n /**\n * Generate a single step configuration using AI.\n *\n * @param agentId - Agent identifier.\n * @param body - Step config generation request.\n * @returns AI-generated step config.\n */\n async generateStepConfig(agentId: string, body: GenerateStepConfigRequest): Promise<GenerateStepConfigResponse> {\n return (await this.request(\"POST\", `/agents/${agentId}/ai-assistant/step-config`, { json: body })) as GenerateStepConfigResponse;\n }\n\n /**\n * Get AI conversation history for an agent.\n *\n * @param agentId - Agent identifier.\n * @returns Conversation history.\n */\n async getAgentAiConversationHistory(\n agentId: string,\n opts: { stepType?: string; stepId?: string; limit?: number; offset?: number } = {},\n ): Promise<AiConversationHistoryResponse> {\n // `step_type` is required by the API. It stays optional in the type so the\n // released one-argument call still compiles, but leaving it undefined only\n // means buildURL drops it and the server answers 422 naming the wire\n // parameter — so fail here instead, naming the option.\n if (!opts.stepType) {\n throw new SeclaiConfigurationError(\n \"getAgentAiConversationHistory requires opts.stepType; the API rejects the \" +\n \"request without it. Pass e.g. { stepType: \\\"llm\\\" }.\",\n );\n }\n return (await this.request(\"GET\", `/agents/${agentId}/ai-assistant/conversations`, {\n query: {\n step_type: opts.stepType,\n step_id: opts.stepId,\n limit: opts.limit,\n offset: opts.offset,\n },\n })) as AiConversationHistoryResponse;\n }\n\n /**\n * Mark an AI suggestion as accepted or rejected.\n *\n * @param agentId - Agent identifier.\n * @param conversationId - Conversation turn identifier.\n * @param body - Mark request payload.\n */\n async markAgentAiSuggestion(agentId: string, conversationId: string, body: MarkAiSuggestionRequest): Promise<void> {\n await this.request(\"PATCH\", `/agents/${agentId}/ai-assistant/${conversationId}`, { json: body });\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent Evaluation Criteria\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List evaluation criteria for an agent.\n *\n * @param agentId - Agent identifier.\n * @param opts - Pagination options.\n */\n async listEvaluationCriteria(agentId: string, opts: ListOptions = {}): Promise<EvaluationCriteriaResponse[]> {\n return (await this.listEvaluationCriteriaPage(agentId, opts)).data ?? [];\n }\n\n /**\n * List evaluation criteria for an agent, with pagination metadata.\n *\n * The endpoint answers with a bare array by default and with `{data,\n * pagination}` once `apiVersion` is 2026-07-27 or later; `pagination` is\n * absent on the bare array.\n *\n * @param agentId - Agent identifier.\n * @param opts - Pagination options.\n * @returns The criteria under `data`, plus the page metadata when present.\n */\n async listEvaluationCriteriaPage(\n agentId: string,\n opts: ListOptions = {},\n ): Promise<EvaluationCriteriaListResponse> {\n return keyedList<EvaluationCriteriaListResponse>(\n await this.request(\"GET\", `/agents/${agentId}/evaluation-criteria`, {\n query: { page: opts.page, limit: opts.limit },\n }),\n \"data\",\n );\n }\n\n /**\n * Create evaluation criteria for an agent.\n *\n * @param agentId - Agent identifier.\n * @param body - Criteria definition.\n * @returns Created evaluation criteria.\n */\n async createEvaluationCriteria(agentId: string, body: CreateEvaluationCriteriaRequest): Promise<EvaluationCriteriaResponse> {\n return (await this.request(\"POST\", `/agents/${agentId}/evaluation-criteria`, { json: body })) as EvaluationCriteriaResponse;\n }\n\n /**\n * Get a single evaluation criteria by ID.\n *\n * @param criteriaId - Criteria identifier.\n * @returns Evaluation criteria details.\n */\n async getEvaluationCriteria(criteriaId: string): Promise<EvaluationCriteriaResponse> {\n return (await this.request(\"GET\", `/agents/evaluation-criteria/${criteriaId}`)) as EvaluationCriteriaResponse;\n }\n\n /**\n * Update an evaluation criteria.\n *\n * @param criteriaId - Criteria identifier.\n * @param body - Fields to update.\n * @returns Updated evaluation criteria.\n */\n async updateEvaluationCriteria(criteriaId: string, body: UpdateEvaluationCriteriaRequest): Promise<EvaluationCriteriaResponse> {\n return (await this.request(\"PATCH\", `/agents/evaluation-criteria/${criteriaId}`, { json: body })) as EvaluationCriteriaResponse;\n }\n\n /**\n * Delete an evaluation criteria and all associated results.\n *\n * @param criteriaId - Criteria identifier.\n */\n async deleteEvaluationCriteria(criteriaId: string): Promise<void> {\n await this.request(\"DELETE\", `/agents/evaluation-criteria/${criteriaId}`);\n }\n\n /**\n * Get the evaluation summary for a specific criteria.\n *\n * @param criteriaId - Criteria identifier.\n * @returns Evaluation result summary.\n */\n async getEvaluationCriteriaSummary(criteriaId: string): Promise<EvaluationResultSummaryResponse> {\n return (await this.request(\"GET\", `/agents/evaluation-criteria/${criteriaId}/summary`)) as EvaluationResultSummaryResponse;\n }\n\n /**\n * List evaluation results for a specific criteria.\n *\n * @param criteriaId - Criteria identifier.\n * @param opts - Pagination, status, flag and time-range filters.\n */\n async listEvaluationResults(\n criteriaId: string,\n opts: ListEvaluationResultsOptions = {},\n ): Promise<EvaluationResultListResponse> {\n return keyedList<EvaluationResultListResponse>(\n await this.request(\"GET\", `/agents/evaluation-criteria/${criteriaId}/results`, {\n query: {\n page: opts.page,\n limit: opts.limit,\n status: opts.status,\n flagged_only: opts.flaggedOnly,\n time_from: opts.timeFrom,\n time_to: opts.timeTo,\n },\n }),\n \"data\",\n PAGE_COUNTERS,\n );\n }\n\n /**\n * Create a manual evaluation result for a criteria.\n *\n * @param criteriaId - Criteria identifier.\n * @param body - Evaluation result payload.\n * @returns Created evaluation result.\n */\n async createEvaluationResult(criteriaId: string, body: CreateEvaluationResultRequest): Promise<EvaluationResultResponse> {\n return (await this.request(\"POST\", `/agents/evaluation-criteria/${criteriaId}/results`, { json: body })) as EvaluationResultResponse;\n }\n\n /**\n * List runs compatible with a specific evaluation criteria.\n *\n * @param criteriaId - Criteria identifier.\n * @param opts - Pagination and a `startedAfter` filter.\n */\n async listCompatibleRuns(criteriaId: string, opts: ListCompatibleRunsOptions = {}): Promise<CompatibleRunListResponse> {\n return keyedList<CompatibleRunListResponse>(\n await this.request(\"GET\", `/agents/evaluation-criteria/${criteriaId}/compatible-runs`, {\n query: { page: opts.page, limit: opts.limit, started_after: opts.startedAfter },\n }),\n \"data\",\n PAGE_COUNTERS,\n );\n }\n\n /**\n * Test a draft evaluation criteria without persisting it.\n *\n * @param agentId - Agent identifier.\n * @param body - Draft evaluation to test.\n * @returns Test evaluation response.\n */\n async testDraftEvaluation(agentId: string, body: TestDraftEvaluationRequest): Promise<TestDraftEvaluationResponse> {\n return (await this.request(\"POST\", `/agents/${agentId}/evaluation-criteria/test-draft`, { json: body })) as TestDraftEvaluationResponse;\n }\n\n /**\n * List all evaluation results for an agent.\n *\n * @param agentId - Agent identifier.\n * @param opts - Pagination, status, step, flag and time-range filters.\n */\n async listAgentEvaluationResults(\n agentId: string,\n opts: ListAgentEvaluationResultsOptions = {},\n ): Promise<EvaluationResultWithCriteriaListResponse> {\n return keyedList<EvaluationResultWithCriteriaListResponse>(\n await this.request(\"GET\", `/agents/${agentId}/evaluation-results`, {\n query: {\n page: opts.page,\n limit: opts.limit,\n status: opts.status,\n step: opts.step,\n flagged_only: opts.flaggedOnly,\n time_from: opts.timeFrom,\n time_to: opts.timeTo,\n },\n }),\n \"data\",\n PAGE_COUNTERS,\n );\n }\n\n /**\n * List evaluation run summaries for an agent.\n *\n * @param agentId - Agent identifier.\n * @param opts - Pagination, status, step and time-range filters.\n */\n async listEvaluationRuns(agentId: string, opts: ListEvaluationRunsOptions = {}): Promise<EvaluationRunSummaryListResponse> {\n return keyedList<EvaluationRunSummaryListResponse>(\n await this.request(\"GET\", `/agents/${agentId}/evaluation-runs`, {\n query: {\n page: opts.page,\n limit: opts.limit,\n status: opts.status,\n step: opts.step,\n time_from: opts.timeFrom,\n time_to: opts.timeTo,\n },\n }),\n \"data\",\n PAGE_COUNTERS,\n );\n }\n\n /**\n * Get a summary of non-manual evaluations, for one agent or the whole account.\n *\n * @param agentId - Agent identifier. Omit (pass `undefined`) for the account-wide summary.\n * @param opts - Date range. `startDate` and `endDate` together set the range;\n * `startDate` alone runs from it through today; otherwise the last `days`\n * days apply (server default 30), and an `endDate` without `startDate` is ignored.\n */\n async getNonManualEvaluationSummary(\n agentId?: string,\n opts: DateRangeOptions = {},\n ): Promise<NonManualEvaluationSummaryResponse> {\n return (await this.request(\"GET\", \"/agents/evaluation-results/non-manual-summary\", {\n query: { agent_id: agentId, days: opts.days, start_date: opts.startDate, end_date: opts.endDate },\n })) as NonManualEvaluationSummaryResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent Email Triggers\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Configure an agent's `EMAIL_RECEIVED` trigger and return its computed\n * email address(es).\n *\n * Sets the custom alias, the sender allowlist, and the inbound-handling flags\n * (`ignore_auto_generated`, `require_sender_auth`, `queue_on_quota`). Omitted\n * fields are left unchanged; passing `null` (or `\"\"` for `alias`) clears them.\n *\n * @param agentId - Agent identifier.\n * @param triggerId - Trigger identifier.\n * @param body - The fields to set.\n * @returns The trigger's resolved addresses and config.\n */\n async setEmailTriggerConfig(\n agentId: string,\n triggerId: string,\n body: SetEmailTriggerConfigRequest,\n ): Promise<EmailTriggerConfigResponse> {\n return (await this.request(\"PUT\", `/agents/${agentId}/triggers/${triggerId}/email-config`, {\n json: body,\n })) as EmailTriggerConfigResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent Slack Triggers\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Configure an agent's `SLACK_COMMAND` trigger, which people run from Slack\n * with `/seclai` or the message shortcut.\n *\n * Sets the Slack connection, `alias` (the name people type after `/seclai`),\n * form, channels, reply visibility and conversation settings. Omitted fields\n * are left unchanged. `input` is deprecated and ignored by the API.\n *\n * @param agentId - Agent identifier.\n * @param triggerId - Trigger identifier.\n * @param body - The fields to set.\n * @returns The trigger's full Slack config, including any `missing_scopes`.\n */\n async setSlackTriggerConfig(\n agentId: string,\n triggerId: string,\n body: SetSlackTriggerConfigRequest,\n ): Promise<SlackTriggerConfigResponse> {\n return (await this.request(\"PUT\", `/agents/${agentId}/triggers/${triggerId}/slack-config`, {\n json: body,\n })) as SlackTriggerConfigResponse;\n }\n\n /**\n * Replace the input attachments a trigger accepts.\n *\n * A run's files are each assigned to one declared attachment before any step\n * runs, and steps reference one as `{{agent.attachments.<name>}}`. The API\n * answers 400 when the agent references an attachment the new declaration\n * leaves out.\n *\n * @param agentId - Agent identifier.\n * @param triggerId - Trigger identifier, as `getAgent()` returns it.\n * @param body - The full list of accepted attachments; a slot's `min` defaults to 0.\n * @returns The trigger's accepted attachments.\n */\n async setAcceptedAttachments(\n agentId: string,\n triggerId: string,\n body: SetAcceptedAttachmentsInput,\n ): Promise<AcceptedAttachmentsResponse> {\n return (await this.request(\"PUT\", `/agents/${agentId}/triggers/${triggerId}/accepted-attachments`, {\n json: body,\n })) as AcceptedAttachmentsResponse;\n }\n\n /**\n * Get the run metadata keys a trigger declares.\n *\n * Steps may reference a declared key as `{{metadata.<key>}}`. The response\n * also lists the system and source keys the trigger's type can declare.\n *\n * @param agentId - Agent identifier.\n * @param triggerId - Trigger identifier, as `getAgent()` returns it.\n * @returns The trigger's declared and declarable metadata keys.\n */\n async getMetadataKeys(agentId: string, triggerId: string): Promise<MetadataKeysResponse> {\n return (await this.request(\n \"GET\",\n `/agents/${agentId}/triggers/${triggerId}/metadata-keys`,\n )) as MetadataKeysResponse;\n }\n\n /**\n * Replace the run metadata keys a trigger declares.\n *\n * The body is the whole declaration and replaces the current one. The API\n * answers 400 when the agent references a key that no trigger of its branch\n * declares.\n *\n * @param agentId - Agent identifier.\n * @param triggerId - Trigger identifier, as `getAgent()` returns it.\n * @param body - The full declaration; each key's `required` defaults to `false`.\n * @returns The trigger's metadata keys, with `warnings` naming agents whose\n * `call_agent` mapping no longer fits.\n */\n async setMetadataKeys(\n agentId: string,\n triggerId: string,\n body: SetMetadataKeysRequest,\n ): Promise<MetadataKeysResponse> {\n return (await this.request(\"PUT\", `/agents/${agentId}/triggers/${triggerId}/metadata-keys`, {\n json: body,\n })) as MetadataKeysResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent Email Governance\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List recipients who have opted out of this account's agent emails.\n *\n * @param opts - Optional agent filter and `limit`/`offset` pagination.\n * @param opts.agentId - Filter to one agent (account-wide opt-outs still apply).\n * @param opts.limit - Page size (1-200, default 50).\n * @param opts.offset - Rows to skip (default 0).\n * @returns The page of opt-outs plus the total count.\n */\n async listAgentEmailOptOuts(\n opts: { agentId?: string; limit?: number; offset?: number } = {},\n ): Promise<AgentEmailOptOutListResponse> {\n return keyedList<AgentEmailOptOutListResponse>(\n await this.request(\"GET\", \"/agents/agent-email-optouts\", {\n query: { agent_id: opts.agentId, limit: opts.limit, offset: opts.offset },\n }),\n \"items\",\n [\"total\"],\n );\n }\n\n /**\n * Revoke an opt-out, opting the recipient back in to agent emails.\n *\n * @param optoutId - Opt-out identifier.\n */\n async removeAgentEmailOptOut(optoutId: string): Promise<void> {\n await this.request(\"DELETE\", `/agents/agent-email-optouts/${optoutId}`);\n }\n\n /**\n * List the account's blocked inbound email senders (newest first), plus the\n * governance `auto_block_mode`.\n *\n * @param opts - Optional `limit`/`offset` pagination.\n * @param opts.limit - Page size (1-200, default 50).\n * @param opts.offset - Rows to skip (default 0).\n */\n async listBlockedEmailSenders(\n opts: OffsetPageOptions = {},\n ): Promise<BlockedEmailSenderListResponse> {\n return keyedList<BlockedEmailSenderListResponse>(\n await this.request(\"GET\", \"/agents/blocked-email-senders\", {\n query: { limit: opts.limit, offset: opts.offset },\n }),\n \"items\",\n [\"total\"],\n );\n }\n\n /**\n * Add a sender address or a whole domain to the account blocklist.\n *\n * Idempotent. `match_type` is `\"address\"` (default) or `\"domain\"`.\n * Requires an account owner/admin.\n *\n * @param body - The sender or domain to block.\n * @returns The blocked-sender entry.\n */\n async blockEmailSender(body: BlockEmailSenderRequest): Promise<BlockedEmailSenderResponse> {\n return (await this.request(\"POST\", \"/agents/blocked-email-senders\", {\n json: body,\n })) as BlockedEmailSenderResponse;\n }\n\n /**\n * Remove a blocked sender by id. Requires an account owner/admin.\n *\n * @param blockedId - Blocked-sender identifier.\n */\n async unblockEmailSender(blockedId: string): Promise<void> {\n await this.request(\"DELETE\", `/agents/blocked-email-senders/${blockedId}`);\n }\n\n /**\n * Set whether a governance BLOCK on an authenticated inbound sender\n * auto-adds them to the blocklist.\n *\n * `mode` is `\"disabled\"`, `\"input\"`, or `\"input_and_output\"`.\n * Requires an account owner/admin.\n *\n * @param body - The mode to set.\n * @returns The updated blocked-sender list.\n */\n async setAutoBlockMode(body: SetAutoBlockModeRequest): Promise<BlockedEmailSenderListResponse> {\n return keyedList<BlockedEmailSenderListResponse>(\n await this.request(\"PUT\", \"/agents/blocked-email-senders/mode\", { json: body }),\n \"items\",\n [\"total\"],\n );\n }\n\n /**\n * List recent inbound emails that were quietly discarded before running an\n * agent (unauthorized sender, unknown alias, spam/virus, flood-shed).\n *\n * @param opts - Optional agent filter and result limit.\n * @param opts.agentId - Filter to a single agent's rejections.\n * @param opts.limit - Maximum results (1-200, default 50).\n */\n async listInboundEmailRejections(\n opts: { agentId?: string; limit?: number } = {},\n ): Promise<InboundEmailRejectionResponse[]> {\n return listItems<InboundEmailRejectionResponse>(\n await this.request(\"GET\", \"/agents/inbound-email-rejections\", {\n query: { agent_id: opts.agentId, limit: opts.limit },\n }),\n );\n }\n\n /**\n * Get the account's inbound-email overload status — whether the circuit\n * breaker has paused new inbound email, and the size of the QUEUED\n * (over-quota parked) run backlog.\n */\n async getInboundEmailStatus(): Promise<InboundEmailStatusResponse> {\n return (await this.request(\"GET\", \"/agents/inbound-email-status\")) as InboundEmailStatusResponse;\n }\n\n /**\n * Fail all of the account's QUEUED (over-quota parked) inbound-email runs at\n * once.\n *\n * A queued run consumed no quota or credits at queue time, so this merely\n * fails them. Requires an account owner/admin.\n *\n * @returns The count cancelled.\n */\n async cancelQueuedEmailRuns(): Promise<CancelQueuedRunsResponse> {\n return (await this.request(\"POST\", \"/agents/inbound-email-status/cancel-queued\")) as CancelQueuedRunsResponse;\n }\n\n /**\n * Manually lift the account-wide inbound-email pause.\n *\n * If the queued backlog is still above the ceiling the breaker re-arms on the\n * next evaluation — this is a one-shot override, not a permanent disable.\n * Requires an account owner/admin.\n */\n async resumeInboundEmail(): Promise<ResumeInboundResponse> {\n return (await this.request(\"POST\", \"/agents/inbound-email-status/resume\")) as ResumeInboundResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Knowledge Bases\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List knowledge bases.\n *\n * @param opts - Pagination and sorting options.\n * @returns Paginated list of knowledge bases.\n */\n async listKnowledgeBases(opts: SortableListOptions = {}): Promise<KnowledgeBaseListResponse> {\n return keyedList<KnowledgeBaseListResponse>(\n await this.request(\"GET\", \"/knowledge_bases\", {\n query: { page: opts.page, limit: opts.limit, sort: opts.sort, order: opts.order },\n }),\n \"knowledge_bases\",\n PAGE_COUNTERS,\n );\n }\n\n /**\n * Create a new knowledge base.\n *\n * @param body - Knowledge base configuration.\n * @returns The created knowledge base.\n */\n async createKnowledgeBase(body: CreateKnowledgeBaseBody): Promise<KnowledgeBaseResponse> {\n return (await this.request(\"POST\", \"/knowledge_bases\", { json: body })) as KnowledgeBaseResponse;\n }\n\n /**\n * Get a knowledge base by ID.\n *\n * @param knowledgeBaseId - Knowledge base identifier.\n * @returns Knowledge base details.\n */\n async getKnowledgeBase(knowledgeBaseId: string): Promise<KnowledgeBaseResponse> {\n return (await this.request(\"GET\", `/knowledge_bases/${knowledgeBaseId}`)) as KnowledgeBaseResponse;\n }\n\n /**\n * Get the item-metadata keys seen in a knowledge base's content.\n *\n * Reports, for all time and the last 30 and 7 days, each key's item count,\n * number of distinct values and five most frequent values.\n *\n * @param knowledgeBaseId - Knowledge base identifier.\n * @returns The key statistics per window.\n */\n async getKnowledgeBaseMetadataKeyStats(knowledgeBaseId: string): Promise<KnowledgeBaseMetadataKeyStatsResponse> {\n return (await this.request(\n \"GET\",\n `/knowledge_bases/${knowledgeBaseId}/metadata-key-stats`,\n )) as KnowledgeBaseMetadataKeyStatsResponse;\n }\n\n /**\n * Update a knowledge base.\n *\n * @param knowledgeBaseId - Knowledge base identifier.\n * @param body - Fields to update.\n * @returns Updated knowledge base.\n */\n async updateKnowledgeBase(knowledgeBaseId: string, body: UpdateKnowledgeBaseBody): Promise<KnowledgeBaseResponse> {\n return (await this.request(\"PUT\", `/knowledge_bases/${knowledgeBaseId}`, { json: body })) as KnowledgeBaseResponse;\n }\n\n /**\n * Delete a knowledge base.\n *\n * @param knowledgeBaseId - Knowledge base identifier.\n */\n async deleteKnowledgeBase(knowledgeBaseId: string): Promise<void> {\n await this.request(\"DELETE\", `/knowledge_bases/${knowledgeBaseId}`);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Memory Banks\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List memory banks.\n *\n * @param opts - Pagination, sorting and a `type` filter.\n * @returns Paginated list of memory banks.\n */\n async listMemoryBanks(opts: ListMemoryBanksOptions = {}): Promise<MemoryBankListResponse> {\n return keyedList<MemoryBankListResponse>(\n await this.request(\"GET\", \"/memory_banks\", {\n query: { page: opts.page, limit: opts.limit, sort: opts.sort, order: opts.order, type: opts.type },\n }),\n \"memory_banks\",\n PAGE_COUNTERS,\n );\n }\n\n /**\n * Create a new memory bank.\n *\n * Memory banks give agents persistent memory across conversations.\n * Types: `conversation` (chat-style history) or `general` (flat factual entries).\n *\n * @param body - Memory bank configuration.\n * @returns The created memory bank.\n */\n async createMemoryBank(body: CreateMemoryBankBody): Promise<MemoryBankResponse> {\n return (await this.request(\"POST\", \"/memory_banks\", { json: body })) as MemoryBankResponse;\n }\n\n /**\n * Get a memory bank by ID.\n *\n * @param memoryBankId - Memory bank identifier.\n * @returns Memory bank details.\n */\n async getMemoryBank(memoryBankId: string): Promise<MemoryBankResponse> {\n return (await this.request(\"GET\", `/memory_banks/${memoryBankId}`)) as MemoryBankResponse;\n }\n\n /**\n * Update a memory bank.\n *\n * @param memoryBankId - Memory bank identifier.\n * @param body - Fields to update.\n * @returns Updated memory bank.\n */\n async updateMemoryBank(memoryBankId: string, body: UpdateMemoryBankBody): Promise<MemoryBankResponse> {\n return (await this.request(\"PUT\", `/memory_banks/${memoryBankId}`, { json: body })) as MemoryBankResponse;\n }\n\n /**\n * Delete a memory bank.\n *\n * @param memoryBankId - Memory bank identifier.\n */\n async deleteMemoryBank(memoryBankId: string): Promise<void> {\n await this.request(\"DELETE\", `/memory_banks/${memoryBankId}`);\n }\n\n /**\n * Get agents that are using a specific memory bank.\n *\n * @param memoryBankId - Memory bank identifier.\n */\n async getAgentsUsingMemoryBank(memoryBankId: string): Promise<unknown> {\n return listItems<unknown>(await this.request(\"GET\", `/memory_banks/${memoryBankId}/agents`));\n }\n\n /**\n * Get stats for a memory bank.\n *\n * @param memoryBankId - Memory bank identifier.\n * @param opts - Date range. Only `startDate` and `endDate` together replace\n * `days`; either one alone is ignored and the last `days` days apply (server default 30).\n */\n async getMemoryBankStats(memoryBankId: string, opts: DateRangeOptions = {}): Promise<unknown> {\n return await this.request(\"GET\", `/memory_banks/${memoryBankId}/stats`, {\n query: { days: opts.days, start_date: opts.startDate, end_date: opts.endDate },\n });\n }\n\n /**\n * Compact a memory bank (trigger compaction).\n *\n * @param memoryBankId - Memory bank identifier.\n */\n async compactMemoryBank(memoryBankId: string): Promise<void> {\n await this.request(\"POST\", `/memory_banks/${memoryBankId}/compact`);\n }\n\n /**\n * Delete a memory bank source.\n *\n * @param memoryBankId - Memory bank identifier.\n */\n async deleteMemoryBankSource(memoryBankId: string): Promise<void> {\n await this.request(\"DELETE\", `/memory_banks/${memoryBankId}/source`);\n }\n\n /**\n * Test compaction for a specific memory bank.\n *\n * @param memoryBankId - Memory bank identifier.\n * @param body - Test compaction request.\n */\n async testMemoryBankCompaction(memoryBankId: string, body: TestCompactionRequest): Promise<CompactionTestResponse> {\n return (await this.request(\"POST\", `/memory_banks/${memoryBankId}/test-compaction`, { json: body })) as CompactionTestResponse;\n }\n\n /**\n * Test compaction prompt standalone (not tied to a specific memory bank).\n *\n * @param body - Standalone compaction test request.\n */\n async testCompactionPromptStandalone(body: StandaloneTestCompactionRequest): Promise<CompactionTestResponse> {\n return (await this.request(\"POST\", \"/memory_banks/test-compaction\", { json: body })) as CompactionTestResponse;\n }\n\n /**\n * List available memory bank templates.\n */\n async listMemoryBankTemplates(): Promise<unknown> {\n return listItems<unknown>(await this.request(\"GET\", \"/memory_banks/templates\"));\n }\n\n // ─── Memory Bank AI Assistant ──────────────────────────────────────────────\n\n /**\n * Generate memory bank configuration using AI.\n *\n * @param body - AI assistant request with user instructions.\n * @returns AI-generated memory bank config.\n */\n async generateMemoryBankConfig(body: MemoryBankAiAssistantRequest): Promise<MemoryBankAiAssistantResponse> {\n return (await this.request(\"POST\", \"/memory_banks/ai-assistant\", { json: body })) as MemoryBankAiAssistantResponse;\n }\n\n /**\n * Get the last AI conversation for memory banks.\n *\n * @param opts - Turns to return (server default 5) and most-recent turns to skip (default 0).\n */\n async getMemoryBankAiLastConversation(opts: OffsetPageOptions = {}): Promise<MemoryBankLastConversationResponse> {\n return (await this.request(\"GET\", \"/memory_banks/ai-assistant/last-conversation\", {\n query: { limit: opts.limit, offset: opts.offset },\n })) as MemoryBankLastConversationResponse;\n }\n\n /**\n * Accept a memory bank AI suggestion.\n *\n * @param conversationId - Conversation identifier.\n * @param body - Accept request payload.\n */\n async acceptMemoryBankAiSuggestion(conversationId: string, body: MemoryBankAcceptRequest): Promise<OkResponse> {\n return (await this.request(\"PATCH\", `/memory_banks/ai-assistant/${conversationId}`, { json: body })) as OkResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Sources\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List sources.\n *\n * @param opts - Pagination, sorting, and filter options.\n * @returns Paginated list of sources.\n */\n async listSources(\n opts: SortableListOptions & { accountId?: string } = {},\n ): Promise<SourceListResponse> {\n return (await this.request(\"GET\", \"/sources\", {\n query: {\n page: opts.page,\n limit: opts.limit,\n sort: opts.sort,\n order: opts.order,\n account_id: opts.accountId,\n },\n })) as SourceListResponse;\n }\n\n /**\n * Create a new content source.\n *\n * @param body - Source configuration (type, name, knowledge base link, etc.).\n * @returns The created source.\n */\n async createSource(body: CreateSourceBody): Promise<SourceResponse> {\n return (await this.request(\"POST\", \"/sources\", { json: body })) as SourceResponse;\n }\n\n /**\n * Get a source by ID.\n *\n * @param sourceId - Source connection identifier.\n * @returns Source details.\n */\n async getSource(sourceId: string): Promise<SourceResponse> {\n return (await this.request(\"GET\", `/sources/${sourceId}`)) as SourceResponse;\n }\n\n /**\n * Update a source.\n *\n * @param sourceId - Source connection identifier.\n * @param body - Fields to update.\n * @returns Updated source.\n */\n async updateSource(sourceId: string, body: UpdateSourceBody): Promise<SourceResponse> {\n return (await this.request(\"PUT\", `/sources/${sourceId}`, { json: body })) as SourceResponse;\n }\n\n /**\n * Delete a source.\n *\n * @param sourceId - Source connection identifier.\n */\n async deleteSource(sourceId: string): Promise<void> {\n await this.request(\"DELETE\", `/sources/${sourceId}`);\n }\n\n /**\n * Upload a file to a source.\n *\n * Maximum file size: 200 MiB. Supports text, PDF, DOCX, audio, video, images, and more.\n * If `mimeType` is omitted, it will be inferred from the `fileName` extension when possible.\n *\n * @param sourceId - Source connection identifier.\n * @param opts - File payload and optional metadata.\n * @returns Upload response details.\n */\n async uploadFileToSource(\n sourceId: string,\n opts: {\n file: Blob | Uint8Array | ArrayBuffer | BufferSource;\n title?: string;\n metadata?: Record<string, unknown>;\n fileName?: string;\n mimeType?: string;\n },\n ): Promise<FileUploadResponse> {\n return (await this.uploadFile(`/sources/${sourceId}/upload`, opts)) as FileUploadResponse;\n }\n\n /**\n * Upload inline text to a source.\n *\n * @param sourceId - Source connection identifier.\n * @param body - Inline text upload payload.\n * @returns Upload response.\n */\n async uploadInlineTextToSource(sourceId: string, body: InlineTextUploadRequest): Promise<FileUploadResponse> {\n return (await this.request(\"POST\", `/sources/${sourceId}`, { json: body })) as FileUploadResponse;\n }\n\n /**\n * List a source's content items and their indexing status.\n *\n * @param sourceId - Source connection identifier.\n * @param opts - Pagination, sorting, and filters. Pass the `content_version_id`\n * values the upload methods return as `contentVersionIds` to poll a batch of\n * uploads in one request — about 100 at a time, since the ids travel in the\n * query string and a URL over 8,192 bytes is rejected with a 414. An empty\n * `contentVersionIds` matches nothing, so it returns an empty page without\n * sending a request.\n * @returns The items under `data` with `pagination`, on every API version.\n */\n async listSourceContents(\n sourceId: string,\n opts: ListSourceContentsOptions = {},\n ): Promise<SourceContentStatusListResponse> {\n if (opts.contentVersionIds?.length === 0) {\n return {\n data: [],\n pagination: {\n page: opts.page ?? 1,\n limit: opts.limit ?? 20,\n total: 0,\n pages: 0,\n has_next: false,\n has_prev: false,\n },\n };\n }\n return (await this.request(\"GET\", `/sources/${sourceId}/contents`, {\n query: {\n page: opts.page,\n limit: opts.limit,\n sort: opts.sort,\n order: opts.order,\n status: opts.status,\n content_version_id: opts.contentVersionIds,\n },\n })) as SourceContentStatusListResponse;\n }\n\n /**\n * Get one content item's indexing status.\n *\n * @param sourceId - Source connection identifier.\n * @param contentVersionId - The `content_version_id` an upload returned.\n */\n async getSourceContentStatus(sourceId: string, contentVersionId: string): Promise<SourceContentStatusResponse> {\n return (await this.request(\n \"GET\",\n `/sources/${sourceId}/contents/${contentVersionId}`,\n )) as SourceContentStatusResponse;\n }\n\n /**\n * List mail an email content source refused, newest first.\n *\n * Each entry says who sent the message and why it was refused, never its\n * subject or body. To accept a refused sender, add its `from_address` or that\n * address's domain to the source's `email_allowed_senders` — which only helps\n * when `authenticated` is true. Requires an account owner or administrator;\n * the API answers 404 for a source that is not an email source.\n *\n * @param sourceId - Source connection identifier.\n * @param opts - Pagination options (`limit` 1-100).\n * @returns The rejections under `data` with `pagination`.\n */\n async listEmailSourceRejections(\n sourceId: string,\n opts: ListOptions = {},\n ): Promise<EmailSourceRejectionListResponse> {\n return (await this.request(\"GET\", `/sources/${sourceId}/email-rejections`, {\n query: { page: opts.page, limit: opts.limit },\n })) as EmailSourceRejectionListResponse;\n }\n\n // ─── Source Exports ────────────────────────────────────────────────────────\n\n /**\n * List exports for a source.\n *\n * @param sourceId - Source connection identifier.\n * @param opts - Pagination options.\n * @returns Paginated list of exports.\n */\n async listSourceExports(sourceId: string, opts: ListOptions = {}): Promise<ExportListResponse> {\n return (await this.request(\"GET\", `/sources/${sourceId}/exports`, {\n query: { page: opts.page, limit: opts.limit },\n })) as ExportListResponse;\n }\n\n /**\n * Create a source data export.\n *\n * @param sourceId - Source connection identifier.\n * @param body - Export configuration (format, etc.).\n * @returns Export response with job status.\n */\n async createSourceExport(sourceId: string, body: CreateExportRequest): Promise<ExportResponse> {\n return (await this.request(\"POST\", `/sources/${sourceId}/exports`, { json: body })) as ExportResponse;\n }\n\n /**\n * Get a specific source export.\n *\n * @param sourceId - Source connection identifier.\n * @param exportId - Export identifier.\n * @returns Export details.\n */\n async getSourceExport(sourceId: string, exportId: string): Promise<ExportResponse> {\n return (await this.request(\"GET\", `/sources/${sourceId}/exports/${exportId}`)) as ExportResponse;\n }\n\n /**\n * Cancel a source export.\n *\n * @param sourceId - Source connection identifier.\n * @param exportId - Export identifier.\n */\n async cancelSourceExport(sourceId: string, exportId: string): Promise<ExportResponse> {\n return (await this.request(\"POST\", `/sources/${sourceId}/exports/${exportId}/cancel`)) as ExportResponse;\n }\n\n /**\n * Download a source export file.\n *\n * Returns the raw `Response` so you can stream or save the binary data.\n *\n * @param sourceId - Source connection identifier.\n * @param exportId - Export identifier.\n * @param opts - Optional `signal`, which cancels the request; with a standard `fetch` this\n * includes reading the body, so `AbortSignal.timeout(ms)` bounds the whole\n * transfer.\n * @returns Raw response with the export file.\n */\n async downloadSourceExport(\n sourceId: string,\n exportId: string,\n opts: { signal?: AbortSignal } = {},\n ): Promise<Response> {\n return await this.requestRaw(\"GET\", `/sources/${sourceId}/exports/${exportId}/download`, {\n signal: opts.signal,\n });\n }\n\n /**\n * Estimate a source export.\n *\n * @param sourceId - Source connection identifier.\n * @param body - Estimate request.\n * @returns Export estimate.\n */\n async estimateSourceExport(sourceId: string, body: EstimateExportRequest): Promise<EstimateExportResponse> {\n return (await this.request(\"POST\", `/sources/${sourceId}/exports/estimate`, { json: body })) as EstimateExportResponse;\n }\n\n /**\n * Delete a source export.\n *\n * @param sourceId - Source connection identifier.\n * @param exportId - Export identifier.\n */\n async deleteSourceExport(sourceId: string, exportId: string): Promise<void> {\n await this.request(\"DELETE\", `/sources/${sourceId}/exports/${exportId}`);\n }\n\n // ─── Source Embedding Migrations ───────────────────────────────────────────\n\n /**\n * Get the status of a source embedding migration.\n *\n * @param sourceId - Source connection identifier.\n * @returns Migration status.\n */\n async getSourceEmbeddingMigration(sourceId: string): Promise<SourceEmbeddingMigrationResponse> {\n return (await this.request(\"GET\", `/sources/${sourceId}/embedding-migration`)) as SourceEmbeddingMigrationResponse;\n }\n\n /**\n * Start a source embedding migration.\n *\n * @param sourceId - Source connection identifier.\n * @param body - Migration configuration (target embedding model, etc.).\n * @returns Migration status.\n */\n async startSourceEmbeddingMigration(sourceId: string, body: StartSourceEmbeddingMigrationRequest): Promise<SourceEmbeddingMigrationResponse> {\n return (await this.request(\"POST\", `/sources/${sourceId}/embedding-migration`, { json: body })) as SourceEmbeddingMigrationResponse;\n }\n\n /**\n * Cancel a source embedding migration.\n *\n * @param sourceId - Source connection identifier.\n * @returns Updated migration status.\n */\n async cancelSourceEmbeddingMigration(sourceId: string): Promise<SourceEmbeddingMigrationResponse> {\n return (await this.request(\"POST\", `/sources/${sourceId}/embedding-migration/cancel`)) as SourceEmbeddingMigrationResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Content\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Get content detail for a specific content version.\n *\n * @param contentVersionId - Content version identifier.\n * @param opts - Range options for slicing large content.\n * @returns Content details for the requested range.\n */\n async getContentDetail(\n contentVersionId: string,\n opts: { start?: number; end?: number } = {},\n ): Promise<ContentDetailResponse> {\n return (await this.request(\"GET\", `/contents/${contentVersionId}`, {\n query: { start: opts.start ?? 0, end: opts.end ?? 5000 },\n })) as ContentDetailResponse;\n }\n\n /**\n * Replace content with inline text.\n *\n * @param contentVersionId - Content version identifier.\n * @param body - Inline text replacement payload.\n */\n async replaceContentWithInlineText(contentVersionId: string, body: InlineTextReplaceRequest): Promise<ContentFileUploadResponse> {\n return (await this.request(\"PUT\", `/contents/${contentVersionId}`, { json: body })) as ContentFileUploadResponse;\n }\n\n /**\n * Delete a specific content version.\n *\n * @param contentVersionId - Content version identifier.\n */\n async deleteContent(contentVersionId: string): Promise<void> {\n await this.request(\"DELETE\", `/contents/${contentVersionId}`);\n }\n\n /**\n * List embeddings for a content version.\n *\n * @param contentVersionId - Content version identifier.\n * @param opts - Pagination options.\n * @returns Paginated list of embeddings.\n */\n async listContentEmbeddings(\n contentVersionId: string,\n opts: ListOptions = {},\n ): Promise<ContentEmbeddingsListResponse> {\n return (await this.request(\"GET\", `/contents/${contentVersionId}/embeddings`, {\n query: { page: opts.page ?? 1, limit: opts.limit ?? 20 },\n })) as ContentEmbeddingsListResponse;\n }\n\n /**\n * List the files attached to a content item.\n *\n * Files arrive from an agent's `write_content_attachment` step, with an email\n * message, from an RSS feed's `feed_attachments`, from a web page's media, or\n * as the images inside a document. Each entry says whether it is indexed for\n * search and, when indexing failed, why.\n *\n * @param contentVersionId - Content version identifier.\n * @param opts - Pagination options.\n * @returns The attachments under `data` with `pagination`.\n */\n async listContentAttachments(\n contentVersionId: string,\n opts: ListOptions = {},\n ): Promise<ContentAttachmentsListResponse> {\n return (await this.request(\"GET\", `/contents/${contentVersionId}/attachments`, {\n query: { page: opts.page, limit: opts.limit },\n })) as ContentAttachmentsListResponse;\n }\n\n /**\n * Get one file attached to a content item: its indexing status and reason,\n * its metadata, and the text it is indexed by.\n *\n * @param contentVersionId - Content version identifier.\n * @param attachmentId - The `id` of an entry from {@link listContentAttachments}.\n * @param opts - `start` and `end` character offsets for paging through long text\n * (server defaults 0 and 5000). Both are sent as given, so `end: 0` asks for\n * the metadata without any text. A file that was not indexed has no text.\n * @returns The attachment with the requested range of its text.\n * @throws {SeclaiAPIStatusError} 402 when the account has no credits left\n * (`error.code` `insufficient_credits`).\n */\n async getContentAttachment(\n contentVersionId: string,\n attachmentId: string,\n opts: { start?: number; end?: number } = {},\n ): Promise<ContentAttachmentDetailResponse> {\n return (await this.request(\"GET\", `/contents/${contentVersionId}/attachments/${attachmentId}`, {\n query: { start: opts.start, end: opts.end },\n })) as ContentAttachmentDetailResponse;\n }\n\n /**\n * List the embeddings (chunk vectors) a content attachment is indexed by.\n * The list is empty for a file that has no completed index.\n *\n * @param contentVersionId - Content version identifier.\n * @param attachmentId - Attachment identifier.\n * @param opts - Pagination options (`limit` 1-100).\n * @returns Paginated list of embeddings.\n * @throws {SeclaiAPIStatusError} 402 when the account has no credits left\n * (`error.code` `insufficient_credits`).\n */\n async listContentAttachmentEmbeddings(\n contentVersionId: string,\n attachmentId: string,\n opts: ListOptions = {},\n ): Promise<ContentEmbeddingsListResponse> {\n return (await this.request(\"GET\", `/contents/${contentVersionId}/attachments/${attachmentId}/embeddings`, {\n query: { page: opts.page, limit: opts.limit },\n })) as ContentEmbeddingsListResponse;\n }\n\n /**\n * Download a content attachment's bytes.\n *\n * Returns the raw `Response` so you can stream or save the binary data. The\n * API answers 403 when the file is withheld — blocked or redacted by a\n * governance policy, or still being indexed after arriving from outside; the\n * attachment's `file_withheld` field says which before you ask.\n *\n * @param contentVersionId - Content version identifier.\n * @param attachmentId - Attachment identifier.\n * @param opts - Optional `signal`, which cancels the request; with a standard `fetch` this\n * includes reading the body, so `AbortSignal.timeout(ms)` bounds the whole\n * transfer.\n * @returns Raw response with the attachment bytes.\n * @throws {SeclaiAPIStatusError} 403 when the file is withheld, and 402 when\n * the account has no credits left (`error.code` `insufficient_credits`).\n */\n async downloadContentAttachment(\n contentVersionId: string,\n attachmentId: string,\n opts: { signal?: AbortSignal } = {},\n ): Promise<Response> {\n return await this.requestRaw(\"GET\", `/contents/${contentVersionId}/attachments/${attachmentId}/file`, {\n signal: opts.signal,\n });\n }\n\n /**\n * Upload a file to replace content for an existing content version.\n *\n * @param contentVersionId - Content version identifier.\n * @param opts - File payload and optional metadata.\n * @returns Upload response.\n */\n async uploadFileToContent(\n contentVersionId: string,\n opts: {\n file: Blob | Uint8Array | ArrayBuffer | BufferSource;\n title?: string;\n metadata?: Record<string, unknown>;\n fileName?: string;\n mimeType?: string;\n },\n ): Promise<ContentFileUploadResponse> {\n return (await this.uploadFile(`/contents/${contentVersionId}/upload`, opts)) as ContentFileUploadResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Solutions\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List solutions.\n *\n * @param opts - Pagination, sorting and a name `search`.\n * @returns Paginated list of solutions.\n */\n async listSolutions(opts: ListSolutionsOptions = {}): Promise<SolutionListResponse> {\n return (await this.request(\"GET\", \"/solutions\", {\n query: { page: opts.page, limit: opts.limit, sort: opts.sort, order: opts.order, search: opts.search },\n })) as SolutionListResponse;\n }\n\n /**\n * Create a new solution.\n *\n * @param body - Solution configuration.\n * @returns The created solution.\n */\n async createSolution(body: CreateSolutionRequest): Promise<SolutionResponse> {\n return (await this.request(\"POST\", \"/solutions\", { json: body })) as SolutionResponse;\n }\n\n /**\n * Get a solution by ID.\n *\n * @param solutionId - Solution identifier.\n * @returns Solution details.\n */\n async getSolution(solutionId: string): Promise<SolutionResponse> {\n return (await this.request(\"GET\", `/solutions/${solutionId}`)) as SolutionResponse;\n }\n\n /**\n * Update a solution.\n *\n * @param solutionId - Solution identifier.\n * @param body - Fields to update.\n * @returns Updated solution.\n */\n async updateSolution(solutionId: string, body: UpdateSolutionRequest): Promise<SolutionResponse> {\n return (await this.request(\"PATCH\", `/solutions/${solutionId}`, { json: body })) as SolutionResponse;\n }\n\n /**\n * Delete a solution.\n *\n * @param solutionId - Solution identifier.\n */\n async deleteSolution(solutionId: string): Promise<void> {\n await this.request(\"DELETE\", `/solutions/${solutionId}`);\n }\n\n // ─── Solution Resource Linking ─────────────────────────────────────────────\n\n /**\n * Link agents to a solution.\n *\n * @param solutionId - Solution identifier.\n * @param body - Resource IDs to link.\n * @returns Updated solution.\n */\n async linkAgentsToSolution(solutionId: string, body: LinkResourcesRequest): Promise<SolutionResponse> {\n return (await this.request(\"POST\", `/solutions/${solutionId}/agents`, { json: body })) as SolutionResponse;\n }\n\n /**\n * Unlink agents from a solution.\n *\n * @param solutionId - Solution identifier.\n * @param body - Resource IDs to unlink.\n * @returns Updated solution.\n */\n async unlinkAgentsFromSolution(solutionId: string, body: UnlinkResourcesRequest): Promise<SolutionResponse> {\n return (await this.request(\"DELETE\", `/solutions/${solutionId}/agents`, { json: body })) as SolutionResponse;\n }\n\n /**\n * Link knowledge bases to a solution.\n *\n * @param solutionId - Solution identifier.\n * @param body - Resource IDs to link.\n * @returns Updated solution.\n */\n async linkKnowledgeBasesToSolution(solutionId: string, body: LinkResourcesRequest): Promise<SolutionResponse> {\n return (await this.request(\"POST\", `/solutions/${solutionId}/knowledge-bases`, { json: body })) as SolutionResponse;\n }\n\n /**\n * Unlink knowledge bases from a solution.\n *\n * @param solutionId - Solution identifier.\n * @param body - Resource IDs to unlink.\n * @returns Updated solution.\n */\n async unlinkKnowledgeBasesFromSolution(solutionId: string, body: UnlinkResourcesRequest): Promise<SolutionResponse> {\n return (await this.request(\"DELETE\", `/solutions/${solutionId}/knowledge-bases`, { json: body })) as SolutionResponse;\n }\n\n /**\n * Link source connections to a solution.\n *\n * @param solutionId - Solution identifier.\n * @param body - Resource IDs to link.\n * @returns Updated solution.\n */\n async linkSourceConnectionsToSolution(solutionId: string, body: LinkResourcesRequest): Promise<SolutionResponse> {\n return (await this.request(\"POST\", `/solutions/${solutionId}/source-connections`, { json: body })) as SolutionResponse;\n }\n\n /**\n * Unlink source connections from a solution.\n *\n * @param solutionId - Solution identifier.\n * @param body - Resource IDs to unlink.\n * @returns Updated solution.\n */\n async unlinkSourceConnectionsFromSolution(solutionId: string, body: UnlinkResourcesRequest): Promise<SolutionResponse> {\n return (await this.request(\"DELETE\", `/solutions/${solutionId}/source-connections`, { json: body })) as SolutionResponse;\n }\n\n // ─── Solution Conversations ────────────────────────────────────────────────\n\n /**\n * List conversations for a solution.\n *\n * @param solutionId - Solution identifier.\n * @returns List of conversations.\n */\n async listSolutionConversations(solutionId: string): Promise<SolutionConversationResponse[]> {\n return listItems<SolutionConversationResponse>(\n await this.request(\"GET\", `/solutions/${solutionId}/conversations`),\n );\n }\n\n /**\n * Add a conversation turn to a solution.\n *\n * @param solutionId - Solution identifier.\n * @param body - Conversation turn payload.\n * @returns Updated conversation.\n */\n async addSolutionConversationTurn(solutionId: string, body: AddConversationTurnRequest): Promise<SolutionConversationResponse> {\n return (await this.request(\"POST\", `/solutions/${solutionId}/conversations`, { json: body })) as SolutionConversationResponse;\n }\n\n /**\n * Mark a conversation turn (e.g. accepted/rejected).\n *\n * @param solutionId - Solution identifier.\n * @param conversationId - Conversation identifier.\n * @param body - Mark payload.\n */\n async markSolutionConversationTurn(solutionId: string, conversationId: string, body: MarkConversationTurnRequest): Promise<void> {\n await this.request(\"PATCH\", `/solutions/${solutionId}/conversations/${conversationId}`, { json: body });\n }\n\n // ─── Solution AI Assistant ─────────────────────────────────────────────────\n\n /**\n * Generate a solution AI plan.\n *\n * @param solutionId - Solution identifier.\n * @param body - Generation request.\n * @returns AI-generated plan.\n */\n async generateSolutionAiPlan(solutionId: string, body: AiAssistantGenerateRequest): Promise<AiAssistantGenerateResponse> {\n return (await this.request(\"POST\", `/solutions/${solutionId}/ai-assistant/generate`, { json: body })) as AiAssistantGenerateResponse;\n }\n\n /**\n * Generate a knowledge base configuration via solution AI.\n *\n * @param solutionId - Solution identifier.\n * @param body - Generation request.\n * @returns AI-generated knowledge base config.\n */\n async generateSolutionAiKnowledgeBase(solutionId: string, body: AiAssistantGenerateRequest): Promise<AiAssistantGenerateResponse> {\n return (await this.request(\"POST\", `/solutions/${solutionId}/ai-assistant/knowledge-base`, { json: body })) as AiAssistantGenerateResponse;\n }\n\n /**\n * Generate a source configuration via solution AI.\n *\n * @param solutionId - Solution identifier.\n * @param body - Generation request.\n * @returns AI-generated source config.\n */\n async generateSolutionAiSource(solutionId: string, body: AiAssistantGenerateRequest): Promise<AiAssistantGenerateResponse> {\n return (await this.request(\"POST\", `/solutions/${solutionId}/ai-assistant/source`, { json: body })) as AiAssistantGenerateResponse;\n }\n\n /**\n * Accept a solution AI plan.\n *\n * @param solutionId - Solution identifier.\n * @param conversationId - Conversation identifier.\n * @param body - Accept request.\n * @returns Acceptance result with executed actions.\n */\n async acceptSolutionAiPlan(solutionId: string, conversationId: string, body: AiAssistantAcceptRequest): Promise<AiAssistantAcceptResponse> {\n return (await this.request(\"POST\", `/solutions/${solutionId}/ai-assistant/${conversationId}/accept`, { json: body })) as AiAssistantAcceptResponse;\n }\n\n /**\n * Decline a solution AI plan.\n *\n * @param solutionId - Solution identifier.\n * @param conversationId - Conversation identifier.\n */\n async declineSolutionAiPlan(solutionId: string, conversationId: string): Promise<void> {\n await this.request(\"POST\", `/solutions/${solutionId}/ai-assistant/${conversationId}/decline`);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Governance — AI Assistant\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Generate governance policy suggestions using AI.\n *\n * @param body - AI governance request.\n * @returns AI-generated governance suggestions.\n */\n async generateGovernanceAiPlan(body: GovernanceAiAssistantRequest): Promise<GovernanceAiAssistantResponse> {\n return (await this.request(\"POST\", \"/governance/ai-assistant\", { json: body })) as GovernanceAiAssistantResponse;\n }\n\n /**\n * List governance AI conversations.\n *\n * @param opts - `limit`: how many conversations (the server defaults to 20).\n */\n async listGovernanceAiConversations(opts: { limit?: number } = {}): Promise<GovernanceConversationResponse[]> {\n return listItems<GovernanceConversationResponse>(\n await this.request(\"GET\", \"/governance/ai-assistant/conversations\", { query: { limit: opts.limit } }),\n );\n }\n\n /**\n * Accept a governance AI plan.\n *\n * @param conversationId - Conversation identifier.\n * @returns Acceptance result.\n */\n async acceptGovernanceAiPlan(conversationId: string): Promise<GovernanceAiAcceptResponse> {\n return (await this.request(\"POST\", `/governance/ai-assistant/${conversationId}/accept`)) as GovernanceAiAcceptResponse;\n }\n\n /**\n * Decline a governance AI plan.\n *\n * @param conversationId - Conversation identifier.\n */\n async declineGovernanceAiPlan(conversationId: string): Promise<void> {\n await this.request(\"POST\", `/governance/ai-assistant/${conversationId}/decline`);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Alerts\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List alerts.\n *\n * @param opts - Pagination and filter options.\n * @returns Paginated list of alerts.\n */\n async listAlerts(opts: ListAlertsOptions = {}): Promise<AlertListResponse> {\n // `severity` is deliberately not forwarded: GET /alerts declares no such\n // filter, so it never filtered anything, and sending it is a 422 once\n // `apiVersion` is 2026-07-27 or later. Accepted and dropped so existing\n // call sites keep working.\n return (await this.request(\"GET\", \"/alerts\", {\n query: {\n page: opts.page,\n limit: opts.limit,\n status: opts.status,\n agent_id: opts.agentId,\n source_connection_id: opts.sourceConnectionId,\n time_from: opts.timeFrom,\n time_to: opts.timeTo,\n },\n })) as AlertListResponse;\n }\n\n /**\n * Get alert details by ID.\n *\n * @param alertId - Alert identifier.\n * @returns Alert details.\n */\n async getAlert(alertId: string): Promise<AlertDetailResponse> {\n return (await this.request(\"GET\", `/alerts/${alertId}`)) as AlertDetailResponse;\n }\n\n /**\n * Change the status of an alert.\n *\n * @param alertId - Alert identifier.\n * @param body - Status change request.\n */\n async changeAlertStatus(alertId: string, body: ChangeStatusRequest): Promise<AlertDetailResponse> {\n return (await this.request(\"POST\", `/alerts/${alertId}/status`, { json: body })) as AlertDetailResponse;\n }\n\n /**\n * Add a comment to an alert.\n *\n * @param alertId - Alert identifier.\n * @param body - Comment payload.\n */\n async addAlertComment(alertId: string, body: AddCommentRequest): Promise<AlertDetailResponse> {\n return (await this.request(\"POST\", `/alerts/${alertId}/comments`, { json: body })) as AlertDetailResponse;\n }\n\n /**\n * Subscribe to an alert.\n *\n * @param alertId - Alert identifier.\n */\n async subscribeToAlert(alertId: string): Promise<AlertDetailResponse> {\n return (await this.request(\"POST\", `/alerts/${alertId}/subscribe`)) as AlertDetailResponse;\n }\n\n /**\n * Unsubscribe from an alert.\n *\n * @param alertId - Alert identifier.\n */\n async unsubscribeFromAlert(alertId: string): Promise<AlertDetailResponse> {\n return (await this.request(\"POST\", `/alerts/${alertId}/unsubscribe`)) as AlertDetailResponse;\n }\n\n // ─── Alert Configs ─────────────────────────────────────────────────────────\n\n /**\n * List alert configurations.\n *\n * @param opts - Pagination options.\n * @returns Paginated list of alert configs.\n */\n /**\n * `configs` and `total` are populated on every API version; `data` and\n * `pagination` are also present once `apiVersion` is 2026-07-27 or later.\n */\n async listAlertConfigs(opts: ListAlertConfigsOptions = {}): Promise<AlertConfigListResponse> {\n return keyedList<AlertConfigListResponse>(\n await this.request(\"GET\", \"/alerts/configs\", {\n query: {\n page: opts.page,\n limit: opts.limit,\n agent_id: opts.agentId,\n source_connection_id: opts.sourceConnectionId,\n scope: opts.scope,\n },\n }),\n \"configs\",\n [\"total\"],\n );\n }\n\n /**\n * Create an alert configuration.\n *\n * @param body - Alert config definition.\n * @returns Created alert config.\n */\n async createAlertConfig(body: CreateAlertConfigRequest): Promise<AlertConfigResponse> {\n return (await this.request(\"POST\", \"/alerts/configs\", { json: body })) as AlertConfigResponse;\n }\n\n /**\n * Get an alert configuration by ID.\n *\n * @param configId - Alert config identifier.\n * @returns Alert config details.\n */\n async getAlertConfig(configId: string): Promise<AlertConfigResponse> {\n return (await this.request(\"GET\", `/alerts/configs/${configId}`)) as AlertConfigResponse;\n }\n\n /**\n * Update an alert configuration.\n *\n * @param configId - Alert config identifier.\n * @param body - Fields to update.\n * @returns Updated alert config.\n */\n async updateAlertConfig(configId: string, body: UpdateAlertConfigRequest): Promise<AlertConfigResponse> {\n return (await this.request(\"PATCH\", `/alerts/configs/${configId}`, { json: body })) as AlertConfigResponse;\n }\n\n /**\n * Delete an alert configuration.\n *\n * @param configId - Alert config identifier.\n */\n async deleteAlertConfig(configId: string): Promise<void> {\n await this.request(\"DELETE\", `/alerts/configs/${configId}`);\n }\n\n // ─── Organization Alert Preferences ────────────────────────────────────────\n\n /**\n * List organization alert preferences.\n *\n * @param opts - Organization filter, and whether to include default subscriptions.\n */\n async listOrganizationAlertPreferences(\n opts: ListOrganizationAlertPreferencesOptions = {},\n ): Promise<OrganizationAlertPreferenceListResponse> {\n return keyedList<OrganizationAlertPreferenceListResponse>(\n await this.request(\"GET\", \"/alerts/organization-preferences/list\", {\n query: { organization_id: opts.organizationId, include_defaults: opts.includeDefaults },\n }),\n \"preferences\",\n [\"total\"],\n );\n }\n\n /**\n * Update an organization alert preference.\n *\n * @param organizationId - Organization identifier.\n * @param alertType - Alert type.\n * @param body - Preference update.\n */\n async updateOrganizationAlertPreference(\n organizationId: string,\n alertType: string,\n body: UpdateOrganizationAlertPreferenceRequest,\n ): Promise<OrganizationAlertPreferenceResponse> {\n return (await this.request(\n \"PATCH\",\n `/alerts/organization-preferences/${organizationId}/${alertType}`,\n { json: body },\n )) as OrganizationAlertPreferenceResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Models & Model Alerts\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List model alerts.\n *\n * @param opts - Pagination, an agent filter and `unreadOnly`.\n */\n async listModelAlerts(opts: ListModelAlertsOptions = {}): Promise<ModelAlertListResponse> {\n // The endpoint declares limit/offset, not page, so `page` was ignored and\n // every page after the first returned page 1.\n const limit = opts.limit ?? 50;\n const offset = opts.page && opts.page > 1 ? (opts.page - 1) * limit : undefined;\n return keyedList<ModelAlertListResponse>(\n await this.request(\"GET\", \"/models/alerts\", {\n query: { offset, limit: opts.limit, agent_id: opts.agentId, unread_only: opts.unreadOnly },\n }),\n \"alerts\",\n [\"total\"],\n );\n }\n\n /**\n * Mark all model alerts as read.\n */\n async markAllModelAlertsRead(): Promise<void> {\n await this.request(\"POST\", \"/models/alerts/mark-all-read\");\n }\n\n /**\n * Get unread model alert count.\n */\n async getUnreadModelAlertCount(): Promise<UnreadCountResponse> {\n return (await this.request(\"GET\", \"/models/alerts/unread-count\")) as UnreadCountResponse;\n }\n\n /**\n * Mark a specific model alert as read.\n *\n * @param alertId - Model alert identifier.\n */\n async markModelAlertRead(alertId: string): Promise<void> {\n await this.request(\"PATCH\", `/models/alerts/${alertId}/read`);\n }\n\n /**\n * Get model recommendations.\n *\n * @param modelId - Model identifier.\n * @param opts - Capabilities and limits a recommended model must have.\n */\n async getModelRecommendations(\n modelId: string,\n opts: ModelRecommendationsOptions = {},\n ): Promise<ModelRecommendationsResponse> {\n return (await this.request(\"GET\", `/models/${modelId}/recommendations`, {\n query: {\n require_tool_use: opts.requireToolUse,\n require_structured_output: opts.requireStructuredOutput,\n require_thinking: opts.requireThinking,\n min_context_tokens: opts.minContextTokens,\n min_output_tokens: opts.minOutputTokens,\n },\n })) as ModelRecommendationsResponse;\n }\n\n /**\n * List all enabled LLM models grouped by provider.\n *\n * @param opts - Optional filters.\n */\n async listModels(\n opts: {\n provider?: string;\n supportsToolUse?: boolean;\n supportsThinking?: boolean;\n supportsInputMedia?: string;\n supportsOutputMedia?: string;\n } = {},\n ): Promise<ProviderGroupResponse[]> {\n return listItems<ProviderGroupResponse>(await this.request(\"GET\", \"/models\", {\n query: {\n provider: opts.provider,\n supports_tool_use: opts.supportsToolUse,\n supports_thinking: opts.supportsThinking,\n supports_input_media: opts.supportsInputMedia,\n supports_output_media: opts.supportsOutputMedia,\n },\n }));\n }\n\n /**\n * Get full details for a specific model.\n *\n * @param modelId - Model identifier.\n */\n async getModel(modelId: string): Promise<PromptModelResponse> {\n return (await this.request(\"GET\", `/models/${modelId}/details`)) as PromptModelResponse;\n }\n\n /**\n * List the media-generation quality tiers and the model + cost each resolves to.\n *\n * On a `prompt_call`'s `media_generation` tool — and the dedicated\n * `generate_*` steps via tier routing — the author/LLM picks a *tier*\n * (fast/balanced/thorough), never a model. This maps each\n * `(modality, tier)` to its concrete generator, raw `credits_per_unit`,\n * `unit_label`, and a human-readable scaled `price_label`.\n *\n * Global routing/pricing (the same for every account); read-only.\n */\n async getGenerationTiers(): Promise<Record<string, unknown>> {\n return keyedList<Record<string, unknown>>(await this.request(\"GET\", \"/models/generation-tiers\"), \"tiers\");\n }\n\n /**\n * List the embedding models a source can index with, and their pricing.\n *\n * The endpoint lists the embedders under `models` by default and under `data`\n * once the caller opts in with `apiVersion` 2026-07-27 or later; `models` is\n * populated on either, with the defaults and pricing beside it.\n *\n * @param opts.supportsInputMedia - Keep only embedders that can index this\n * input modality — a coarse kind (text, image, video, audio) or a full MIME.\n */\n async listEmbeddingModels(opts: { supportsInputMedia?: string } = {}): Promise<EmbeddingModelListResponse> {\n return keyedList<EmbeddingModelListResponse>(\n await this.request(\"GET\", \"/models/embedders\", {\n query: { supports_input_media: opts.supportsInputMedia },\n }),\n \"models\",\n );\n }\n\n /**\n * List the reranker models a knowledge base can use, and their pricing.\n *\n * `models` is populated on either wire shape, as for {@link Seclai.listEmbeddingModels}.\n */\n async listRerankerModels(): Promise<RerankerModelListResponse> {\n return keyedList<RerankerModelListResponse>(await this.request(\"GET\", \"/models/rerankers\"), \"models\");\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Model Playground Experiments\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List model playground experiments.\n *\n * @param opts - Date range and offset paging. Only `startDate` and `endDate`\n * together replace `days`; either one alone is ignored and the last `days`\n * days apply (server default 30).\n */\n async listExperiments(opts: DateRangeOptions & OffsetPageOptions = {}): Promise<ExperimentListResponse> {\n return keyedList<ExperimentListResponse>(\n await this.request(\"GET\", \"/models/playground/experiments\", {\n query: { days: opts.days, start_date: opts.startDate, end_date: opts.endDate, limit: opts.limit, offset: opts.offset },\n }),\n \"experiments\",\n [\"total\"],\n );\n }\n\n /**\n * Create a model playground experiment.\n *\n * @param body - Experiment configuration.\n */\n async createExperiment(body: CreateExperimentInput): Promise<CreateExperimentResponse> {\n return (await this.request(\"POST\", \"/models/playground/experiments\", { json: body })) as CreateExperimentResponse;\n }\n\n /**\n * Get a model playground experiment by ID.\n *\n * @param experimentId - Experiment identifier.\n */\n async getExperiment(experimentId: string): Promise<ExperimentDetailResponse> {\n return (await this.request(\"GET\", `/models/playground/experiments/${experimentId}`)) as ExperimentDetailResponse;\n }\n\n /**\n * Cancel a running model playground experiment.\n *\n * @param experimentId - Experiment identifier.\n */\n async cancelExperiment(experimentId: string): Promise<CancelExperimentResponse> {\n return (await this.request(\"POST\", `/models/playground/experiments/${experimentId}/cancel`)) as CancelExperimentResponse;\n }\n\n /**\n * Soft-delete a model playground experiment.\n *\n * Removes the experiment from list/detail views while preserving audit\n * history. Returns HTTP 204 with no body.\n *\n * @param experimentId - Experiment identifier.\n */\n async deleteExperiment(experimentId: string): Promise<void> {\n await this.request(\"DELETE\", `/models/playground/experiments/${experimentId}`);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Cloud Drives\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List the cloud-drive providers this deployment has configured.\n *\n * @returns The providers, read from either wire shape.\n */\n async listCloudDriveProviders(): Promise<CloudDriveProviderResponse[]> {\n return listItems<CloudDriveProviderResponse>(await this.request(\"GET\", \"/cloud-drives/providers\"));\n }\n\n /**\n * List the account's cloud-drive connections.\n *\n * @returns The connections, read from either wire shape.\n */\n async listCloudDrives(): Promise<CloudDriveResponse[]> {\n return listItems<CloudDriveResponse>(await this.request(\"GET\", \"/cloud-drives\"));\n }\n\n /**\n * Get a cloud-drive connection.\n *\n * @param connectionId - Cloud-drive connection identifier.\n */\n async getCloudDrive(connectionId: string): Promise<CloudDriveResponse> {\n return (await this.request(\"GET\", `/cloud-drives/${connectionId}`)) as CloudDriveResponse;\n }\n\n /**\n * Update a cloud-drive connection.\n *\n * @param connectionId - Cloud-drive connection identifier.\n * @param body - Fields to change — `name` and/or `folder_path`.\n * @returns The updated connection.\n */\n async updateCloudDrive(connectionId: string, body: CloudDriveUpdateRequest): Promise<CloudDriveResponse> {\n return (await this.request(\"PATCH\", `/cloud-drives/${connectionId}`, { json: body })) as CloudDriveResponse;\n }\n\n /**\n * Disconnect a cloud-drive connection, keeping the connection itself.\n *\n * @param connectionId - Cloud-drive connection identifier.\n * @returns The connection in its disconnected state.\n */\n async disconnectCloudDrive(connectionId: string): Promise<CloudDriveResponse> {\n return (await this.request(\"POST\", `/cloud-drives/${connectionId}/disconnect`)) as CloudDriveResponse;\n }\n\n /**\n * Delete a cloud-drive connection.\n *\n * @param connectionId - Cloud-drive connection identifier.\n */\n async deleteCloudDrive(connectionId: string): Promise<void> {\n await this.request(\"DELETE\", `/cloud-drives/${connectionId}`);\n }\n\n /**\n * List the agents that use a cloud-drive connection.\n *\n * @param connectionId - Cloud-drive connection identifier.\n * @returns The agents, read from either wire shape.\n */\n async getAgentsUsingCloudDrive(connectionId: string): Promise<AgentUsingCloudDriveResponse[]> {\n return listItems<AgentUsingCloudDriveResponse>(\n await this.request(\"GET\", `/cloud-drives/${connectionId}/agents`),\n );\n }\n\n /**\n * List the files a cloud-drive connection skipped, newest first.\n *\n * A skipped file fires no trigger, so this is where to look when an agent\n * did not run for a file.\n *\n * @param connectionId - Cloud-drive connection identifier.\n * @param opts.limit - Maximum number of rejections (1-200, default 50).\n * @returns The rejections with their reasons, read from either wire shape.\n */\n async listCloudDriveRejections(\n connectionId: string,\n opts: { limit?: number } = {},\n ): Promise<CloudDriveRejectionResponse[]> {\n return listItems<CloudDriveRejectionResponse>(\n await this.request(\"GET\", `/cloud-drives/${connectionId}/rejections`, {\n query: { limit: opts.limit },\n }),\n );\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Search\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Search across all resource types in your account.\n *\n * Accepts a free-text keyword query or a UUID. Results are ranked:\n * name-prefix > name-substring > description-substring.\n *\n * @param opts - Search options.\n * @param opts.query - Search query string (required, 1-200 chars).\n * @param opts.limit - Maximum results (1-50, default 10).\n * @param opts.entityType - Optional entity type filter (e.g. \"agent\", \"knowledge_base\").\n * @returns Search results.\n */\n async search(opts: { query: string; limit?: number; entityType?: string }): Promise<SearchResponse> {\n return (await this.request(\"GET\", \"/search\", {\n query: { q: opts.query, limit: opts.limit, entity_type: opts.entityType },\n })) as SearchResponse;\n }\n\n /**\n * Search the Seclai documentation by content.\n *\n * `mode: \"keyword\"` matches page titles and summaries (fast, no AI cost);\n * `mode: \"semantic\"` matches page body content by meaning (uses an embedding).\n *\n * Each result carries a `doc_slug` and an optional section `anchor` for\n * building a `https://seclai.com/docs/<doc_slug>[#<anchor>]` link, a `score`\n * (not comparable across modes), and — in semantic mode — a `highlight`\n * (best matching verbatim sentence; `null` for keyword).\n *\n * Documentation is global, so results are not account-scoped.\n *\n * @param opts - Search options.\n * @param opts.query - Search query string (required, 1-200 chars).\n * @param opts.mode - Search strategy (default `\"keyword\"`).\n * @param opts.limit - Maximum results (1-20, default 8).\n */\n async searchDocs(opts: { query: string; mode?: \"keyword\" | \"semantic\"; limit?: number }): Promise<Record<string, unknown>> {\n return (await this.request(\"GET\", \"/docs-search\", {\n query: { q: opts.query, mode: opts.mode, limit: opts.limit },\n })) as Record<string, unknown>;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Email Domains\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List the account's vanity (`<slug>.seclai.com`) and custom\n * (`agent.mycompany.com`) agent-email domains.\n *\n * Includes each domain's verification status and the DNS records the customer\n * must publish, plus the plan capabilities (`can_add_vanity` /\n * `can_add_custom`) and whether one of each kind already exists\n * (`has_vanity` / `has_custom` — the per-kind limit is 1).\n *\n * Requires a user-bound credential; an account-only API key is refused with 403.\n */\n async listEmailDomains(): Promise<EmailDomainsListResponse> {\n return keyedList<EmailDomainsListResponse>(await this.request(\"GET\", \"/email-domains\"), \"domains\");\n }\n\n /**\n * Add and provision a new agent-email domain.\n *\n * Pass `kind: \"vanity\"` with `value: \"<slug>\"`, or `kind: \"custom\"` with\n * `value: \"agent.mycompany.com\"` (optionally `delegated: true` to let Seclai\n * manage a dedicated Route53 zone). Stands up the SES identity + DNS and\n * returns the records the customer must publish. Requires an account\n * owner/admin.\n *\n * @param body - The domain to add. `delegated` defaults to `false` server-side.\n */\n async addEmailDomain(body: AddEmailDomainInput): Promise<EmailDomainResponse> {\n return (await this.request(\"POST\", \"/email-domains\", { json: body })) as EmailDomainResponse;\n }\n\n /**\n * Remove a domain and tear down its SES identity + DNS / receipt-rule recipient.\n *\n * Returns a `cleanup_note` when the removed domain was Seclai-managed\n * (delegated), reminding you to delete the registrar NS delegation record\n * (dangling-delegation / subdomain-takeover guard). Requires an account\n * owner/admin.\n *\n * @param domainId - Domain identifier.\n */\n async removeEmailDomain(domainId: string): Promise<RemoveEmailDomainResponse> {\n return (await this.request(\"DELETE\", `/email-domains/${domainId}`)) as RemoveEmailDomainResponse;\n }\n\n /**\n * Run a verification check immediately (\"Check now\").\n *\n * Re-polls SES + DNS for this domain instead of waiting for the background\n * verification sweep, and returns its updated status + DNS-record check\n * results. Useful right after publishing the required records. Requires an\n * account owner/admin.\n *\n * @param domainId - Domain identifier.\n */\n async verifyEmailDomain(domainId: string): Promise<EmailDomainResponse> {\n return (await this.request(\"POST\", `/email-domains/${domainId}/verify`)) as EmailDomainResponse;\n }\n\n /**\n * Promote a verified domain to the account's primary domain.\n *\n * Agent email then sends FROM and receives ON this domain\n * (`<agentID>@<domain>`, `<alias>@<domain>`) instead of the shared\n * `agent.seclai.com`. The domain must be verified. Requires an account\n * owner/admin.\n *\n * @param domainId - Domain identifier.\n */\n async setPrimaryEmailDomain(domainId: string): Promise<EmailDomainResponse> {\n return (await this.request(\"POST\", `/email-domains/${domainId}/primary`)) as EmailDomainResponse;\n }\n\n /**\n * Revert to the shared `agent.seclai.com` sending/inbound domain.\n *\n * Clears the account's primary domain WITHOUT removing the configured\n * domain(s) — they stay verified and can be promoted again later. Requires an\n * account owner/admin.\n */\n async useSharedEmailDomain(): Promise<void> {\n await this.request(\"POST\", \"/email-domains/use-shared-domain\");\n }\n\n /**\n * Send a test message FROM a verified domain (`noreply@<domain>`) TO the\n * account owner's email.\n *\n * Confirms end-to-end that the domain actually sends (SES verified, DKIM/SPF\n * aligned). Never sends to any other address, so it can't be used as an open\n * relay. Requires an account owner/admin.\n *\n * @param domainId - Domain identifier.\n */\n async sendEmailDomainTestEmail(domainId: string): Promise<SendTestEmailResponse> {\n return (await this.request(\"POST\", `/email-domains/${domainId}/test-email`)) as SendTestEmailResponse;\n }\n\n /**\n * Get the DMARC aggregate-report summary for a domain.\n *\n * Pass rate, disposition breakdown (`none`/`quarantine`/`reject`), and top\n * failing source IPs from the DMARC `rua` reports over the last `days`\n * (clamped by the service).\n *\n * Populated for domains whose DNS zone Seclai controls (vanity + delegated\n * custom); a self-managed custom domain keeps its own DMARC reporting and\n * returns an all-zero summary.\n *\n * @param domainId - Domain identifier.\n * @param opts - Reporting window options.\n * @param opts.days - Window length in days (default 30).\n * @param opts.topSources - Number of top failing sources to return (default 10).\n */\n async getDmarcSummary(\n domainId: string,\n opts: { days?: number; topSources?: number } = {},\n ): Promise<DmarcSummaryResponse> {\n return (await this.request(\"GET\", `/email-domains/${domainId}/dmarc`, {\n query: { days: opts.days, top_sources: opts.topSources },\n })) as DmarcSummaryResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Top-Level AI Assistant\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Submit feedback on an AI assistant interaction.\n *\n * @param body - Feedback payload (thumbs up/down, optional comment).\n * @returns Feedback response.\n */\n async submitAiFeedback(body: AiAssistantFeedbackRequest): Promise<AiAssistantFeedbackResponse> {\n return (await this.request(\"POST\", \"/ai-assistant/feedback\", { json: body })) as AiAssistantFeedbackResponse;\n }\n\n /**\n * Generate a knowledge base configuration via AI assistant.\n *\n * @param body - Generation request.\n */\n async aiAssistantKnowledgeBase(body: AiAssistantGenerateRequest): Promise<AiAssistantGenerateResponse> {\n return (await this.request(\"POST\", \"/ai-assistant/knowledge-base\", { json: body })) as AiAssistantGenerateResponse;\n }\n\n /**\n * Generate a source configuration via AI assistant.\n *\n * @param body - Generation request.\n */\n async aiAssistantSource(body: AiAssistantGenerateRequest): Promise<AiAssistantGenerateResponse> {\n return (await this.request(\"POST\", \"/ai-assistant/source\", { json: body })) as AiAssistantGenerateResponse;\n }\n\n /**\n * Generate a solution via AI assistant.\n *\n * @param body - Generation request.\n */\n async aiAssistantSolution(body: AiAssistantGenerateRequest): Promise<AiAssistantGenerateResponse> {\n return (await this.request(\"POST\", \"/ai-assistant/solution\", { json: body })) as AiAssistantGenerateResponse;\n }\n\n /**\n * Generate a memory bank configuration via AI assistant.\n *\n * @param body - Generation request.\n */\n async aiAssistantMemoryBank(body: MemoryBankAiAssistantRequest): Promise<MemoryBankAiAssistantResponse> {\n return (await this.request(\"POST\", \"/ai-assistant/memory-bank\", { json: body })) as MemoryBankAiAssistantResponse;\n }\n\n /**\n * Get AI assistant memory bank conversation history.\n *\n * @param opts - Turns to return (server default 5) and most-recent turns to skip (default 0).\n */\n async getAiAssistantMemoryBankHistory(opts: OffsetPageOptions = {}): Promise<MemoryBankLastConversationResponse> {\n return (await this.request(\"GET\", \"/ai-assistant/memory-bank/last-conversation\", {\n query: { limit: opts.limit, offset: opts.offset },\n })) as MemoryBankLastConversationResponse;\n }\n\n /**\n * Accept an AI assistant suggestion.\n *\n * @param conversationId - Conversation identifier.\n * @param body - Acceptance request payload.\n */\n async acceptAiAssistantPlan(conversationId: string, body: AiAssistantAcceptRequest): Promise<AiAssistantAcceptResponse> {\n return (await this.request(\"POST\", `/ai-assistant/${conversationId}/accept`, { json: body })) as AiAssistantAcceptResponse;\n }\n\n /**\n * Decline an AI assistant suggestion.\n *\n * @param conversationId - Conversation identifier.\n */\n async declineAiAssistantPlan(conversationId: string): Promise<void> {\n await this.request(\"POST\", `/ai-assistant/${conversationId}/decline`);\n }\n\n /**\n * Accept/mark an AI memory bank suggestion.\n *\n * @param conversationId - Conversation identifier.\n * @param body - Acceptance payload for the memory bank suggestion.\n */\n async acceptAiMemoryBankSuggestion(conversationId: string, body: MemoryBankAcceptRequest): Promise<OkResponse> {\n return (await this.request(\"PATCH\", `/ai-assistant/memory-bank/${conversationId}`, { json: body })) as OkResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Pagination Helpers\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Auto-paginate through a list endpoint.\n *\n * Yields individual items from each page, fetching the next page until the\n * response reports there is none. A fetcher that answers with a bare array has\n * no further pages, so its items are yielded once.\n *\n * @param fetchPage - A function that fetches a single page given `{ page, limit }`.\n * @param opts - Page size (default: 50).\n * @throws {@link SeclaiError} When a page carries its items under neither `data` nor `items`.\n *\n * @example\n * ```ts\n * for await (const agent of client.paginate(\n * (opts) => client.listAgents(opts),\n * )) {\n * console.log(agent.name);\n * }\n * ```\n */\n async *paginate<T>(\n fetchPage: (opts: { page: number; limit: number }) => Promise<PaginatedPage<T>>,\n opts?: { limit?: number },\n ): AsyncGenerator<T, void, undefined> {\n const limit = opts?.limit ?? 50;\n let page = 1;\n\n while (true) {\n const result = (await fetchPage({ page, limit })) as unknown;\n if (Array.isArray(result)) {\n yield* result as T[];\n return;\n }\n const body = (result ?? {}) as {\n data?: T[] | null;\n items?: T[] | null;\n pagination?: { pages?: number; total_pages?: number; has_next?: boolean } | null;\n total?: number;\n limit?: number;\n };\n const items = \"data\" in body ? body.data ?? [] : body.items;\n if (!Array.isArray(items)) {\n throw new SeclaiError(\n \"paginate() could not find the page's items: expected an array, or an object with a `data` or `items` array.\",\n );\n }\n yield* items;\n\n const pagination = body.pagination;\n if (items.length === 0) return;\n if (!pagination) {\n // The flat `{data, total, page, limit}` shape. Counted from the page\n // requested, so a server that ignores `page` cannot loop this forever.\n if (typeof body.total !== \"number\") return;\n const pageSize = typeof body.limit === \"number\" && body.limit > 0 ? body.limit : limit;\n if (page * pageSize >= body.total) return;\n } else if (typeof pagination.has_next === \"boolean\") {\n if (!pagination.has_next) return;\n } else {\n const pages = pagination.pages ?? pagination.total_pages;\n if (items.length < limit || pages === undefined || page >= pages) return;\n }\n page++;\n }\n }\n}\n"],"mappings":";AAUO,IAAM,mBAAmB;AAAA,EAC9B,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAA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AA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA0BA,OAAO,SACL,WACA,MACoC;AACpC,UAAM,QAAQ,MAAM,SAAS;AAC7B,QAAI,OAAO;AAEX,WAAO,MAAM;AACX,YAAM,SAAU,MAAM,UAAU,EAAE,MAAM,MAAM,CAAC;AAC/C,UAAI,MAAM,QAAQ,MAAM,GAAG;AACzB,eAAO;AACP;AAAA,MACF;AACA,YAAM,OAAQ,UAAU,CAAC;AAOzB,YAAM,QAAQ,UAAU,OAAO,KAAK,QAAQ,CAAC,IAAI,KAAK;AACtD,UAAI,CAAC,MAAM,QAAQ,KAAK,GAAG;AACzB,cAAM,IAAI;AAAA,UACR;AAAA,QACF;AAAA,MACF;AACA,aAAO;AAEP,YAAM,aAAa,KAAK;AACxB,UAAI,MAAM,WAAW,EAAG;AACxB,UAAI,CAAC,YAAY;AAGf,YAAI,OAAO,KAAK,UAAU,SAAU;AACpC,cAAM,WAAW,OAAO,KAAK,UAAU,YAAY,KAAK,QAAQ,IAAI,KAAK,QAAQ;AACjF,YAAI,OAAO,YAAY,KAAK,MAAO;AAAA,MACrC,WAAW,OAAO,WAAW,aAAa,WAAW;AACnD,YAAI,CAAC,WAAW,SAAU;AAAA,MAC5B,OAAO;AACL,cAAM,QAAQ,WAAW,SAAS,WAAW;AAC7C,YAAI,MAAM,SAAS,SAAS,UAAU,UAAa,QAAQ,MAAO;AAAA,MACpE;AACA;AAAA,IACF;AAAA,EACF;AACF;","names":["getEnv","run","state"]}
1
+ {"version":3,"sources":["../src/versions.ts","../src/errors.ts","../src/auth.ts","../src/client.ts"],"sourcesContent":["/**\n * Dated API versions known to this release, for use with the `apiVersion`\n * client option.\n *\n * The set is open: the API adds versions without an SDK release, and\n * {@link ApiVersion} widens to `string`, so a date newer than this release\n * knows about can be passed directly. Treat these as convenience constants\n * rather than an exhaustive list — `getApiVersion()` reports what the server\n * actually supports.\n */\nexport const SeclaiApiVersion = {\n V2026_07_01: \"2026-07-01\",\n V2026_07_27: \"2026-07-27\",\n V2026_08_03: \"2026-08-03\",\n V2026_08_21: \"2026-08-21\",\n V2026_09_28: \"2026-09-28\",\n V2026_09_30: \"2026-09-30\",\n V2026_10_03: \"2026-10-03\",\n V2026_10_05: \"2026-10-05\",\n V2026_10_13: \"2026-10-13\",\n V2026_10_16: \"2026-10-16\",\n V2026_10_18: \"2026-10-18\",\n V2026_10_19: \"2026-10-19\",\n V2026_10_21: \"2026-10-21\",\n V2026_10_28: \"2026-10-28\",\n V2026_11_02: \"2026-11-02\",\n V2026_11_04: \"2026-11-04\",\n V2026_11_08: \"2026-11-08\",\n V2026_11_09: \"2026-11-09\",\n V2026_11_14: \"2026-11-14\",\n V2026_11_19: \"2026-11-19\",\n /** Baseline applied to an unpinned, header-less caller. */\n Default: \"2026-07-01\",\n /** Newest version known to this SDK release. May lag the server. */\n Latest: \"2026-11-19\",\n} as const;\n\n/**\n * A dated API version. Known values autocomplete; any `YYYY-MM-DD` string still\n * typechecks, but one this release was not built against is rejected at\n * construction unless `allowUnknownApiVersion` is set.\n */\nexport type ApiVersion =\n | (typeof SeclaiApiVersion)[keyof typeof SeclaiApiVersion]\n // eslint-disable-next-line @typescript-eslint/ban-types\n | (string & {});\n\n/** Every version this release was built against, oldest first. */\nexport const KNOWN_API_VERSIONS: readonly string[] = Object.entries(SeclaiApiVersion)\n .filter(([k]) => k.startsWith(\"V\"))\n .map(([, v]) => v);\n","/**\n * @module\n *\n * Error classes thrown by the Seclai SDK.\n *\n * All errors extend {@link SeclaiError}, so a single `catch (err instanceof SeclaiError)`\n * handles every SDK error. Narrow to more specific subclasses for finer handling.\n */\n\nimport type { AgentRunResponse } from \"./types\";\n\n/** Base error class for the Seclai SDK. */\nexport class SeclaiError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SeclaiError\";\n }\n}\n\n/** Thrown when the SDK is misconfigured (for example, missing API key). */\nexport class SeclaiConfigurationError extends SeclaiError {\n constructor(message: string) {\n super(message);\n this.name = \"SeclaiConfigurationError\";\n }\n}\n\n/**\n * Thrown when the API returns a non-success status code.\n *\n * @remarks\n * Use {@link SeclaiAPIValidationError} for HTTP 422 validation errors.\n */\nexport class SeclaiAPIStatusError extends SeclaiError {\n /** HTTP status code returned by the API. */\n public readonly statusCode: number;\n /** HTTP method used for the request. */\n public readonly method: string;\n /** Full request URL. */\n public readonly url: string;\n /** Best-effort response body text (if available). */\n public readonly responseText: string | undefined;\n /**\n * Headers of the error response, such as `Retry-After` on a 503, or\n * `Content-Range` on a 416 from a ranged `downloadAgentRunAttachment()`, whose\n * value ends in `/<size>`, the file's size in bytes. Empty when the response\n * headers are unknown. In a browser, only the headers the server's CORS policy\n * exposes are present.\n */\n public readonly headers: Headers;\n\n constructor(opts: {\n /** Human-readable error message. */\n message: string;\n statusCode: number;\n method: string;\n url: string;\n responseText: string | undefined;\n /** Response headers; defaults to an empty `Headers`. */\n headers?: Headers;\n }) {\n super(opts.message);\n this.name = \"SeclaiAPIStatusError\";\n this.statusCode = opts.statusCode;\n this.method = opts.method;\n this.url = opts.url;\n this.responseText = opts.responseText;\n this.headers = opts.headers ?? new Headers();\n }\n}\n\n/**\n * Thrown when the API returns a validation error response (typically HTTP 422).\n *\n * The `validationError` field contains the decoded validation payload when available.\n */\nexport class SeclaiAPIValidationError extends SeclaiAPIStatusError {\n /** Parsed validation error payload (best-effort). */\n public readonly validationError: unknown;\n\n constructor(opts: {\n message: string;\n statusCode: number;\n method: string;\n url: string;\n responseText: string | undefined;\n headers?: Headers;\n validationError: unknown;\n }) {\n super(opts);\n this.name = \"SeclaiAPIValidationError\";\n this.validationError = opts.validationError;\n }\n}\n\n/**\n * Thrown when a streaming operation fails (e.g. stream ends unexpectedly), or\n * when a run helper stops waiting before the run finished.\n */\nexport class SeclaiStreamingError extends SeclaiError {\n /** The run ID associated with the failed stream, when available. */\n public readonly runId: string | undefined;\n /**\n * Set by `runStreamingAgentAndWait()` and `runAgentAndPoll()` to the latest\n * run they had, if any (when it has `result_reported_at` set, its `output`\n * is the answer). The run may still be in progress, and can still fail.\n */\n public readonly run: AgentRunResponse | undefined;\n\n constructor(message: string, runId?: string, run?: AgentRunResponse) {\n super(message);\n this.name = \"SeclaiStreamingError\";\n this.runId = runId;\n this.run = run;\n }\n}\n","/**\n * @module\n *\n * SSO credential resolution: config file parsing, token caching, and automatic\n * token refresh against AWS Cognito.\n *\n * @internal — not part of the public API surface. Consumed by {@link Seclai}.\n */\nimport type { FetchLike } from \"./client\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Resolved SSO profile settings. */\nexport interface SsoProfile {\n ssoAccountId?: string | undefined;\n ssoRegion: string;\n ssoClientId: string;\n ssoDomain: string;\n}\n\n/** Contents of a single SSO cache file. */\nexport interface SsoCacheEntry {\n accessToken: string;\n refreshToken?: string;\n idToken?: string | undefined;\n expiresAt: string; // ISO-8601\n clientId: string;\n region: string;\n cognitoDomain: string;\n}\n\n// ─── Constants ───────────────────────────────────────────────────────────────\n\nconst DEFAULT_CONFIG_DIR = \".seclai\";\nconst SSO_CACHE_DIR = \"sso/cache\";\nconst CONFIG_FILE = \"config\";\nconst EXPIRY_BUFFER_MS = 30_000; // 30 seconds\nconst DEFAULT_API_KEY_HEADER = \"x-api-key\";\n\n/** Default SSO domain (production Cognito). Override with `SECLAI_SSO_DOMAIN` or config file. */\nexport const DEFAULT_SSO_DOMAIN = \"auth.seclai.com\";\n/** Default SSO client ID (production public client). Override with `SECLAI_SSO_CLIENT_ID` or config file. */\nexport const DEFAULT_SSO_CLIENT_ID = \"4bgf8v9qmc5puivbaqon9n5lmr\";\n/** Default SSO region. Override with `SECLAI_SSO_REGION` or config file. */\nexport const DEFAULT_SSO_REGION = \"us-west-2\";\n\n// ─── Environment helpers ─────────────────────────────────────────────────────\n\nfunction getEnv(name: string): string | undefined {\n const p = (globalThis as any)?.process;\n return p?.env?.[name];\n}\n\nfunction getHomeDir(): string | undefined {\n const p = (globalThis as any)?.process;\n return p?.env?.HOME ?? p?.env?.USERPROFILE;\n}\n\n// ─── SHA-1 hash ──────────────────────────────────────────────────────────────\n\nasync function sha1Hex(input: string): Promise<string> {\n // Prefer Node.js crypto when available\n try {\n // @ts-expect-error -- resolved at runtime; no @types/node in this package\n const { createHash } = await import(\"node:crypto\");\n return createHash(\"sha1\").update(input).digest(\"hex\");\n } catch {\n // Fall back to Web Crypto API\n const encoded = new TextEncoder().encode(input);\n const buffer = await crypto.subtle.digest(\"SHA-1\", encoded);\n return Array.from(new Uint8Array(buffer))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n }\n}\n\n/**\n * Compute the cache filename for a given domain + clientId.\n *\n * @param domain - The Cognito domain (e.g. `\"auth.example.com\"`).\n * @param clientId - The Cognito app client ID.\n * @returns SHA-1 hex digest of `\"domain|clientId\"`.\n */\nexport async function cacheFileName(domain: string, clientId: string): Promise<string> {\n return sha1Hex(`${domain}|${clientId}`);\n}\n\n// ─── INI parser ──────────────────────────────────────────────────────────────\n\n/**\n * Minimal INI parser matching AWS config format:\n * - `[default]` section\n * - `[profile <name>]` sections\n * - `key = value` pairs\n * - Lines starting with `#` or `;` are comments\n *\n * @param content - Raw INI file content.\n * @returns Map of section names to key-value pairs.\n */\nexport function parseIni(content: string): Record<string, Record<string, string>> {\n const sections: Record<string, Record<string, string>> = {};\n let currentSection: string | null = null;\n\n for (const rawLine of content.split(/\\r?\\n/)) {\n const line = rawLine.trim();\n\n if (!line || line.startsWith(\"#\") || line.startsWith(\";\")) continue;\n\n const sectionMatch = line.match(/^\\[(.+)\\]$/);\n if (sectionMatch) {\n const raw = sectionMatch[1]!.trim();\n // `[default]` stays as \"default\", `[profile foo]` becomes \"foo\"\n currentSection = raw.startsWith(\"profile \")\n ? raw.slice(\"profile \".length).trim()\n : raw;\n sections[currentSection] ??= {};\n continue;\n }\n\n if (currentSection !== null) {\n const eqIdx = line.indexOf(\"=\");\n if (eqIdx > 0) {\n const key = line.slice(0, eqIdx).trim();\n const value = line.slice(eqIdx + 1).trim();\n sections[currentSection]![key] = value;\n }\n }\n }\n\n return sections;\n}\n\n// ─── File system (Node.js only) ──────────────────────────────────────────────\n\ninterface FsModule {\n readFileSync(path: string, encoding: string): string;\n writeFileSync(path: string, data: string, options?: { mode?: number }): void;\n mkdirSync(path: string, options?: { recursive?: boolean; mode?: number }): void;\n existsSync(path: string): boolean;\n unlinkSync(path: string): void;\n renameSync(oldPath: string, newPath: string): void;\n}\n\ninterface PathModule {\n join(...parts: string[]): string;\n}\n\nlet _fs: FsModule | null = null;\nlet _path: PathModule | null = null;\n\nasync function getFs(): Promise<FsModule> {\n if (!_fs) {\n // @ts-expect-error -- resolved at runtime; no @types/node in this package\n _fs = (await import(\"node:fs\")) as unknown as FsModule;\n }\n return _fs;\n}\n\nasync function getPath(): Promise<PathModule> {\n if (!_path) {\n // @ts-expect-error -- resolved at runtime; no @types/node in this package\n _path = (await import(\"node:path\")) as unknown as PathModule;\n }\n return _path;\n}\n\n// ─── Config dir resolution ───────────────────────────────────────────────────\n\n/**\n * Resolve the config directory path.\n *\n * @param override - Explicit directory path (highest priority).\n * @returns Resolved absolute path to the config directory.\n * @throws {Error} If the home directory cannot be determined and no override is provided.\n */\nexport async function resolveConfigDir(override?: string): Promise<string> {\n if (override) return override;\n\n const envDir = getEnv(\"SECLAI_CONFIG_DIR\");\n if (envDir) return envDir;\n\n const home = getHomeDir();\n if (!home) {\n throw new Error(\"Cannot determine home directory. Set SECLAI_CONFIG_DIR.\");\n }\n\n const pathMod = await getPath();\n return pathMod.join(home, DEFAULT_CONFIG_DIR);\n}\n\n// ─── Profile resolution ─────────────────────────────────────────────────────\n\n/**\n * Load and resolve an SSO profile from the config file.\n * Non-default profiles inherit unset keys from `[default]`.\n * All profiles fall back to built-in defaults and environment variable overrides.\n *\n * **Node.js only** — this function uses `node:fs` and `node:path` internally\n * and will throw in browser/edge-worker runtimes.\n *\n * @param configDir - Resolved config directory path.\n * @param profileName - Profile name to look up (`\"default\"` or a named profile).\n * @returns The resolved profile. Always returns a valid profile using built-in defaults.\n */\nexport async function loadSsoProfile(\n configDir: string,\n profileName: string,\n): Promise<SsoProfile> {\n const fs = await getFs();\n const pathMod = await getPath();\n\n let merged: Record<string, string> = {};\n\n const configPath = pathMod.join(configDir, CONFIG_FILE);\n if (fs.existsSync(configPath)) {\n const content = fs.readFileSync(configPath, \"utf-8\");\n const sections = parseIni(content);\n\n const defaultSection = sections[\"default\"] ?? {};\n const profileSection = profileName === \"default\" ? defaultSection : sections[profileName];\n\n if (profileSection) {\n merged = profileName === \"default\" ? profileSection : { ...defaultSection, ...profileSection };\n }\n }\n\n // Environment variables override config file values\n const ssoDomain = getEnv(\"SECLAI_SSO_DOMAIN\") ?? merged[\"sso_domain\"] ?? DEFAULT_SSO_DOMAIN;\n const ssoClientId = getEnv(\"SECLAI_SSO_CLIENT_ID\") ?? merged[\"sso_client_id\"] ?? DEFAULT_SSO_CLIENT_ID;\n const ssoRegion = getEnv(\"SECLAI_SSO_REGION\") ?? merged[\"sso_region\"] ?? DEFAULT_SSO_REGION;\n const ssoAccountId = merged[\"sso_account_id\"] || undefined;\n\n return { ssoAccountId, ssoRegion, ssoClientId, ssoDomain };\n}\n\n// ─── Cache I/O ───────────────────────────────────────────────────────────────\n\n/**\n * Read a cached SSO token from disk.\n *\n * @param configDir - Resolved config directory path.\n * @param profile - SSO profile (used to derive the cache filename).\n * @returns The cached entry, or `null` if not found or unreadable.\n */\n/** Resolve the full path to a profile's SSO cache file. */\nasync function resolveCachePath(\n configDir: string,\n profile: SsoProfile,\n): Promise<string> {\n const pathMod = await getPath();\n const hash = await cacheFileName(profile.ssoDomain, profile.ssoClientId);\n return pathMod.join(configDir, SSO_CACHE_DIR, `${hash}.json`);\n}\n\nexport async function readSsoCache(\n configDir: string,\n profile: SsoProfile,\n): Promise<SsoCacheEntry | null> {\n const fs = await getFs();\n\n const cachePath = await resolveCachePath(configDir, profile);\n\n if (!fs.existsSync(cachePath)) return null;\n\n try {\n const raw = fs.readFileSync(cachePath, \"utf-8\");\n return JSON.parse(raw) as SsoCacheEntry;\n } catch {\n return null;\n }\n}\n\n/**\n * Write a cached SSO token to disk atomically.\n * Creates the cache directory if it doesn't exist.\n *\n * @param configDir - Resolved config directory path.\n * @param profile - SSO profile (used to derive the cache filename).\n * @param entry - Token data to persist.\n */\nexport async function writeSsoCache(\n configDir: string,\n profile: SsoProfile,\n entry: SsoCacheEntry,\n): Promise<void> {\n const fs = await getFs();\n const pathMod = await getPath();\n\n const cacheDir = pathMod.join(configDir, SSO_CACHE_DIR);\n fs.mkdirSync(cacheDir, { recursive: true, mode: 0o700 });\n\n const cachePath = await resolveCachePath(configDir, profile);\n const tmpPath = `${cachePath}.tmp`;\n\n fs.writeFileSync(tmpPath, JSON.stringify(entry, null, 2), { mode: 0o600 });\n // On Windows, renameSync fails if destination exists — delete first (best-effort)\n if (fs.existsSync(cachePath)) {\n try { fs.unlinkSync(cachePath); } catch { /* let renameSync throw if needed */ }\n }\n fs.renameSync(tmpPath, cachePath);\n}\n\n/**\n * Delete a cached SSO token file.\n *\n * @param configDir - Resolved config directory path.\n * @param profile - SSO profile (used to derive the cache filename).\n */\nexport async function deleteSsoCache(\n configDir: string,\n profile: SsoProfile,\n): Promise<void> {\n const fs = await getFs();\n\n const cachePath = await resolveCachePath(configDir, profile);\n\n if (fs.existsSync(cachePath)) {\n fs.unlinkSync(cachePath);\n }\n}\n\n// ─── Token validation ────────────────────────────────────────────────────────\n\n/**\n * Check if a cached token is still valid (with 30s buffer).\n *\n * @param entry - The cached token entry to check.\n * @returns `true` if the token expires more than 30 seconds in the future.\n */\nexport function isTokenValid(entry: SsoCacheEntry): boolean {\n const expiresAt = new Date(entry.expiresAt).getTime();\n return Date.now() + EXPIRY_BUFFER_MS < expiresAt;\n}\n\n// ─── Token refresh ───────────────────────────────────────────────────────────\n\n/**\n * Refresh an access token using a Cognito refresh_token grant.\n *\n * @param profile - SSO profile with Cognito domain and client ID.\n * @param refreshTokenValue - The refresh token to exchange.\n * @param fetcher - A `fetch`-compatible function for making HTTP requests.\n * @returns A fresh {@link SsoCacheEntry} with the new tokens.\n * @throws {Error} If the Cognito token endpoint returns a non-OK status.\n */\nexport async function refreshToken(\n profile: SsoProfile,\n refreshTokenValue: string,\n fetcher: FetchLike,\n): Promise<SsoCacheEntry> {\n const tokenUrl = `https://${profile.ssoDomain}/oauth2/token`;\n\n const body = new URLSearchParams({\n grant_type: \"refresh_token\",\n client_id: profile.ssoClientId,\n refresh_token: refreshTokenValue,\n });\n\n const response = await fetcher(tokenUrl, {\n method: \"POST\",\n headers: { \"content-type\": \"application/x-www-form-urlencoded\" },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n throw new Error(`Token refresh failed (HTTP ${response.status}): ${text}`);\n }\n\n const data = (await response.json()) as {\n access_token: string;\n id_token?: string;\n refresh_token?: string;\n expires_in: number;\n };\n\n const expiresAt = new Date(Date.now() + data.expires_in * 1000).toISOString();\n\n return {\n accessToken: data.access_token,\n refreshToken: data.refresh_token ?? refreshTokenValue,\n idToken: data.id_token ?? undefined,\n expiresAt,\n clientId: profile.ssoClientId,\n region: profile.ssoRegion,\n cognitoDomain: profile.ssoDomain,\n };\n}\n\n// ─── Credential chain resolver ───────────────────────────────────────────────\n\n/** Options for resolving the credential chain. */\nexport interface CredentialChainOptions {\n /** Explicit API key (highest priority). */\n apiKey?: string | undefined;\n /** Explicit static bearer token. */\n accessToken?: string | undefined;\n /** Dynamic bearer token provider. */\n accessTokenProvider?: (() => string | Promise<string>) | undefined;\n /** Name of the profile from ~/.seclai/config. */\n profile?: string | undefined;\n /** Override config directory path. */\n configDir?: string | undefined;\n /** Whether to auto-refresh expired SSO tokens. Defaults to true. */\n autoRefresh?: boolean | undefined;\n /** Account ID override (takes precedence over profile's sso_account_id). */\n accountId?: string | undefined;\n /** Header name for API key auth. */\n apiKeyHeader?: string | undefined;\n /** fetch implementation for token refresh. */\n fetch?: FetchLike | undefined;\n}\n\n/**\n * Resolved authentication state used throughout the client lifecycle.\n * Created once by {@link resolveCredentialChain} and passed to\n * {@link resolveAuthHeaders} on every request.\n */\nexport interface AuthState {\n mode: \"apiKey\" | \"bearerStatic\" | \"bearerProvider\" | \"sso\";\n apiKey?: string;\n apiKeyHeader: string;\n accessToken?: string;\n accessTokenProvider?: () => string | Promise<string>;\n accountId?: string | undefined;\n ssoProfile?: SsoProfile;\n configDir?: string;\n autoRefresh: boolean;\n fetcher?: FetchLike | undefined;\n /** @internal Coalesces concurrent SSO token refresh attempts. */\n _refreshPromise?: Promise<string> | undefined;\n}\n\n/**\n * Resolve the credential chain and return an AuthState.\n * This is called once at client construction time.\n *\n * Resolution order:\n * 1. Explicit `apiKey` option\n * 2. Explicit `accessToken` option\n * 3. Explicit `accessTokenProvider` option\n * 4. `SECLAI_API_KEY` environment variable\n * 5. SSO profile from `~/.seclai/config`\n *\n * @param opts - Credential chain options.\n * @returns Resolved authentication state.\n * @throws {Error} If no credentials are found.\n */\nexport async function resolveCredentialChain(\n opts: CredentialChainOptions,\n): Promise<AuthState> {\n const apiKeyHeader = opts.apiKeyHeader ?? DEFAULT_API_KEY_HEADER;\n\n // 1. Explicit apiKey option\n if (opts.apiKey) {\n return {\n mode: \"apiKey\",\n apiKey: opts.apiKey,\n apiKeyHeader,\n accountId: opts.accountId,\n autoRefresh: false,\n };\n }\n\n // 2. Explicit accessToken (mutual exclusion already checked by caller)\n if (opts.accessToken) {\n return {\n mode: \"bearerStatic\",\n accessToken: opts.accessToken,\n apiKeyHeader,\n accountId: opts.accountId,\n autoRefresh: false,\n };\n }\n\n // 3. Explicit accessTokenProvider\n if (opts.accessTokenProvider) {\n return {\n mode: \"bearerProvider\",\n accessTokenProvider: opts.accessTokenProvider,\n apiKeyHeader,\n accountId: opts.accountId,\n autoRefresh: false,\n };\n }\n\n // 4. SECLAI_API_KEY env var\n const envApiKey = getEnv(\"SECLAI_API_KEY\");\n if (envApiKey) {\n return {\n mode: \"apiKey\",\n apiKey: envApiKey,\n apiKeyHeader,\n accountId: opts.accountId,\n autoRefresh: false,\n };\n }\n\n // 5. Profile-based SSO resolution\n try {\n const configDir = await resolveConfigDir(opts.configDir);\n const profileName = opts.profile ?? getEnv(\"SECLAI_PROFILE\") ?? \"default\";\n const ssoProfile = await loadSsoProfile(configDir, profileName);\n\n return {\n mode: \"sso\",\n apiKeyHeader,\n accountId: opts.accountId ?? ssoProfile.ssoAccountId,\n ssoProfile,\n configDir,\n autoRefresh: opts.autoRefresh !== false,\n fetcher: opts.fetch,\n };\n } catch {\n // Config dir not found — fall through\n }\n\n // 6. Nothing found\n throw new Error(\n \"Missing credentials. Provide apiKey, accessToken, set SECLAI_API_KEY, or run `seclai auth login`.\",\n );\n}\n\n/**\n * Resolve authentication headers from the current AuthState.\n * Called per-request to handle dynamic token providers and SSO cache refresh.\n *\n * @param state - The resolved authentication state.\n * @returns Headers object with the appropriate auth header(s) set.\n */\nexport async function resolveAuthHeaders(\n state: AuthState,\n): Promise<Record<string, string>> {\n const headers: Record<string, string> = {};\n\n switch (state.mode) {\n case \"apiKey\":\n headers[state.apiKeyHeader] = state.apiKey!;\n break;\n\n case \"bearerStatic\":\n headers[\"authorization\"] = `Bearer ${state.accessToken!}`;\n break;\n\n case \"bearerProvider\": {\n const token = await Promise.resolve(state.accessTokenProvider!());\n headers[\"authorization\"] = `Bearer ${token}`;\n break;\n }\n\n case \"sso\": {\n const token = await resolveSsoToken(state);\n headers[\"authorization\"] = `Bearer ${token}`;\n break;\n }\n }\n\n if (state.accountId) {\n headers[\"x-account-id\"] = state.accountId;\n }\n\n return headers;\n}\n\n/** Resolve a valid SSO token, refreshing from cache if needed. */\nasync function resolveSsoToken(state: AuthState): Promise<string> {\n const profile = state.ssoProfile!;\n const configDir = state.configDir!;\n\n const cached = await readSsoCache(configDir, profile);\n\n if (cached && isTokenValid(cached)) {\n return cached.accessToken;\n }\n\n if (cached?.refreshToken && state.autoRefresh) {\n // Coalesce concurrent refresh attempts\n if (state._refreshPromise) {\n return state._refreshPromise;\n }\n\n const fetcher = state.fetcher ?? (globalThis.fetch as FetchLike | undefined);\n if (!fetcher) {\n throw new Error(\"No fetch implementation available for token refresh.\");\n }\n\n state._refreshPromise = (async () => {\n try {\n const refreshed = await refreshToken(profile, cached.refreshToken!, fetcher);\n await writeSsoCache(configDir, profile, refreshed);\n return refreshed.accessToken;\n } finally {\n state._refreshPromise = undefined;\n }\n })();\n return state._refreshPromise;\n }\n\n throw new Error(\n `SSO token expired. Run \\`seclai auth login\\` to re-authenticate.`,\n );\n}\n","/**\n * @module\n *\n * Main SDK client for the Seclai API.\n *\n * Exports the {@link Seclai} class which provides typed convenience methods for\n * every API endpoint, plus low-level {@link Seclai.request | request()} and\n * {@link Seclai.requestRaw | requestRaw()} escape hatches, streaming helpers,\n * and automatic pagination.\n */\nimport {\n SeclaiAPIStatusError,\n SeclaiAPIValidationError,\n SeclaiConfigurationError,\n SeclaiError,\n SeclaiStreamingError,\n} from \"./errors\";\nimport type { ApiVersion } from \"./versions\";\nimport { KNOWN_API_VERSIONS } from \"./versions\";\nimport type { AuthState } from \"./auth\";\nimport { resolveCredentialChain, resolveAuthHeaders } from \"./auth\";\nimport type {\n AgentRunEvent,\n AddEmailDomainInput,\n AgentAttachmentRefsApiResponse,\n AcceptedAttachmentsResponse,\n SetAcceptedAttachmentsInput,\n ContentAttachmentsListResponse,\n ContentAttachmentDetailResponse,\n EmailSourceRejectionListResponse,\n AgentCallerApiResponse,\n AgentDefinitionImportErrorResponse,\n AgentDefinitionResponse,\n AgentEmailOptOutListResponse,\n AgentExportResponse,\n AgentImportPreviewRequest,\n AgentImportPreviewResponse,\n AgentListResponse,\n AgentRunListResponse,\n AgentRunRequest,\n AgentRunResponse,\n AgentRunStreamRequest,\n AgentSummaryResponse,\n AgentUsingCloudDriveResponse,\n CloudDriveProviderResponse,\n CloudDriveRejectionResponse,\n CloudDriveResponse,\n CloudDriveUpdateRequest,\n EmbeddingModelListResponse,\n ListSourceContentsOptions,\n RerankerModelListResponse,\n GenerationTierListResponse,\n SourceContentStatusListResponse,\n SourceContentStatusResponse,\n AgentTraceSearchRequest,\n AgentTraceSearchResponse,\n AiAssistantAcceptRequest,\n AiAssistantAcceptResponse,\n AiAssistantFeedbackRequest,\n AiAssistantFeedbackResponse,\n AiAssistantGenerateRequest,\n AiAssistantGenerateResponse,\n AiConversationHistoryResponse,\n AddCommentRequest,\n AddConversationTurnRequest,\n BlockEmailSenderRequest,\n BlockedEmailSenderListResponse,\n BlockedEmailSenderResponse,\n CancelQueuedRunsResponse,\n ChangeStatusRequest,\n CompatibleRunListResponse,\n CompactionTestResponse,\n ContentDetailResponse,\n ContentEmbeddingsListResponse,\n ContentFileUploadResponse,\n CreateAgentRequest,\n CreateAlertConfigRequest,\n CreateEvaluationCriteriaRequest,\n CreateEvaluationResultRequest,\n CreateExportRequest,\n CreateKnowledgeBaseBody,\n CreateMemoryBankBody,\n CreateSolutionRequest,\n CreateSourceBody,\n DmarcSummaryResponse,\n EmailDomainResponse,\n EmailDomainsListResponse,\n EmailTriggerConfigResponse,\n EstimateExportRequest,\n EstimateExportResponse,\n EvaluationCriteriaResponse,\n EvaluationCriteriaListResponse,\n ApiVersionResponse,\n AlertDetailResponse,\n AlertCommentResponse,\n AlertSubscriberResponse,\n UnreadCountResponse,\n ModelRecommendationsResponse,\n ModelRecommendationResponse,\n ExperimentListResponse,\n ExperimentSummaryResponse,\n ExperimentDetailResponse,\n CreateExperimentResponse,\n CancelExperimentResponse,\n SearchResponse,\n SearchResultResponse,\n OkResponse,\n AlertResponse,\n AlertConfigResponse,\n ModelAlertResponse,\n AlertListResponse,\n AlertConfigListResponse,\n ModelAlertListResponse,\n EvaluationResultListResponse,\n EvaluationResultResponse,\n EvaluationResultSummaryResponse,\n EvaluationResultWithCriteriaListResponse,\n EvaluationRunSummaryListResponse,\n ExportListResponse,\n ExportResponse,\n FileUploadResponse,\n GenerateAgentStepsRequest,\n GenerateAgentStepsResponse,\n GenerateStepConfigRequest,\n GenerateStepConfigResponse,\n GovernanceAiAcceptResponse,\n GovernanceAiAssistantRequest,\n GovernanceAiAssistantResponse,\n GovernanceConversationResponse,\n InboundEmailRejectionResponse,\n InboundEmailStatusResponse,\n InlineTextReplaceRequest,\n InlineTextUploadRequest,\n KnowledgeBaseListResponse,\n KnowledgeBaseResponse,\n LinkResourcesRequest,\n ListOptions,\n MarkAiSuggestionRequest,\n MarkConversationTurnRequest,\n MemoryBankAcceptRequest,\n MemoryBankAiAssistantRequest,\n MemoryBankAiAssistantResponse,\n MemoryBankLastConversationResponse,\n MeResponse,\n MemoryBankListResponse,\n MemoryBankResponse,\n NonManualEvaluationSummaryResponse,\n OrganizationAlertPreferenceListResponse,\n OrganizationAlertPreferenceResponse,\n PlaygroundCreateRequest,\n CreateExperimentInput,\n PromptModelResponse,\n ProviderGroupResponse,\n RemoveEmailDomainResponse,\n ResumeInboundResponse,\n SendTestEmailResponse,\n SetAutoBlockModeRequest,\n SetEmailTriggerConfigRequest,\n SolutionConversationResponse,\n SolutionListResponse,\n SolutionResponse,\n SortableListOptions,\n SourceEmbeddingMigrationResponse,\n SourceListResponse,\n SourceResponse,\n StandaloneTestCompactionRequest,\n StartSourceEmbeddingMigrationRequest,\n TestCompactionRequest,\n TestDraftEvaluationRequest,\n TestDraftEvaluationResponse,\n UnlinkResourcesRequest,\n UpdateAgentDefinitionRequest,\n UpdateAgentRequest,\n UpdateAlertConfigRequest,\n UpdateEvaluationCriteriaRequest,\n UpdateKnowledgeBaseBody,\n UpdateMemoryBankBody,\n UpdateOrganizationAlertPreferenceRequest,\n UpdateSolutionRequest,\n UpdateSourceBody,\n UploadAgentInputApiResponse,\n AgentExampleListResponse,\n ListAgentExamplesOptions,\n SetSlackTriggerConfigRequest,\n SlackTriggerConfigResponse,\n SetMetadataKeysRequest,\n MetadataKeysResponse,\n KnowledgeBaseMetadataKeyStatsResponse,\n ListSolutionsOptions,\n ListMemoryBanksOptions,\n ListEvaluationResultsOptions,\n ListAgentEvaluationResultsOptions,\n ListEvaluationRunsOptions,\n ListCompatibleRunsOptions,\n DateRangeOptions,\n OffsetPageOptions,\n ListAlertsOptions,\n ListAlertConfigsOptions,\n ListOrganizationAlertPreferencesOptions,\n ListModelAlertsOptions,\n ModelRecommendationsOptions,\n} from \"./types\";\n\n/** Default API base URL (can be overridden with `baseUrl` or `SECLAI_API_URL`). */\nexport const SECLAI_API_URL = \"https://api.seclai.com\";\n\n/** A `fetch`-compatible function (e.g. `globalThis.fetch` or `undici.fetch`). */\nexport type FetchLike = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\n/**\n * Token provider: a synchronous or asynchronous function that returns an\n * access token string. Called on every request to allow automatic refresh.\n */\nexport type AccessTokenProvider = () => string | Promise<string>;\n\n/** Configuration for the {@link Seclai} client. */\nexport interface SeclaiOptions {\n /** API key used for authentication. Defaults to `process.env.SECLAI_API_KEY` when available. */\n apiKey?: string;\n /**\n * Static bearer access token **or** a provider function that returns one.\n * Mutually exclusive with `apiKey`.\n */\n accessToken?: string | AccessTokenProvider;\n /** API base URL. Defaults to `process.env.SECLAI_API_URL` when available, else {@link SECLAI_API_URL}. */\n baseUrl?: string;\n /** Header name to use for the API key. Defaults to `x-api-key`. */\n apiKeyHeader?: string;\n /** Extra headers to include on every request. */\n defaultHeaders?: Record<string, string>;\n /** Optional `fetch` implementation for environments without a global `fetch`. */\n fetch?: FetchLike;\n /**\n * SSO profile name to load from `~/.seclai/config`.\n * Defaults to `process.env.SECLAI_PROFILE`, then `\"default\"`.\n */\n profile?: string;\n /**\n * Override the config directory path (default: `SECLAI_CONFIG_DIR` env var or `~/.seclai/`).\n */\n configDir?: string;\n /**\n * Whether to auto-refresh expired SSO tokens. Defaults to `true`.\n * Set to `false` in environments that should not write to disk.\n */\n autoRefresh?: boolean;\n /**\n * Target organization account ID. Sent as `X-Account-Id` header.\n * Overrides the profile's `sso_account_id` when using SSO auth.\n */\n accountId?: string;\n /**\n * Dated API version (`YYYY-MM-DD`) sent as the `Seclai-Version` header, opting\n * this client into backward-incompatible API changes released on or before\n * that date.\n *\n * Left unset the header is omitted and the account's pinned baseline applies,\n * so responses keep their current shapes and upgrading the SDK alone never\n * changes the wire contract. Pin the account instead with\n * {@link Seclai.updateApiVersion}, and read what a request resolves to with\n * {@link Seclai.getApiVersion}.\n *\n * From `2026-07-27` the API rejects undeclared query parameters with a 422\n * rather than ignoring them, and list endpoints return the canonical\n * `{data, pagination}` envelope.\n */\n apiVersion?: ApiVersion;\n /**\n * Permit an {@link apiVersion} this release was not built against.\n *\n * Off by default. A newer API version can change response shapes, and this\n * client would decode them incorrectly rather than reject them — a\n * request-side mistake answers 422, but a reshaped response just mis-decodes,\n * silently. Prefer upgrading the package.\n */\n allowUnknownApiVersion?: boolean;\n}\n\n// ─── Internal Helpers ────────────────────────────────────────────────────────\n\nfunction getEnv(name: string): string | undefined {\n const p = (globalThis as any)?.process;\n return p?.env?.[name];\n}\n\nfunction buildURL(baseUrl: string, path: string, query?: Record<string, unknown>): URL {\n // Ensure baseUrl ends with \"/\" so new URL() preserves its path component.\n const base = baseUrl.endsWith(\"/\") ? baseUrl : `${baseUrl}/`;\n // Strip leading \"/\" from path so it's treated as relative to base.\n const relative = path.startsWith(\"/\") ? path.slice(1) : path;\n const url = new URL(relative, base);\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) continue;\n if (Array.isArray(value)) {\n // A repeatable parameter: one `key=value` pair per element.\n for (const item of value) url.searchParams.append(key, String(item));\n continue;\n }\n url.searchParams.set(key, String(value));\n }\n }\n return url;\n}\n\n/**\n * One page as a fetcher handed to {@link Seclai.paginate} may return it: a list\n * method's `{data, pagination}` envelope or flat `{data, total, page, limit}`,\n * a bare array, or `{items, pagination}` with a `total_pages` count.\n */\nexport type PaginatedPage<T> =\n | T[]\n | {\n data?: T[] | null;\n pagination?: { pages?: number; has_next?: boolean } | null;\n total?: number;\n limit?: number;\n }\n | { items: T[]; pagination?: { page: number; total_pages: number } };\n\n/**\n * The items of a version-gated list whose method is declared as an array: a\n * bare array by default, under `data` from 2026-07-27.\n */\nfunction listItems<T>(res: unknown): T[] {\n if (Array.isArray(res)) return res as T[];\n if (res !== null && typeof res === \"object\" && \"data\" in res) {\n const data = (res as { data: unknown }).data;\n if (Array.isArray(data)) return data as T[];\n if (data === null) return [];\n }\n throw notAList();\n}\n\n/** An empty list would read as \"no results\" for a body that is not a list at all. */\nfunction notAList(): SeclaiError {\n return new SeclaiError(\n \"Expected a list response: an array, or an object carrying the items under `data` or the endpoint's own key.\",\n );\n}\n\n/**\n * A version-gated list as its declared object type. The items are under `key`\n * by default (or the body is a bare array) and under `data` from 2026-07-27,\n * where `flat` counters arrive inside `pagination`; both are restored to where\n * the type declares them, and `data`/`pagination` stay when the API sent them.\n */\nfunction keyedList<T extends object>(\n res: unknown,\n key: keyof T & string,\n flat: readonly (\"total\" | \"page\" | \"limit\")[] = [],\n): T {\n if (Array.isArray(res)) return { [key]: res } as T;\n if (res === null || typeof res !== \"object\") throw notAList();\n const body: Record<string, unknown> = { ...(res as Record<string, unknown>) };\n if (Array.isArray(body.data)) body[key] = body.data;\n else if (\"data\" in body && body.data === null) body[key] = [];\n else if (!Array.isArray(body[key])) throw notAList();\n const pagination = body.pagination as Record<string, unknown> | null | undefined;\n for (const field of flat) {\n if (body[field] === undefined && pagination?.[field] !== undefined) body[field] = pagination[field];\n }\n return body as T;\n}\n\n/** The flat counters of a list type that declares `total`, `page` and `limit`. */\nconst PAGE_COUNTERS = [\"total\", \"page\", \"limit\"] as const;\n\n/**\n * Merge header layers into one value per header. A later layer wins, and names\n * compare case-insensitively, so an override replaces instead of adding a\n * second spelling for `fetch` to join.\n */\nfunction mergeHeaders(...layers: (Record<string, string> | undefined)[]): Record<string, string> {\n const byName = new Map<string, [string, string]>();\n for (const layer of layers) {\n for (const [name, value] of Object.entries(layer ?? {})) {\n // A nullish value from untyped JavaScript means \"not set\", not a header.\n if (value === undefined || value === null) continue;\n const lower = name.toLowerCase();\n byName.delete(lower);\n byName.set(lower, [name, value]);\n }\n }\n return Object.fromEntries(byName.values());\n}\n\n/** The spelling under which `headers` carries `name` — the last one, which is the one a merge keeps. */\nfunction headerKey(headers: Record<string, string> | undefined, name: string): string | undefined {\n return Object.keys(headers ?? {})\n .filter((key) => key.toLowerCase() === name)\n .pop();\n}\n\n/**\n * The `Range` header value for one byte range, or `undefined` when none of the\n * three is set. Throws {@link SeclaiConfigurationError} for any combination\n * other than start, start and end, or suffix alone, so no request is sent.\n */\nfunction byteRangeHeader(\n start: number | undefined,\n end: number | undefined,\n suffix: number | undefined,\n): string | undefined {\n // A nullish value from untyped JavaScript means \"not set\", as for headers.\n const hasStart = start !== undefined && start !== null;\n const hasEnd = end !== undefined && end !== null;\n const hasSuffix = suffix !== undefined && suffix !== null;\n if (!hasStart && !hasEnd && !hasSuffix) return undefined;\n const fail = (why: string): never => {\n throw new SeclaiConfigurationError(`Invalid byte range: ${why}`);\n };\n if (hasSuffix) {\n if (hasStart || hasEnd) fail(\"rangeSuffix cannot be combined with rangeStart or rangeEnd.\");\n if (!Number.isSafeInteger(suffix) || (suffix as number) < 1) {\n fail(`rangeSuffix must be a whole number of at least 1, got ${String(suffix)}.`);\n }\n return `bytes=-${suffix}`;\n }\n if (!hasStart) fail(\"rangeEnd requires rangeStart; use rangeSuffix for the last bytes of the file.\");\n if (!Number.isSafeInteger(start) || (start as number) < 0) {\n fail(`rangeStart must be a whole number of at least 0, got ${String(start)}.`);\n }\n if (!hasEnd) return `bytes=${start}-`;\n if (!Number.isSafeInteger(end) || (end as number) < 0) {\n fail(`rangeEnd must be a whole number of at least 0, got ${String(end)}.`);\n }\n if ((end as number) < (start as number)) {\n fail(`rangeEnd (${end}) must not be less than rangeStart (${start}).`);\n }\n return `bytes=${start}-${end}`;\n}\n\nasync function safeText(response: Response): Promise<string | undefined> {\n try {\n return await response.clone().text();\n } catch {\n return undefined;\n }\n}\n\nasync function safeJson(response: Response): Promise<unknown | undefined> {\n try {\n return await response.clone().json();\n } catch {\n return undefined;\n }\n}\n\ntype SseMessage = { event?: string; data?: string };\n\nfunction createSseParser(onMessage: (msg: SseMessage) => void) {\n let buffer = \"\";\n let eventName: string | undefined;\n let dataLines: string[] = [];\n\n function dispatch() {\n if (!eventName && dataLines.length === 0) return;\n const msg: SseMessage = { data: dataLines.join(\"\\n\") };\n if (eventName !== undefined) msg.event = eventName;\n onMessage(msg);\n eventName = undefined;\n dataLines = [];\n }\n\n function processLine(rawLine: string) {\n let line = rawLine;\n if (line.endsWith(\"\\r\")) line = line.slice(0, -1);\n\n if (line === \"\") {\n dispatch();\n return;\n }\n\n if (line.startsWith(\":\")) return;\n\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n let value = colon === -1 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) value = value.slice(1);\n\n if (field === \"event\") {\n eventName = value;\n } else if (field === \"data\") {\n dataLines.push(value);\n }\n }\n\n function feed(textChunk: string) {\n buffer += textChunk;\n while (true) {\n const newlineIdx = buffer.indexOf(\"\\n\");\n if (newlineIdx === -1) return;\n const line = buffer.slice(0, newlineIdx);\n buffer = buffer.slice(newlineIdx + 1);\n processLine(line);\n }\n }\n\n /**\n * The stream closed: parse a final line that has no trailing newline, then\n * dispatch the event its lines make up.\n */\n function end() {\n if (buffer !== \"\") {\n const line = buffer;\n buffer = \"\";\n processLine(line);\n }\n dispatch();\n }\n\n /**\n * The stream broke: dispatch the event whose complete lines were read. Text\n * after the last newline may be cut mid-line, so it is not parsed.\n */\n function abandon() {\n buffer = \"\";\n dispatch();\n }\n\n return { feed, end, abandon };\n}\n\n/**\n * A signal that aborts when any of `signals` does, and a `cleanup` that removes\n * the listeners it added, so a caller's long-lived signal does not collect one\n * per call.\n */\nfunction anySignal(signals: Array<AbortSignal | undefined>): { signal: AbortSignal | undefined; cleanup: () => void } {\n const present = signals.filter(Boolean) as AbortSignal[];\n if (present.length === 0) return { signal: undefined, cleanup: () => {} };\n if (present.length === 1) return { signal: present[0], cleanup: () => {} };\n const controller = new AbortController();\n // Each listener closes over its signal: a polyfill may dispatch an event with no target.\n const listening: Array<[AbortSignal, () => void]> = [];\n const cleanup = () => {\n for (const [s, onAbort] of listening) s.removeEventListener(\"abort\", onAbort);\n listening.length = 0;\n };\n for (const s of present) {\n if (s.aborted) {\n cleanup();\n controller.abort(s.reason);\n break;\n }\n const onAbort = () => controller.abort(s.reason);\n s.addEventListener(\"abort\", onAbort, { once: true });\n listening.push([s, onAbort]);\n }\n return { signal: controller.signal, cleanup };\n}\n\n/**\n * What an aborted `signal` throws: its `reason`, or an `AbortError` for a\n * signal that carries none (a polyfill or an older runtime).\n */\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason !== undefined ? signal.reason : new DOMException(\"This operation was aborted\", \"AbortError\");\n}\n\n/** `signal.throwIfAborted()`, for signals that lack it too. */\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw abortReason(signal);\n}\n\n/** The longest delay `setTimeout` takes; a longer one fires at once. */\nconst MAX_TIMER_MS = 2_147_483_647;\n\n/** Wait `ms`, or reject with `signal.reason` once `signal` aborts. Leaves no listener behind. */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortReason(signal));\n return;\n }\n // setTimeout fires at once for a delay over MAX_TIMER_MS, so wait in steps\n // of at most that until the whole delay has passed (Infinity: until aborted).\n let remaining = Math.max(ms, 0);\n let timer: ReturnType<typeof setTimeout> | undefined;\n const onAbort = () => {\n clearTimeout(timer);\n reject(abortReason(signal!));\n };\n const arm = () => {\n const step = Math.min(remaining, MAX_TIMER_MS);\n remaining -= step;\n timer = setTimeout(() => {\n if (remaining > 0) return arm();\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, step);\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n arm();\n });\n}\n\nfunction isTerminalStatus(status: unknown): boolean {\n return status === \"completed\" || status === \"failed\" || status === \"cancelled\";\n}\n\nfunction isRunSnapshot(data: unknown): data is AgentRunResponse {\n return data !== null && typeof data === \"object\" && !Array.isArray(data);\n}\n\n/** The message of the timeout {@link Seclai.runStreamingAgent} and {@link Seclai.runStreamingAgentAndWait} throw. */\nfunction streamTimeoutMessage(timeoutMs: number): string {\n return `Timed out after ${timeoutMs}ms waiting for streaming agent run to complete.`;\n}\n\n/**\n * The error a wait helper throws when it gives up on a run that has not\n * finished: `reason`, then whether `run` carries a reported answer.\n */\nfunction incompleteRunError(reason: string, run: AgentRunResponse | undefined, runId?: string): SeclaiStreamingError {\n const state = run?.result_reported_at ? \"A result had been reported; see `run`.\" : \"No result had been reported.\";\n return new SeclaiStreamingError(`${reason} ${state}`, runId ?? run?.run_id, run);\n}\n\n/**\n * Set `cause` on `error` the way `new Error(message, { cause })` does: an own\n * property that is not enumerable, so loggers and `JSON.stringify` skip it.\n */\nfunction withCause<E extends Error>(error: E, cause: unknown): E {\n Object.defineProperty(error, \"cause\", { value: cause, enumerable: false, writable: true, configurable: true });\n return error;\n}\n\n/** Timeout errors thrown by the stream iterator, so the wait helper can attach its snapshot. */\nconst streamTimeouts = new WeakSet<object>();\n\n/** What the stream iterator reports to the wait helper built on it. */\ntype StreamProgress = {\n /** The server answered with plain JSON; the single `done` event carries it. */\n jsonReply: boolean;\n /** The SSE body is being read, so a failure from here on is a broken stream. */\n reading: boolean;\n /** `timeoutMs` elapsed, though the body may have ended without an error. */\n timedOut: boolean;\n};\n\nfunction toBlob(\n file: Blob | Uint8Array | ArrayBuffer | BufferSource,\n mimeType?: string,\n): Blob {\n if (file instanceof Blob) return file;\n const opts = mimeType ? { type: mimeType } : undefined;\n if (file instanceof ArrayBuffer) return new Blob([new Uint8Array(file)], opts);\n return new Blob([file as unknown as BlobPart], opts);\n}\n\nconst MIME_TYPES: Record<string, string> = {\n txt: \"text/plain\", html: \"text/html\", htm: \"text/html\", md: \"text/markdown\",\n csv: \"text/csv\", xml: \"text/xml\", json: \"application/json\",\n pdf: \"application/pdf\", doc: \"application/msword\",\n docx: \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n ppt: \"application/vnd.ms-powerpoint\",\n pptx: \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n xls: \"application/vnd.ms-excel\",\n xlsx: \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n msg: \"application/vnd.ms-outlook\", zip: \"application/zip\",\n epub: \"application/epub+zip\",\n png: \"image/png\", jpg: \"image/jpeg\", jpeg: \"image/jpeg\", gif: \"image/gif\",\n bmp: \"image/bmp\", tiff: \"image/tiff\", webp: \"image/webp\",\n mp3: \"audio/mpeg\", wav: \"audio/wav\", m4a: \"audio/mp4\", flac: \"audio/flac\",\n ogg: \"audio/ogg\", mp4: \"video/mp4\", mov: \"video/quicktime\", avi: \"video/x-msvideo\",\n};\n\nfunction inferMimeType(fileName: string | undefined): string | undefined {\n if (!fileName) return undefined;\n const ext = fileName.split(\".\").pop()?.toLowerCase();\n return ext ? MIME_TYPES[ext] : undefined;\n}\n\n// ─── Client ──────────────────────────────────────────────────────────────────\n\n/**\n * Seclai JavaScript/TypeScript client.\n *\n * Provides typed methods for every Seclai API endpoint, plus higher-level\n * abstractions for streaming, polling, and pagination.\n *\n * @example\n * ```ts\n * import { Seclai } from \"@seclai/sdk\";\n *\n * const client = new Seclai({ apiKey: \"sk-...\" });\n *\n * // List agents\n * const { data: agents } = await client.listAgents();\n *\n * // Run an agent\n * const run = await client.runAgent(\"agent-id\", { input: \"Hello!\" });\n *\n * // Stream an agent run\n * for await (const event of client.runStreamingAgent(\"agent-id\", { input: \"Hello!\" })) {\n * console.log(event.event, event.data);\n * }\n * ```\n */\nexport class Seclai {\n private readonly baseUrl: string;\n private readonly defaultHeaders: Record<string, string>;\n private readonly allowUnknownApiVersion: boolean;\n private readonly fetcher: FetchLike;\n private _authState: AuthState | null = null;\n private _authInitPromise: Promise<void> | null = null;\n private _authInitError: SeclaiConfigurationError | null = null;\n\n /**\n * Create a new Seclai client.\n *\n * Credentials are resolved via a chain (first match wins):\n * 1. Explicit `apiKey` option\n * 2. Explicit `accessToken` option (static string or provider function)\n * 3. `SECLAI_API_KEY` environment variable\n * 4. SSO profile from `~/.seclai/config` + cached tokens in `~/.seclai/sso/cache/`\n *\n * @param opts - Client configuration.\n * @throws {@link SeclaiConfigurationError} If no `fetch` implementation is available.\n * @throws {@link SeclaiConfigurationError} If both `apiKey` and `accessToken` are provided.\n */\n constructor(opts: SeclaiOptions = {}) {\n // Validate mutual exclusion\n if (opts.apiKey && opts.accessToken) {\n throw new SeclaiConfigurationError(\n \"Provide either apiKey or accessToken, not both.\"\n );\n }\n\n const fetcher = opts.fetch ?? (globalThis.fetch as FetchLike | undefined);\n if (!fetcher) {\n throw new SeclaiConfigurationError(\n \"No fetch implementation available. Provide opts.fetch or run in an environment with global fetch.\"\n );\n }\n\n this.baseUrl = opts.baseUrl ?? getEnv(\"SECLAI_API_URL\") ?? SECLAI_API_URL;\n\n // `defaultHeaders` is applied last so an explicit header wins, which means\n // it can carry its own Seclai-Version; the guard reads the merged result,\n // the value the client will send.\n this.allowUnknownApiVersion = opts.allowUnknownApiVersion ?? false;\n const merged = mergeHeaders(\n opts.apiVersion ? { \"Seclai-Version\": opts.apiVersion } : undefined,\n opts.defaultHeaders,\n );\n const defaultKey = headerKey(opts.defaultHeaders, \"seclai-version\");\n this.assertKnownApiVersion(merged, defaultKey ? `defaultHeaders['${defaultKey}']` : \"apiVersion\");\n this.defaultHeaders = merged;\n this.fetcher = fetcher;\n\n // Resolve credential chain (may be async for SSO profile loading)\n const accessTokenProvider =\n typeof opts.accessToken === \"function\" ? opts.accessToken : undefined;\n const accessTokenStatic =\n typeof opts.accessToken === \"string\" ? opts.accessToken : undefined;\n\n this._authInitPromise = resolveCredentialChain({\n apiKey: opts.apiKey,\n accessToken: accessTokenStatic,\n accessTokenProvider,\n profile: opts.profile,\n configDir: opts.configDir,\n autoRefresh: opts.autoRefresh,\n accountId: opts.accountId,\n apiKeyHeader: opts.apiKeyHeader,\n fetch: fetcher,\n }).then((state) => {\n this._authState = state;\n }).catch((err) => {\n this._authInitError = new SeclaiConfigurationError(\n err instanceof Error ? err.message : String(err)\n );\n });\n }\n\n /** Ensure the credential chain has been resolved. */\n private async ensureAuth(): Promise<AuthState> {\n if (this._authInitPromise) {\n await this._authInitPromise;\n this._authInitPromise = null;\n }\n if (this._authInitError) {\n throw this._authInitError;\n }\n if (!this._authState) {\n throw new SeclaiConfigurationError(\n \"Missing credentials. Provide apiKey, accessToken, set SECLAI_API_KEY, or run `seclai auth login`.\"\n );\n }\n return this._authState;\n }\n\n /** Throw unless the `Seclai-Version` in `headers` is one this release was built against. */\n private assertKnownApiVersion(headers: Record<string, string>, via: string): void {\n const key = headerKey(headers, \"seclai-version\");\n if (key === undefined || this.allowUnknownApiVersion) return;\n const version = headers[key] ?? \"\";\n if (KNOWN_API_VERSIONS.includes(version)) return;\n throw new SeclaiConfigurationError(\n `Unknown API version '${version}' (via ${via}). This release was ` +\n `built against ${KNOWN_API_VERSIONS.join(\", \")}. A newer API version can ` +\n `change response shapes, which this client would decode incorrectly rather ` +\n `than reject. Upgrade the package, or set allowUnknownApiVersion to ` +\n `proceed anyway.`,\n );\n }\n\n /**\n * The headers one request sends: `layers` merged in order, later winning,\n * with the resulting `Seclai-Version` checked against the known versions.\n */\n private requestHeaders(\n layers: (Record<string, string> | undefined)[],\n perRequest?: Record<string, string>,\n ): Record<string, string> {\n const headers = mergeHeaders(...layers);\n const requestKey = headerKey(perRequest, \"seclai-version\");\n this.assertKnownApiVersion(headers, requestKey ? `headers['${requestKey}']` : \"defaultHeaders\");\n return headers;\n }\n\n /** Resolve auth headers for the current request. */\n private async authHeaders(): Promise<Record<string, string>> {\n const state = await this.ensureAuth();\n return resolveAuthHeaders(state);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Low-level request\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Make a raw HTTP request to the Seclai API.\n *\n * This is a low-level escape hatch. For most operations, prefer the typed convenience methods.\n *\n * @param method - HTTP method (e.g. `\"GET\"`, `\"POST\"`).\n * @param path - Request path relative to `baseUrl` (e.g. `\"/sources/\"`).\n * @param opts - Query params, JSON body, per-request headers, and optional AbortSignal.\n * @returns Parsed JSON for JSON responses, raw text for non-JSON responses, or `null` for empty bodies.\n * @throws {@link SeclaiAPIValidationError} For validation errors (typically HTTP 422).\n * @throws {@link SeclaiAPIStatusError} For other non-success HTTP status codes.\n */\n async request(\n method: string,\n path: string,\n opts?: {\n query?: Record<string, unknown>;\n json?: unknown;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n }\n ): Promise<unknown | string | null> {\n const url = buildURL(this.baseUrl, path, opts?.query);\n\n const authHeaders = await this.authHeaders();\n let body: BodyInit | undefined;\n if (opts?.json !== undefined) body = JSON.stringify(opts.json);\n // A caller's content type, default or per-request, replaces the JSON one.\n const headers = this.requestHeaders(\n [\n body === undefined ? undefined : { \"content-type\": \"application/json\" },\n this.defaultHeaders,\n opts?.headers,\n authHeaders,\n ],\n opts?.headers,\n );\n\n const init: RequestInit = { method, headers };\n if (body !== undefined) {\n init.body = body;\n }\n if (opts?.signal) {\n init.signal = opts.signal;\n }\n const response = await this.fetcher(url, init);\n\n if (response.status === 204) return null;\n\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n const isJson = contentType.includes(\"application/json\");\n\n if (!response.ok) {\n const responseText = await safeText(response);\n if (response.status === 422) {\n const validation = await safeJson(response);\n throw new SeclaiAPIValidationError({\n message: \"Validation error\",\n statusCode: response.status,\n method,\n url: url.toString(),\n responseText,\n headers: new Headers(response.headers),\n validationError: validation,\n });\n }\n throw new SeclaiAPIStatusError({\n message: `Request failed with status ${response.status}`,\n statusCode: response.status,\n method,\n url: url.toString(),\n responseText,\n headers: new Headers(response.headers),\n });\n }\n\n if (!response.body) return null;\n\n if (isJson) {\n return (await response.json()) as unknown;\n }\n return await response.text();\n }\n\n /**\n * Make a raw HTTP request and return the raw `Response` object (for binary downloads, etc.).\n *\n * @param method - HTTP method.\n * @param path - Request path relative to `baseUrl`.\n * @param opts - Query params, JSON body, per-request headers, and optional AbortSignal.\n * @returns The raw `Response` object.\n * @throws {SeclaiAPIValidationError} On HTTP 422 responses.\n * @throws {SeclaiAPIStatusError} On other non-2xx responses.\n */\n async requestRaw(\n method: string,\n path: string,\n opts?: {\n query?: Record<string, unknown>;\n json?: unknown;\n headers?: Record<string, string>;\n signal?: AbortSignal | undefined;\n }\n ): Promise<Response> {\n const url = buildURL(this.baseUrl, path, opts?.query);\n\n const authHeaders = await this.authHeaders();\n let body: BodyInit | undefined;\n if (opts?.json !== undefined) body = JSON.stringify(opts.json);\n // A caller's content type, default or per-request, replaces the JSON one.\n const headers = this.requestHeaders(\n [\n body === undefined ? undefined : { \"content-type\": \"application/json\" },\n this.defaultHeaders,\n opts?.headers,\n authHeaders,\n ],\n opts?.headers,\n );\n\n const init: RequestInit = { method, headers };\n if (body !== undefined) init.body = body;\n if (opts?.signal) init.signal = opts.signal;\n\n const response = await this.fetcher(url, init);\n\n if (!response.ok) {\n const responseText = await safeText(response);\n if (response.status === 422) {\n const validation = await safeJson(response);\n throw new SeclaiAPIValidationError({\n message: \"Validation error\",\n statusCode: response.status,\n method,\n url: url.toString(),\n responseText,\n headers: new Headers(response.headers),\n validationError: validation,\n });\n }\n throw new SeclaiAPIStatusError({\n message: `Request failed with status ${response.status}`,\n statusCode: response.status,\n method,\n url: url.toString(),\n responseText,\n headers: new Headers(response.headers),\n });\n }\n\n return response;\n }\n\n /** Shared multipart upload helper. */\n private async uploadFile(\n path: string,\n opts: {\n file: Blob | Uint8Array | ArrayBuffer | BufferSource;\n title?: string;\n metadata?: Record<string, unknown>;\n fileName?: string;\n mimeType?: string;\n signal?: AbortSignal;\n },\n ): Promise<unknown> {\n const url = buildURL(this.baseUrl, path);\n\n const authHeaders = await this.authHeaders();\n const headers = this.requestHeaders([this.defaultHeaders, authHeaders]);\n // Let fetch set the multipart Content-Type with its boundary.\n const contentType = headerKey(headers, \"content-type\");\n if (contentType !== undefined) delete headers[contentType];\n\n const form = new FormData();\n const mimeType = opts.mimeType ?? inferMimeType(opts.fileName);\n const blob = toBlob(opts.file, mimeType);\n form.set(\"file\", blob, opts.fileName ?? \"upload\");\n\n if (opts.title !== undefined) form.set(\"title\", opts.title);\n if (opts.metadata !== undefined) form.set(\"metadata\", JSON.stringify(opts.metadata));\n\n const init: RequestInit = { method: \"POST\", headers, body: form };\n if (opts.signal) init.signal = opts.signal;\n\n const response = await this.fetcher(url, init);\n\n if (!response.ok) {\n const responseText = await safeText(response);\n if (response.status === 422) {\n const validation = await safeJson(response);\n throw new SeclaiAPIValidationError({\n message: \"Validation error\",\n statusCode: response.status,\n method: \"POST\",\n url: url.toString(),\n responseText,\n headers: new Headers(response.headers),\n validationError: validation,\n });\n }\n throw new SeclaiAPIStatusError({\n message: `Request failed with status ${response.status}`,\n statusCode: response.status,\n method: \"POST\",\n url: url.toString(),\n responseText,\n headers: new Headers(response.headers),\n });\n }\n\n return await response.json();\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Identity\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Get the authenticated user's identity.\n *\n * Returns the personal `account_id` plus every organization the user belongs\n * to — each with its own `id`, display `name`, and `account_id`. Use it to\n * discover the account IDs that can be passed as the client's `accountId`\n * option (sent as the `X-Account-Id` header) to target an org context.\n *\n * @returns The current user's account ID and organization memberships.\n */\n async getMe(): Promise<MeResponse> {\n return (await this.request(\"GET\", \"/me\")) as MeResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // API Version\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Read the API version this request resolved to, and the versions available.\n *\n * Resolution order is the `Seclai-Version` header, then the account pin, then\n * the default — so `effective_version` reflects the client's `apiVersion`\n * option when that is set.\n *\n * @returns The pinned, effective, default and latest versions.\n */\n async getApiVersion(): Promise<ApiVersionResponse> {\n return (await this.request(\"GET\", \"/version\")) as ApiVersionResponse;\n }\n\n /**\n * Pin the account to a dated API version, or clear the pin.\n *\n * Owner/admin only. The pin applies to later header-less requests; a\n * `Seclai-Version` header still overrides it, so `effective_version` in the\n * response describes this request rather than the pin just written.\n *\n * @param version - A `YYYY-MM-DD` date to pin to, or `null` to clear the pin.\n * @returns The updated version state.\n */\n async updateApiVersion(version: string | null): Promise<ApiVersionResponse> {\n return (await this.request(\"PUT\", \"/version\", { json: { version } })) as ApiVersionResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agents — CRUD\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List agents.\n *\n * @param opts - Pagination options.\n * @returns Paginated list of agents.\n */\n async listAgents(opts: ListOptions = {}): Promise<AgentListResponse> {\n return (await this.request(\"GET\", \"/agents\", {\n query: { page: opts.page, limit: opts.limit },\n })) as AgentListResponse;\n }\n\n /**\n * List the agent gallery: example agents to start from.\n *\n * From `apiVersion` `2026-11-09`, `query` describes what the agent should do\n * and entries come back ranked by how well they match it, best first. Before\n * it, only entries containing every word of `query` are returned.\n *\n * Pass an entry's `key` as `agent_template` to {@link createAgent}, with\n * `resource_bindings` for the resources it needs.\n *\n * @param opts - Text search, use-case filter and pagination.\n * @returns A page of gallery entries.\n */\n async listAgentExamples(opts: ListAgentExamplesOptions = {}): Promise<AgentExampleListResponse> {\n return (await this.request(\"GET\", \"/agents/examples\", {\n query: { query: opts.query, use_case: opts.useCase, page: opts.page, limit: opts.limit },\n })) as AgentExampleListResponse;\n }\n\n /**\n * Create a new agent.\n *\n * @param body - Agent creation payload (name, trigger type, template, etc.).\n * @returns Summary of the created agent.\n */\n async createAgent(body: CreateAgentRequest): Promise<AgentSummaryResponse> {\n return (await this.request(\"POST\", \"/agents\", { json: body })) as AgentSummaryResponse;\n }\n\n /**\n * Get agent details including its definition.\n *\n * @param agentId - Agent identifier.\n * @returns Full agent metadata.\n */\n async getAgent(agentId: string): Promise<AgentSummaryResponse> {\n return (await this.request(\"GET\", `/agents/${agentId}`)) as AgentSummaryResponse;\n }\n\n /**\n * Update an agent.\n *\n * @param agentId - Agent identifier.\n * @param body - Fields to update.\n * @returns Updated agent summary.\n */\n async updateAgent(agentId: string, body: UpdateAgentRequest): Promise<AgentSummaryResponse> {\n return (await this.request(\"PUT\", `/agents/${agentId}`, { json: body })) as AgentSummaryResponse;\n }\n\n /**\n * Delete an agent.\n *\n * @param agentId - Agent identifier.\n */\n async deleteAgent(agentId: string): Promise<void> {\n await this.request(\"DELETE\", `/agents/${agentId}`);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agents — Enable / Disable\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Pause (disable) an agent so it stops firing from every trigger path.\n *\n * API runs return HTTP 409, inbound email is turned away, and scheduled /\n * content triggers are skipped.\n *\n * Fails with HTTP 409 when other live agents still call this one via a\n * `call_agent` step — use {@link getAgentCallers} to list them, and disable\n * those first.\n *\n * @param agentId - Agent identifier.\n * @returns The updated agent summary.\n */\n async disableAgent(agentId: string): Promise<AgentSummaryResponse> {\n return (await this.request(\"POST\", `/agents/${agentId}/disable`)) as AgentSummaryResponse;\n }\n\n /**\n * Resume (enable) a paused agent.\n *\n * Clears the disable state whether the agent was paused manually or\n * auto-paused by the inbound-email overload safeguard.\n *\n * @param agentId - Agent identifier.\n * @returns The updated agent summary.\n */\n async enableAgent(agentId: string): Promise<AgentSummaryResponse> {\n return (await this.request(\"POST\", `/agents/${agentId}/enable`)) as AgentSummaryResponse;\n }\n\n /**\n * List the live agents that call this agent via a `call_agent` step.\n *\n * These must be disabled before this agent can be paused.\n *\n * @param agentId - Agent identifier.\n * @returns The calling agents.\n */\n async getAgentCallers(agentId: string): Promise<AgentCallerApiResponse[]> {\n return listItems<AgentCallerApiResponse>(await this.request(\"GET\", `/agents/${agentId}/callers`));\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent Export / Import\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Export an agent definition as a portable JSON snapshot.\n *\n * @param agentId - Agent identifier.\n * @param download - When true (default), the server sets Content-Disposition: attachment.\n * @returns The exported agent snapshot.\n */\n async exportAgent(agentId: string, download = true): Promise<AgentExportResponse> {\n return (await this.request(\"GET\", `/agents/${agentId}/export`, {\n query: { download },\n })) as AgentExportResponse;\n }\n\n /**\n * Validate an `agent_definition` payload (same shape as {@link exportAgent})\n * without creating or modifying any agent.\n *\n * Use this before {@link createAgent} or {@link updateAgent} with an\n * `agent_definition` to surface `unresolved_refs` — workflow references to\n * knowledge bases, memory banks, source connections, or sub-agents that\n * don't exist in the target account. Pass the returned ids back in\n * `entity_remap` on the commit call to substitute them.\n *\n * @param body - The preview payload (`{ agent_definition: ... }`).\n * @returns Summary of the validated payload (step counts, schedules,\n * alert configs, evaluation criteria, governance policies, and any\n * `unresolved_refs`).\n * @throws {SeclaiAPIValidationError} On HTTP 422 — the body is an\n * {@link AgentDefinitionImportErrorResponse} with 1-indexed\n * line/column-anchored errors against a canonical `source` echo.\n */\n async previewImportAgent(body: AgentImportPreviewRequest): Promise<AgentImportPreviewResponse> {\n return (await this.request(\"POST\", \"/agents/preview-import\", { json: body })) as AgentImportPreviewResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent Definitions\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Get an agent's full definition (steps, model config, etc.).\n *\n * @param agentId - Agent identifier.\n * @returns The agent definition.\n */\n async getAgentDefinition(agentId: string): Promise<AgentDefinitionResponse> {\n return (await this.request(\"GET\", `/agents/${agentId}/definition`)) as AgentDefinitionResponse;\n }\n\n /**\n * Update an agent's definition.\n *\n * @param agentId - Agent identifier.\n * @param body - Updated definition payload.\n * @returns Updated agent definition.\n */\n async updateAgentDefinition(agentId: string, body: UpdateAgentDefinitionRequest): Promise<AgentDefinitionResponse> {\n return (await this.request(\"PUT\", `/agents/${agentId}/definition`, { json: body })) as AgentDefinitionResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent Runs\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Start an agent run.\n *\n * From `apiVersion` `2026-11-14`, an agent whose definition fails to validate\n * is refused with HTTP 409 ({@link SeclaiAPIStatusError}) and no run is\n * created; earlier versions return the run, already failed with the\n * validation error as its cause.\n *\n * @param agentId - Agent identifier.\n * @param body - Run request payload (`input`, `metadata`, `priority`, etc.).\n * @returns The created agent run.\n */\n async runAgent(agentId: string, body: AgentRunRequest): Promise<AgentRunResponse> {\n return (await this.request(\"POST\", `/agents/${agentId}/runs`, { json: body })) as AgentRunResponse;\n }\n\n /**\n * List runs for a specific agent.\n *\n * @param agentId - Agent identifier.\n * @param opts - Pagination and filter options.\n * @returns Paginated list of runs.\n */\n async listAgentRuns(\n agentId: string,\n opts: ListOptions & { status?: string } = {},\n ): Promise<AgentRunListResponse> {\n return (await this.request(\"GET\", `/agents/${agentId}/runs`, {\n query: { page: opts.page, limit: opts.limit, status: opts.status },\n })) as AgentRunListResponse;\n }\n\n /**\n * Search agent runs (traces) across all agents.\n *\n * @param body - Search query and filters.\n * @returns Search results with matching runs.\n */\n async searchAgentRuns(body: AgentTraceSearchRequest): Promise<AgentTraceSearchResponse> {\n return (await this.request(\"POST\", \"/agents/runs/search\", { json: body })) as AgentTraceSearchResponse;\n }\n\n /**\n * Get details of a specific agent run.\n *\n * @param runId - Run identifier.\n * @param opts - Optional flags.\n * @returns Agent run details.\n */\n async getAgentRun(\n runId: string,\n opts?: { includeStepOutputs?: boolean },\n ): Promise<AgentRunResponse> {\n return (await this.request(\"GET\", `/agents/runs/${runId}`, opts?.includeStepOutputs ? {\n query: { include_step_outputs: true },\n } : undefined)) as AgentRunResponse;\n }\n\n /**\n * Cancel an agent run.\n *\n * @deprecated This never deleted anything — the endpoint it calls is documented\n * as \"Cancel an agent run\", and the API has no delete-a-run operation. It also\n * discards the returned run state. Use {@link cancelAgentRun} instead.\n *\n * @param runId - Run identifier.\n */\n async deleteAgentRun(runId: string): Promise<void> {\n await this.cancelAgentRun(runId);\n }\n\n /**\n * Cancel an agent run that has not ended: `queued`, `pending`, `processing`,\n * `waiting_human` or `waiting_scheduled`.\n *\n * Cancellation is `DELETE` on the run resource — the API exposes no\n * `POST .../cancel` route, and no operation that deletes a run. Rejected when\n * the run has already ended (`completed`, `failed` or `cancelled`). From\n * `apiVersion` `2026-11-08` the cancelled run ends with status `cancelled`;\n * on earlier versions it ends `failed`.\n *\n * @param runId - Run identifier.\n * @returns The updated run.\n */\n async cancelAgentRun(runId: string): Promise<AgentRunResponse> {\n return (await this.request(\"DELETE\", `/agents/runs/${runId}`)) as AgentRunResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent Runs — Streaming\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Run an agent in streaming mode (SSE) and wait for the final result.\n *\n * Reads the events of {@link runStreamingAgent} and returns the run from the\n * terminal `done` event. For real-time event access, use\n * {@link runStreamingAgent} instead. The body takes no `include_reasoning`\n * or `include_commentary`, and one passed anyway is not sent: this method\n * returns no `stream_reasoning` or `stream_commentary` events.\n *\n * A `result` event carries the run's answer in `output` once\n * `result_reported_at` is set, and can arrive while later steps still run.\n * Pass `returnOnResult: true` to return that `result` snapshot as soon as it\n * arrives, without waiting for `done`. Such a run may still be in progress:\n * its `status` is not terminal and the run can still fail, so check\n * `result_reported_at`, not `status`.\n *\n * The latest snapshot is the `result` event's run if one arrived, else the\n * `init` event's run. When the server sends an `error`\n * event, this throws {@link SeclaiStreamingError} with the server's error\n * text in its message; when the server sends a `timeout` event, or\n * `timeoutMs` elapses (unless an HTTP error status arrives as it elapses),\n * it throws {@link SeclaiStreamingError} too. Each\n * carries the latest snapshot in `run`. An abort from `signal` rethrows the\n * abort error. Every way out of this method closes the response body.\n *\n * By default, a stream that ends before `done` returns the latest snapshot\n * when its status is not `pending`, so the run returned may\n * not have finished: check `status` and `result_reported_at`. A stream that\n * breaks throws the fetch error, unless a `done` event, or with\n * `returnOnResult` a `result` event, was read in full before it\n * broke. Pass `throwOnIncomplete: true` to throw\n * {@link SeclaiStreamingError} with the latest snapshot in `run` in both\n * cases instead; it is recommended, and becomes the default in the next\n * major version.\n *\n * @param agentId - Agent identifier.\n * @param body - Streaming run request payload, without `include_reasoning`\n * or `include_commentary`.\n * @param opts - Timeout, abort signal and `returnOnResult` options.\n * @returns The run from the `done` event; with `returnOnResult`, the\n * `result` snapshot; without `throwOnIncomplete`, possibly an unfinished\n * snapshot (see above).\n * @throws {@link SeclaiStreamingError} If the server sends an `error` or\n * `timeout` event, `timeoutMs` elapses (unless an HTTP error status\n * arrives as it elapses), or, with `throwOnIncomplete`, the\n * stream ends or breaks, before the run finished. Its `run` holds the\n * latest snapshot. On `timeoutMs`, when the request or read was cut off,\n * its `cause` is the error it ended with.\n * @throws {@link SeclaiAPIStatusError} For an HTTP error status, also one\n * that arrives as `timeoutMs` elapses.\n *\n * @example\n * ```ts\n * try {\n * const run = await client.runStreamingAgentAndWait(\"agent-id\", { input: \"Hello\" }, { throwOnIncomplete: true });\n * console.log(run.output);\n * } catch (err) {\n * if (err instanceof SeclaiStreamingError && err.run?.result_reported_at) {\n * console.log(\"Answer (run not finished):\", err.run.output);\n * } else throw err;\n * }\n * ```\n */\n async runStreamingAgentAndWait(\n agentId: string,\n body: Omit<AgentRunStreamRequest, \"include_reasoning\" | \"include_commentary\">,\n opts?: {\n timeoutMs?: number;\n signal?: AbortSignal;\n /**\n * Return the `result` snapshot as soon as a `result` event arrives (its\n * answer is in `output`), without waiting for `done` (default: false).\n */\n returnOnResult?: boolean;\n /**\n * Throw {@link SeclaiStreamingError}, with the latest snapshot in `run`,\n * whenever the stream ends or breaks before `done`, or the server answers\n * with plain JSON for a run that has not finished, instead of returning\n * an unfinished run or throwing the fetch error (default: false). This\n * becomes the default in the next major version.\n */\n throwOnIncomplete?: boolean;\n },\n ): Promise<AgentRunResponse> {\n // Not sent even from untyped callers: the reasoning and commentary events\n // are discarded here.\n const {\n include_reasoning: _reasoning,\n include_commentary: _commentary,\n ...runBody\n } = body as AgentRunStreamRequest;\n const timeoutMs = opts?.timeoutMs ?? 60_000;\n const streamOpts: { timeoutMs: number; signal?: AbortSignal } = { timeoutMs };\n if (opts?.signal) streamOpts.signal = opts.signal;\n const progress: StreamProgress = { jsonReply: false, reading: false, timedOut: false };\n\n // The latest snapshot, as released: the result event's run, else the init\n // event's, else none. Update events do not count.\n let initial: AgentRunResponse | undefined;\n let reported: AgentRunResponse | undefined;\n const snapshot = () => reported ?? initial;\n\n try {\n // Returning or throwing inside the loop closes the iterator, which\n // cancels the reader.\n for await (const { event, data } of this.streamRunEvents(agentId, runBody, streamOpts, progress)) {\n if (event === \"error\" || event === \"timeout\") {\n const info = isRunSnapshot(data) ? (data as { run_id?: unknown; error?: unknown }) : {};\n const runId = typeof info.run_id === \"string\" ? info.run_id : undefined;\n if (event === \"timeout\") {\n throw incompleteRunError(\"The server timed out the streaming agent run before it finished.\", snapshot(), runId);\n }\n const text = typeof info.error === \"string\" ? info.error : typeof data === \"string\" ? data : undefined;\n const reason = text\n ? `The streaming agent run failed on the server: ${text}${/[.!?]$/.test(text) ? \"\" : \".\"}`\n : \"The streaming agent run failed on the server.\";\n throw incompleteRunError(reason, snapshot(), runId);\n }\n if (!isRunSnapshot(data)) continue;\n if (event === \"init\") {\n initial = data;\n } else if (event === \"result\") {\n reported = data;\n if (opts?.returnOnResult) return data;\n } else if (event === \"done\") {\n const finished = isTerminalStatus(data.status) || Boolean(opts?.returnOnResult && data.result_reported_at);\n if (progress.jsonReply && opts?.throwOnIncomplete && !finished) {\n throw incompleteRunError(\"The server answered with JSON for a run that has not finished.\", data);\n }\n return data;\n }\n }\n } catch (err) {\n // The caller asked to stop: keep the abort error.\n if (opts?.signal?.aborted) throw err;\n if (streamTimeouts.has(err as object)) {\n throw withCause(incompleteRunError(streamTimeoutMessage(timeoutMs), snapshot()), (err as Error).cause);\n }\n // A failure after the body was being read is a broken stream. Without\n // throwOnIncomplete it throws the fetch error, as released.\n if (opts?.throwOnIncomplete && progress.reading && !(err instanceof SeclaiStreamingError)) {\n const message = err instanceof Error ? err.message : String(err);\n throw incompleteRunError(`Stream failed before the run finished: ${message}.`, snapshot());\n }\n throw err;\n }\n\n // A body the timeout did not cut ended after it: still a timeout, as released.\n if (progress.timedOut) throw incompleteRunError(streamTimeoutMessage(timeoutMs), snapshot());\n // Released behaviour without throwOnIncomplete: the stream ended early.\n const latest = snapshot();\n if (!opts?.throwOnIncomplete && latest?.status && latest.status !== \"pending\") {\n return latest;\n }\n throw incompleteRunError(\"Stream ended before receiving a 'done' event.\", snapshot());\n }\n\n /**\n * Run an agent in streaming mode and yield each SSE event as it arrives.\n *\n * This is an `AsyncGenerator` suitable for real-time UIs that want to render\n * step progress as it happens. Set `include_reasoning` or\n * `include_commentary` in `body` to also receive `stream_reasoning` or\n * `stream_commentary` events.\n *\n * The server ends the stream after `done`, after `error` (data\n * `{ run_id, error }`, the stream failed on the server) or after `timeout`\n * (data `{ run_id }`); all three are yielded like any other event. When the\n * server answers with plain JSON instead of SSE, its run is yielded as one\n * `done` event. Leaving the loop early (`break`, `return` or a throw)\n * closes the response body.\n *\n * From `apiVersion` `2026-11-14`, an agent whose definition fails to validate\n * is refused with HTTP 409 ({@link SeclaiAPIStatusError}) before any event,\n * and no run is created.\n *\n * @param agentId - Agent identifier.\n * @param body - Streaming run request payload.\n * @param opts - Timeout and abort signal options.\n * @yields {@link AgentRunEvent} for each SSE message.\n * @throws {@link SeclaiStreamingError} If `timeoutMs` elapses, with the\n * error the request or read ended with as its `cause`. An HTTP error\n * status that arrives as it elapses is thrown as itself. An event read\n * in full before the stream broke or timed out is yielded first, unless\n * `signal` was aborted.\n *\n * @example\n * ```ts\n * for await (const event of client.runStreamingAgent(\"agent-id\", { input: \"Hello!\" })) {\n * // `result` carries the answer in `output`, possibly before later steps finish.\n * if (event.event === \"result\") {\n * console.log(\"Answer:\", (event.data as AgentRunResponse).output);\n * }\n * if (event.event === \"done\") {\n * console.log(\"Final:\", event.data);\n * }\n * }\n * ```\n */\n async *runStreamingAgent(\n agentId: string,\n body: AgentRunStreamRequest,\n opts?: { timeoutMs?: number; signal?: AbortSignal },\n ): AsyncGenerator<AgentRunEvent, void, undefined> {\n yield* this.streamRunEvents(agentId, body, opts);\n }\n\n /**\n * The stream behind {@link runStreamingAgent} and\n * {@link runStreamingAgentAndWait}: one request, reader and parser for both.\n * `progress` tells the wait helper what the events alone do not.\n */\n private async *streamRunEvents(\n agentId: string,\n body: AgentRunStreamRequest,\n opts: { timeoutMs?: number; signal?: AbortSignal } | undefined,\n progress?: StreamProgress,\n ): AsyncGenerator<AgentRunEvent, void, undefined> {\n const url = buildURL(this.baseUrl, `/agents/${agentId}/runs/stream`);\n\n const authHdrs = await this.authHeaders();\n const headers = this.requestHeaders([\n this.defaultHeaders,\n authHdrs,\n { accept: \"text/event-stream\", \"content-type\": \"application/json\" },\n ]);\n\n const timeoutMs = opts?.timeoutMs ?? 60_000;\n const timeoutController = new AbortController();\n let timedOut = false;\n const timeoutId = setTimeout(() => {\n timedOut = true;\n if (progress) progress.timedOut = true;\n timeoutController.abort();\n }, timeoutMs);\n\n const { signal, cleanup } = anySignal([opts?.signal, timeoutController.signal]);\n let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\n try {\n const init: RequestInit = { method: \"POST\", headers, body: JSON.stringify(body) };\n if (signal) init.signal = signal;\n\n const response = await this.fetcher(url, init);\n\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n const isJson = contentType.includes(\"application/json\");\n\n if (!response.ok) {\n const responseText = await safeText(response);\n if (response.status === 422) {\n const validation = await safeJson(response);\n throw new SeclaiAPIValidationError({\n message: \"Validation error\",\n statusCode: response.status,\n method: \"POST\",\n url: url.toString(),\n responseText,\n headers: new Headers(response.headers),\n validationError: validation,\n });\n }\n throw new SeclaiAPIStatusError({\n message: `Request failed with status ${response.status}`,\n statusCode: response.status,\n method: \"POST\",\n url: url.toString(),\n responseText,\n headers: new Headers(response.headers),\n });\n }\n\n // If server returned JSON instead of SSE, yield it as a single \"done\" event\n if (isJson) {\n const data = (await response.json()) as AgentRunResponse;\n if (progress) progress.jsonReply = true;\n yield { event: \"done\", data };\n return;\n }\n\n if (!response.body) {\n throw new SeclaiConfigurationError(\n \"Streaming response body is not available in this environment. Provide a fetch implementation that supports ReadableStream bodies.\"\n );\n }\n\n reader = response.body.getReader();\n if (progress) progress.reading = true;\n const decoder = new TextDecoder();\n const events: AgentRunEvent[] = [];\n\n const parser = createSseParser((msg) => {\n if (!msg.data) return;\n let data: unknown;\n try {\n data = JSON.parse(msg.data);\n } catch {\n data = msg.data;\n }\n events.push({ event: msg.event ?? \"message\", data });\n });\n\n while (true) {\n let chunk: ReadableStreamReadResult<Uint8Array>;\n try {\n chunk = await reader.read();\n } catch (err) {\n // Keep an event whose lines were read in full before the failure,\n // unless the caller aborted: then only the abort error is thrown.\n if (!opts?.signal?.aborted) {\n parser.feed(decoder.decode());\n parser.abandon();\n while (events.length > 0) yield events.shift()!;\n }\n throw err;\n }\n const { value, done } = chunk;\n if (value) parser.feed(decoder.decode(value, { stream: true }));\n if (done) {\n parser.feed(decoder.decode());\n parser.end();\n }\n\n // Yield all events that were parsed from this chunk\n while (events.length > 0) {\n yield events.shift()!;\n }\n\n if (done) break;\n }\n } catch (err) {\n // An HTTP error status that arrived is thrown as itself.\n if (timedOut && !(err instanceof SeclaiAPIStatusError)) {\n // The error the fetch or read ended with is its cause.\n const timeout = withCause(new SeclaiStreamingError(streamTimeoutMessage(timeoutMs)), err);\n streamTimeouts.add(timeout);\n throw timeout;\n }\n throw err;\n } finally {\n clearTimeout(timeoutId);\n cleanup();\n reader?.cancel().catch(() => {});\n }\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent Runs — Polling\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Run an agent and poll until it reaches a terminal status.\n *\n * This is useful in environments where SSE streaming is unavailable.\n *\n * A run's answer can be ready before its last step finishes: once\n * `result_reported_at` is set, `output` holds the answer. Pass\n * `returnOnResult: true` to return as soon as a run has it set, the run\n * `runAgent()` returns included. With `includeStepOutputs`, when that run\n * would end the poll, it is fetched again at once for its step outputs.\n * Such a run may still be in progress: its `status` is not terminal and the\n * run can still fail, so check `result_reported_at`, not `status`.\n *\n * When `timeoutMs` elapses first, this throws {@link SeclaiStreamingError}\n * with the latest run it has (the `runAgent()` response if no poll answered)\n * in `run`. If that run has `result_reported_at` set, its `output` is the\n * answer. No poll is sent at or after the deadline: a wait between polls that\n * reaches it ends the call with the timeout, so a `timeoutMs` no greater than\n * `pollIntervalMs` sends no poll. With a `fetch` that honours `signal`, a\n * poll still in flight at the deadline is aborted and the timeout is thrown.\n * Any error but an HTTP error status that a poll ends with once the deadline\n * has passed is the timeout's `cause`; an HTTP error status a poll gets after\n * the deadline is thrown as itself, and a caller abort throws `signal.reason`\n * instead. `timeoutMs` does not cut off the start request (the server may\n * already have created the run) or the fetch for an ended start run's step\n * outputs; only `signal` does. A request is not cut off while more than\n * 2^31-1 ms remain.\n *\n * `signal` is passed to every request and to the wait between polls. An\n * abort throws `signal.reason`, as `signal.throwIfAborted()` does (by\n * default an `AbortError`), or an `AbortError` for a signal that has no\n * `reason`: an already-aborted signal starts no run. A run\n * that has ended the poll is returned even after an abort. When the start\n * run has ended it and `includeStepOutputs` is set, an abort during the\n * fetch for its step outputs (with a `fetch` that honours `signal`) returns\n * the start run without step outputs.\n *\n * @param agentId - Agent identifier.\n * @param body - Run request payload.\n * @param opts - Polling configuration and abort signal.\n * @returns The terminal agent run, or, with `returnOnResult`, the first run\n * with `result_reported_at` set.\n * @throws {@link SeclaiStreamingError} If `timeoutMs` elapses before the run\n * finished. Its `run` holds the latest run it has (the `runAgent()`\n * response if no poll answered), and its `cause` the error a poll ended\n * with at the deadline, if one did (a caller abort throws `signal.reason`\n * instead).\n * @throws `signal.reason` If `signal` is aborted before the run has ended\n * the poll.\n */\n async runAgentAndPoll(\n agentId: string,\n body: AgentRunRequest,\n opts?: {\n /** Polling interval in ms (default: 2000). */\n pollIntervalMs?: number;\n /** Maximum time to wait in ms (default: 300000 = 5 min). */\n timeoutMs?: number;\n /** Include per-step outputs in the final result. */\n includeStepOutputs?: boolean;\n /**\n * Return as soon as a run, the `runAgent()` response included, has\n * `result_reported_at` set (its answer is in `output`), without waiting\n * for later steps to finish (default: false).\n */\n returnOnResult?: boolean;\n signal?: AbortSignal;\n },\n ): Promise<AgentRunResponse> {\n const pollInterval = opts?.pollIntervalMs ?? 2_000;\n const timeout = opts?.timeoutMs ?? 300_000;\n const signal = opts?.signal;\n const deadline = Date.now() + timeout;\n\n throwIfAborted(signal);\n let current: AgentRunResponse | undefined;\n let runId: string | undefined;\n const timedOut = () => incompleteRunError(`Polling timed out after ${timeout}ms.`, current, runId);\n // Each request gets its own signal, linked to the caller's and unlinked\n // when it settles, so a fetch that leaves its listener on the signal it was\n // given leaves none on the caller's. A caller abort throws the abort error,\n // whatever the fetch rejects with. With `bounded`, the request is also cut\n // off at the deadline, which throws the timeout, unless an HTTP error\n // status arrived anyway: that is thrown as itself. No timer is set while more than\n // MAX_TIMER_MS remain (setTimeout would fire at once).\n const abortable = async <T>(bounded: boolean, send: (s: AbortSignal | undefined) => Promise<T>): Promise<T> => {\n const limit = new AbortController();\n const left = deadline - Date.now();\n // A wait that ran late must not send a poll past the deadline.\n if (bounded && left <= 0) throw timedOut();\n const timer = bounded && Number.isFinite(left) && left <= MAX_TIMER_MS\n ? setTimeout(() => limit.abort(), Math.max(left, 0))\n : undefined;\n const linked = anySignal([signal, limit.signal]);\n try {\n return await send(linked.signal);\n } catch (err) {\n throwIfAborted(signal);\n // A status that arrived is thrown as itself; anything else once the\n // deadline has fired is the cut-off, whatever the fetch turned it into.\n if (limit.signal.aborted && !(err instanceof SeclaiAPIStatusError)) {\n // Keep what the request ended with, which may not be the abort.\n throw withCause(timedOut(), err);\n }\n throw err;\n } finally {\n clearTimeout(timer);\n linked.cleanup();\n }\n };\n const pollOpts = (s: AbortSignal | undefined) => {\n const o: { query?: Record<string, unknown>; signal?: AbortSignal } = {};\n if (opts?.includeStepOutputs) o.query = { include_step_outputs: true };\n if (s) o.signal = s;\n return o;\n };\n const endsPoll = (r: AgentRunResponse) =>\n isTerminalStatus(r.status) || Boolean(opts?.returnOnResult && r.result_reported_at);\n\n // runAgent(), with the signal. timeoutMs does not cut it off: the server may\n // already have created the run, and there would be no runId to find it by.\n const run = (await abortable(false, (s) => {\n const startOpts: { json: unknown; signal?: AbortSignal } = { json: body };\n if (s) startOpts.signal = s;\n return this.request(\"POST\", `/agents/${agentId}/runs`, startOpts);\n })) as AgentRunResponse;\n runId = (run as any).id ?? (run as any).run_id;\n if (!runId) throw new SeclaiError(\"Agent run response did not contain an id.\");\n\n // The initial response is checked too: a fast run can already be done. It\n // carries no step outputs, so when they are asked for and it would end the\n // poll, fetch the run first. This is not waiting for the run, so timeoutMs\n // does not cut it off. After an abort, the start run is returned without them.\n current = run;\n if (opts?.includeStepOutputs && endsPoll(run) && !signal?.aborted) {\n try {\n current = (await abortable(false, (s) => this.request(\"GET\", `/agents/runs/${runId}`, pollOpts(s)))) as AgentRunResponse;\n } catch (err) {\n if (!signal?.aborted) throw err;\n }\n }\n while (true) {\n if (endsPoll(current)) return current;\n\n throwIfAborted(signal);\n const left = deadline - Date.now();\n if (left <= pollInterval) {\n // The wait reaches the deadline: no poll is sent at or after it.\n if (left > 0) await sleep(left, signal);\n throw timedOut();\n }\n await sleep(pollInterval, signal);\n\n current = (await abortable(true, (s) => this.request(\"GET\", `/agents/runs/${runId}`, pollOpts(s)))) as AgentRunResponse;\n }\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent Run Evaluation Results\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List evaluation results for a specific agent run.\n *\n * @param agentId - Agent identifier.\n * @param runId - Run identifier.\n * @param opts - Pagination options.\n * @returns Paginated list of evaluation results.\n */\n async listRunEvaluationResults(\n agentId: string,\n runId: string,\n opts: ListOptions = {},\n ): Promise<EvaluationResultWithCriteriaListResponse> {\n return keyedList<EvaluationResultWithCriteriaListResponse>(\n await this.request(\"GET\", `/agents/${agentId}/runs/${runId}/evaluation-results`, {\n query: { page: opts.page, limit: opts.limit },\n }),\n \"data\",\n PAGE_COUNTERS,\n );\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent Input Uploads\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Upload a file to use as input for a `dynamic_input` agent run. Any other\n * agent rejects the upload with HTTP 400. Files are limited to 200 MB.\n *\n * From API version `2026-10-16` a file of any type is accepted and is `ready`\n * at once: pass its `id` as `input_upload_id` to {@link runAgent}.\n * Earlier versions accept only a fixed list of extensions and write each\n * file's extracted text into the run's `input`, so poll\n * {@link getAgentInputUploadStatus} until `status` is `ready` before running.\n *\n * @param agentId - Agent identifier.\n * @param opts - File payload and optional metadata.\n * @returns Upload response with the upload ID and status.\n */\n async uploadAgentInput(\n agentId: string,\n opts: {\n file: Blob | Uint8Array | ArrayBuffer | BufferSource;\n fileName?: string;\n mimeType?: string;\n },\n ): Promise<UploadAgentInputApiResponse> {\n return (await this.uploadFile(`/agents/${agentId}/upload-input`, opts)) as UploadAgentInputApiResponse;\n }\n\n /**\n * Get the status of an agent input upload.\n *\n * @param agentId - Agent identifier.\n * @param uploadId - Upload identifier.\n * @returns Upload status and metadata.\n */\n async getAgentInputUploadStatus(agentId: string, uploadId: string): Promise<UploadAgentInputApiResponse> {\n return (await this.request(\"GET\", `/agents/${agentId}/input-uploads/${uploadId}`)) as UploadAgentInputApiResponse;\n }\n\n /**\n * Get the static attachment-reference contract for an agent — what files (if\n * any) its definition expects on a run.\n *\n * Call this before staging uploads to learn whether the agent accepts files\n * at all (`requires_uploads`) and which specific filenames, indexes, or glob\n * patterns its templates reference. A run-time upload batch that doesn't\n * satisfy every declared selector is rejected with HTTP 400.\n *\n * @param agentId - Agent identifier.\n * @returns The agent's attachment-reference contract.\n */\n async getAgentAttachmentReferences(agentId: string): Promise<AgentAttachmentRefsApiResponse> {\n return (await this.request(\"GET\", `/agents/${agentId}/attachment-references`)) as AgentAttachmentRefsApiResponse;\n }\n\n /**\n * Download a file of an agent run (one a step emitted or one the run started\n * with), or one byte range of it.\n *\n * Returns the raw `Response` so you can stream or save the binary data.\n *\n * To fetch part of the file, set a byte range. Offsets are zero-based and\n * `rangeEnd` is inclusive:\n *\n * - `rangeStart` alone sends `Range: bytes=<rangeStart>-`, from that byte to the end.\n * - `rangeStart` and `rangeEnd` send `Range: bytes=<rangeStart>-<rangeEnd>`.\n * - `rangeSuffix` alone sends `Range: bytes=-<rangeSuffix>`, the last that many bytes.\n *\n * With none of them set, the SDK adds no `Range` header. The server answers a range\n * with status 206 and a `Content-Range` header, so check `resp.status` before\n * treating the body as the whole file. A range of an empty file is answered with\n * 200 and the whole (empty) file. A range that starts at or past the end of a\n * non-empty file throws {@link SeclaiAPIStatusError} with `statusCode` 416,\n * and its `headers.get(\"content-range\")` ends in `/<size>`, the file's size in\n * bytes.\n *\n * @param runId - Run identifier.\n * @param attachmentId - The `id` of an entry in the run's or a step's\n * `attachments`, or the URL-safe-base64-encoded storage key that webhook and\n * email links carry.\n * @param opts - Optional `downloadName` filename hint for the download\n * disposition; `rangeStart`, `rangeEnd` and `rangeSuffix`, the byte range\n * described above; and `signal`, which cancels the request; with a standard `fetch` this\n * includes reading the body, so `AbortSignal.timeout(ms)` bounds the whole\n * transfer.\n * @returns Raw response with the attachment bytes: status 200 with the whole\n * file, or 206 with the requested range.\n * @throws {@link SeclaiConfigurationError} Before any request, when the range\n * options are not one of the three forms above: `rangeEnd` without\n * `rangeStart`, `rangeSuffix` with either of them, `rangeEnd` less than\n * `rangeStart`, a negative `rangeStart` or `rangeEnd`, a `rangeSuffix` below\n * 1, or a value that is not a safe integer (`Number.isSafeInteger`).\n * @throws {@link SeclaiAPIStatusError} On a non-2xx response, including 416\n * when the range cannot be satisfied.\n */\n async downloadAgentRunAttachment(\n runId: string,\n attachmentId: string,\n opts: {\n downloadName?: string;\n rangeStart?: number;\n rangeEnd?: number;\n rangeSuffix?: number;\n signal?: AbortSignal;\n } = {},\n ): Promise<Response> {\n const range = byteRangeHeader(opts.rangeStart, opts.rangeEnd, opts.rangeSuffix);\n return await this.requestRaw(\"GET\", `/v2/agent-runs/${runId}/attachments/${attachmentId}`, {\n query: { download_name: opts.downloadName },\n ...(range === undefined ? {} : { headers: { Range: range } }),\n signal: opts.signal,\n });\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent AI Assistant (Steps Generation)\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Generate agent workflow steps from natural language using AI.\n *\n * @param agentId - Agent identifier.\n * @param body - Generation request with user instructions.\n * @returns AI-generated step configuration.\n */\n async generateAgentSteps(agentId: string, body: GenerateAgentStepsRequest): Promise<GenerateAgentStepsResponse> {\n return (await this.request(\"POST\", `/agents/${agentId}/ai-assistant/generate-steps`, { json: body })) as GenerateAgentStepsResponse;\n }\n\n /**\n * Generate a single step configuration using AI.\n *\n * @param agentId - Agent identifier.\n * @param body - Step config generation request.\n * @returns AI-generated step config.\n */\n async generateStepConfig(agentId: string, body: GenerateStepConfigRequest): Promise<GenerateStepConfigResponse> {\n return (await this.request(\"POST\", `/agents/${agentId}/ai-assistant/step-config`, { json: body })) as GenerateStepConfigResponse;\n }\n\n /**\n * Get AI conversation history for an agent.\n *\n * @param agentId - Agent identifier.\n * @returns Conversation history.\n */\n async getAgentAiConversationHistory(\n agentId: string,\n opts: { stepType?: string; stepId?: string; limit?: number; offset?: number } = {},\n ): Promise<AiConversationHistoryResponse> {\n // `step_type` is required by the API. It stays optional in the type so the\n // released one-argument call still compiles, but leaving it undefined only\n // means buildURL drops it and the server answers 422 naming the wire\n // parameter — so fail here instead, naming the option.\n if (!opts.stepType) {\n throw new SeclaiConfigurationError(\n \"getAgentAiConversationHistory requires opts.stepType; the API rejects the \" +\n \"request without it. Pass e.g. { stepType: \\\"llm\\\" }.\",\n );\n }\n return (await this.request(\"GET\", `/agents/${agentId}/ai-assistant/conversations`, {\n query: {\n step_type: opts.stepType,\n step_id: opts.stepId,\n limit: opts.limit,\n offset: opts.offset,\n },\n })) as AiConversationHistoryResponse;\n }\n\n /**\n * Mark an AI suggestion as accepted or rejected.\n *\n * @param agentId - Agent identifier.\n * @param conversationId - Conversation turn identifier.\n * @param body - Mark request payload.\n */\n async markAgentAiSuggestion(agentId: string, conversationId: string, body: MarkAiSuggestionRequest): Promise<void> {\n await this.request(\"PATCH\", `/agents/${agentId}/ai-assistant/${conversationId}`, { json: body });\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent Evaluation Criteria\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List evaluation criteria for an agent.\n *\n * @param agentId - Agent identifier.\n * @param opts - Pagination options.\n */\n async listEvaluationCriteria(agentId: string, opts: ListOptions = {}): Promise<EvaluationCriteriaResponse[]> {\n return (await this.listEvaluationCriteriaPage(agentId, opts)).data ?? [];\n }\n\n /**\n * List evaluation criteria for an agent, with pagination metadata.\n *\n * The endpoint answers with a bare array by default and with `{data,\n * pagination}` once `apiVersion` is 2026-07-27 or later; `pagination` is\n * absent on the bare array.\n *\n * @param agentId - Agent identifier.\n * @param opts - Pagination options.\n * @returns The criteria under `data`, plus the page metadata when present.\n */\n async listEvaluationCriteriaPage(\n agentId: string,\n opts: ListOptions = {},\n ): Promise<EvaluationCriteriaListResponse> {\n return keyedList<EvaluationCriteriaListResponse>(\n await this.request(\"GET\", `/agents/${agentId}/evaluation-criteria`, {\n query: { page: opts.page, limit: opts.limit },\n }),\n \"data\",\n );\n }\n\n /**\n * Create evaluation criteria for an agent.\n *\n * @param agentId - Agent identifier.\n * @param body - Criteria definition.\n * @returns Created evaluation criteria.\n */\n async createEvaluationCriteria(agentId: string, body: CreateEvaluationCriteriaRequest): Promise<EvaluationCriteriaResponse> {\n return (await this.request(\"POST\", `/agents/${agentId}/evaluation-criteria`, { json: body })) as EvaluationCriteriaResponse;\n }\n\n /**\n * Get a single evaluation criteria by ID.\n *\n * @param criteriaId - Criteria identifier.\n * @returns Evaluation criteria details.\n */\n async getEvaluationCriteria(criteriaId: string): Promise<EvaluationCriteriaResponse> {\n return (await this.request(\"GET\", `/agents/evaluation-criteria/${criteriaId}`)) as EvaluationCriteriaResponse;\n }\n\n /**\n * Update an evaluation criteria.\n *\n * @param criteriaId - Criteria identifier.\n * @param body - Fields to update.\n * @returns Updated evaluation criteria.\n */\n async updateEvaluationCriteria(criteriaId: string, body: UpdateEvaluationCriteriaRequest): Promise<EvaluationCriteriaResponse> {\n return (await this.request(\"PATCH\", `/agents/evaluation-criteria/${criteriaId}`, { json: body })) as EvaluationCriteriaResponse;\n }\n\n /**\n * Delete an evaluation criteria and all associated results.\n *\n * @param criteriaId - Criteria identifier.\n */\n async deleteEvaluationCriteria(criteriaId: string): Promise<void> {\n await this.request(\"DELETE\", `/agents/evaluation-criteria/${criteriaId}`);\n }\n\n /**\n * Get the evaluation summary for a specific criteria.\n *\n * @param criteriaId - Criteria identifier.\n * @returns Evaluation result summary.\n */\n async getEvaluationCriteriaSummary(criteriaId: string): Promise<EvaluationResultSummaryResponse> {\n return (await this.request(\"GET\", `/agents/evaluation-criteria/${criteriaId}/summary`)) as EvaluationResultSummaryResponse;\n }\n\n /**\n * List evaluation results for a specific criteria.\n *\n * @param criteriaId - Criteria identifier.\n * @param opts - Pagination, status, flag and time-range filters.\n */\n async listEvaluationResults(\n criteriaId: string,\n opts: ListEvaluationResultsOptions = {},\n ): Promise<EvaluationResultListResponse> {\n return keyedList<EvaluationResultListResponse>(\n await this.request(\"GET\", `/agents/evaluation-criteria/${criteriaId}/results`, {\n query: {\n page: opts.page,\n limit: opts.limit,\n status: opts.status,\n flagged_only: opts.flaggedOnly,\n time_from: opts.timeFrom,\n time_to: opts.timeTo,\n },\n }),\n \"data\",\n PAGE_COUNTERS,\n );\n }\n\n /**\n * Create a manual evaluation result for a criteria.\n *\n * @param criteriaId - Criteria identifier.\n * @param body - Evaluation result payload.\n * @returns Created evaluation result.\n */\n async createEvaluationResult(criteriaId: string, body: CreateEvaluationResultRequest): Promise<EvaluationResultResponse> {\n return (await this.request(\"POST\", `/agents/evaluation-criteria/${criteriaId}/results`, { json: body })) as EvaluationResultResponse;\n }\n\n /**\n * List runs compatible with a specific evaluation criteria.\n *\n * @param criteriaId - Criteria identifier.\n * @param opts - Pagination and a `startedAfter` filter.\n */\n async listCompatibleRuns(criteriaId: string, opts: ListCompatibleRunsOptions = {}): Promise<CompatibleRunListResponse> {\n return keyedList<CompatibleRunListResponse>(\n await this.request(\"GET\", `/agents/evaluation-criteria/${criteriaId}/compatible-runs`, {\n query: { page: opts.page, limit: opts.limit, started_after: opts.startedAfter },\n }),\n \"data\",\n PAGE_COUNTERS,\n );\n }\n\n /**\n * Test a draft evaluation criteria without persisting it.\n *\n * @param agentId - Agent identifier.\n * @param body - Draft evaluation to test.\n * @returns Test evaluation response.\n */\n async testDraftEvaluation(agentId: string, body: TestDraftEvaluationRequest): Promise<TestDraftEvaluationResponse> {\n return (await this.request(\"POST\", `/agents/${agentId}/evaluation-criteria/test-draft`, { json: body })) as TestDraftEvaluationResponse;\n }\n\n /**\n * List all evaluation results for an agent.\n *\n * @param agentId - Agent identifier.\n * @param opts - Pagination, status, step, flag and time-range filters.\n */\n async listAgentEvaluationResults(\n agentId: string,\n opts: ListAgentEvaluationResultsOptions = {},\n ): Promise<EvaluationResultWithCriteriaListResponse> {\n return keyedList<EvaluationResultWithCriteriaListResponse>(\n await this.request(\"GET\", `/agents/${agentId}/evaluation-results`, {\n query: {\n page: opts.page,\n limit: opts.limit,\n status: opts.status,\n step: opts.step,\n flagged_only: opts.flaggedOnly,\n time_from: opts.timeFrom,\n time_to: opts.timeTo,\n },\n }),\n \"data\",\n PAGE_COUNTERS,\n );\n }\n\n /**\n * List evaluation run summaries for an agent.\n *\n * @param agentId - Agent identifier.\n * @param opts - Pagination, status, step and time-range filters.\n */\n async listEvaluationRuns(agentId: string, opts: ListEvaluationRunsOptions = {}): Promise<EvaluationRunSummaryListResponse> {\n return keyedList<EvaluationRunSummaryListResponse>(\n await this.request(\"GET\", `/agents/${agentId}/evaluation-runs`, {\n query: {\n page: opts.page,\n limit: opts.limit,\n status: opts.status,\n step: opts.step,\n time_from: opts.timeFrom,\n time_to: opts.timeTo,\n },\n }),\n \"data\",\n PAGE_COUNTERS,\n );\n }\n\n /**\n * Get a summary of non-manual evaluations, for one agent or the whole account.\n *\n * @param agentId - Agent identifier. Omit (pass `undefined`) for the account-wide summary.\n * @param opts - Date range. `startDate` and `endDate` together set the range;\n * `startDate` alone runs from it through today; otherwise the last `days`\n * days apply (server default 30), and an `endDate` without `startDate` is ignored.\n */\n async getNonManualEvaluationSummary(\n agentId?: string,\n opts: DateRangeOptions = {},\n ): Promise<NonManualEvaluationSummaryResponse> {\n return (await this.request(\"GET\", \"/agents/evaluation-results/non-manual-summary\", {\n query: { agent_id: agentId, days: opts.days, start_date: opts.startDate, end_date: opts.endDate },\n })) as NonManualEvaluationSummaryResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent Email Triggers\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Configure an agent's `EMAIL_RECEIVED` trigger and return its computed\n * email address(es).\n *\n * Sets the custom alias, the sender allowlist, and the inbound-handling flags\n * (`ignore_auto_generated`, `require_sender_auth`, `queue_on_quota`). Omitted\n * fields are left unchanged; passing `null` (or `\"\"` for `alias`) clears them.\n *\n * @param agentId - Agent identifier.\n * @param triggerId - Trigger identifier.\n * @param body - The fields to set.\n * @returns The trigger's resolved addresses and config.\n */\n async setEmailTriggerConfig(\n agentId: string,\n triggerId: string,\n body: SetEmailTriggerConfigRequest,\n ): Promise<EmailTriggerConfigResponse> {\n return (await this.request(\"PUT\", `/agents/${agentId}/triggers/${triggerId}/email-config`, {\n json: body,\n })) as EmailTriggerConfigResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent Slack Triggers\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Configure an agent's `SLACK_COMMAND` trigger, which people run from Slack\n * with `/seclai` or the message shortcut.\n *\n * Sets the Slack connection, `alias` (the name people type after `/seclai`),\n * form, channels, reply visibility and conversation settings. Omitted fields\n * are left unchanged. `input` is deprecated and ignored by the API.\n *\n * @param agentId - Agent identifier.\n * @param triggerId - Trigger identifier.\n * @param body - The fields to set.\n * @returns The trigger's full Slack config, including any `missing_scopes`.\n */\n async setSlackTriggerConfig(\n agentId: string,\n triggerId: string,\n body: SetSlackTriggerConfigRequest,\n ): Promise<SlackTriggerConfigResponse> {\n return (await this.request(\"PUT\", `/agents/${agentId}/triggers/${triggerId}/slack-config`, {\n json: body,\n })) as SlackTriggerConfigResponse;\n }\n\n /**\n * Replace the input attachments a trigger accepts.\n *\n * A run's files are each assigned to one declared attachment before any step\n * runs, and steps reference one as `{{agent.attachments.<name>}}`. The API\n * answers 400 when the agent references an attachment the new declaration\n * leaves out.\n *\n * @param agentId - Agent identifier.\n * @param triggerId - Trigger identifier, as `getAgent()` returns it.\n * @param body - The full list of accepted attachments; a slot's `min` defaults to 0.\n * @returns The trigger's accepted attachments.\n */\n async setAcceptedAttachments(\n agentId: string,\n triggerId: string,\n body: SetAcceptedAttachmentsInput,\n ): Promise<AcceptedAttachmentsResponse> {\n return (await this.request(\"PUT\", `/agents/${agentId}/triggers/${triggerId}/accepted-attachments`, {\n json: body,\n })) as AcceptedAttachmentsResponse;\n }\n\n /**\n * Get the run metadata keys a trigger declares.\n *\n * Steps may reference a declared key as `{{metadata.<key>}}`. The response\n * also lists the system and source keys the trigger's type can declare.\n *\n * @param agentId - Agent identifier.\n * @param triggerId - Trigger identifier, as `getAgent()` returns it.\n * @returns The trigger's declared and declarable metadata keys.\n */\n async getMetadataKeys(agentId: string, triggerId: string): Promise<MetadataKeysResponse> {\n return (await this.request(\n \"GET\",\n `/agents/${agentId}/triggers/${triggerId}/metadata-keys`,\n )) as MetadataKeysResponse;\n }\n\n /**\n * Replace the run metadata keys a trigger declares.\n *\n * The body is the whole declaration and replaces the current one. The API\n * answers 400 when the agent references a key that no trigger of its branch\n * declares.\n *\n * @param agentId - Agent identifier.\n * @param triggerId - Trigger identifier, as `getAgent()` returns it.\n * @param body - The full declaration; each key's `required` defaults to `false`.\n * @returns The trigger's metadata keys, with `warnings` naming agents whose\n * `call_agent` mapping no longer fits.\n */\n async setMetadataKeys(\n agentId: string,\n triggerId: string,\n body: SetMetadataKeysRequest,\n ): Promise<MetadataKeysResponse> {\n return (await this.request(\"PUT\", `/agents/${agentId}/triggers/${triggerId}/metadata-keys`, {\n json: body,\n })) as MetadataKeysResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Agent Email Governance\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List recipients who have opted out of this account's agent emails.\n *\n * @param opts - Optional agent filter and `limit`/`offset` pagination.\n * @param opts.agentId - Filter to one agent (account-wide opt-outs still apply).\n * @param opts.limit - Page size (1-200, default 50).\n * @param opts.offset - Rows to skip (default 0).\n * @returns The page of opt-outs plus the total count.\n */\n async listAgentEmailOptOuts(\n opts: { agentId?: string; limit?: number; offset?: number } = {},\n ): Promise<AgentEmailOptOutListResponse> {\n return keyedList<AgentEmailOptOutListResponse>(\n await this.request(\"GET\", \"/agents/agent-email-optouts\", {\n query: { agent_id: opts.agentId, limit: opts.limit, offset: opts.offset },\n }),\n \"items\",\n [\"total\"],\n );\n }\n\n /**\n * Revoke an opt-out, opting the recipient back in to agent emails.\n *\n * @param optoutId - Opt-out identifier.\n */\n async removeAgentEmailOptOut(optoutId: string): Promise<void> {\n await this.request(\"DELETE\", `/agents/agent-email-optouts/${optoutId}`);\n }\n\n /**\n * List the account's blocked inbound email senders (newest first), plus the\n * governance `auto_block_mode`.\n *\n * @param opts - Optional `limit`/`offset` pagination.\n * @param opts.limit - Page size (1-200, default 50).\n * @param opts.offset - Rows to skip (default 0).\n */\n async listBlockedEmailSenders(\n opts: OffsetPageOptions = {},\n ): Promise<BlockedEmailSenderListResponse> {\n return keyedList<BlockedEmailSenderListResponse>(\n await this.request(\"GET\", \"/agents/blocked-email-senders\", {\n query: { limit: opts.limit, offset: opts.offset },\n }),\n \"items\",\n [\"total\"],\n );\n }\n\n /**\n * Add a sender address or a whole domain to the account blocklist.\n *\n * Idempotent. `match_type` is `\"address\"` (default) or `\"domain\"`.\n * Requires an account owner/admin.\n *\n * @param body - The sender or domain to block.\n * @returns The blocked-sender entry.\n */\n async blockEmailSender(body: BlockEmailSenderRequest): Promise<BlockedEmailSenderResponse> {\n return (await this.request(\"POST\", \"/agents/blocked-email-senders\", {\n json: body,\n })) as BlockedEmailSenderResponse;\n }\n\n /**\n * Remove a blocked sender by id. Requires an account owner/admin.\n *\n * @param blockedId - Blocked-sender identifier.\n */\n async unblockEmailSender(blockedId: string): Promise<void> {\n await this.request(\"DELETE\", `/agents/blocked-email-senders/${blockedId}`);\n }\n\n /**\n * Set whether a governance BLOCK on an authenticated inbound sender\n * auto-adds them to the blocklist.\n *\n * `mode` is `\"disabled\"`, `\"input\"`, or `\"input_and_output\"`.\n * Requires an account owner/admin.\n *\n * @param body - The mode to set.\n * @returns The updated blocked-sender list.\n */\n async setAutoBlockMode(body: SetAutoBlockModeRequest): Promise<BlockedEmailSenderListResponse> {\n return keyedList<BlockedEmailSenderListResponse>(\n await this.request(\"PUT\", \"/agents/blocked-email-senders/mode\", { json: body }),\n \"items\",\n [\"total\"],\n );\n }\n\n /**\n * List recent inbound emails that were quietly discarded before running an\n * agent (unauthorized sender, unknown alias, spam/virus, flood-shed).\n *\n * @param opts - Optional agent filter and result limit.\n * @param opts.agentId - Filter to a single agent's rejections.\n * @param opts.limit - Maximum results (1-200, default 50).\n */\n async listInboundEmailRejections(\n opts: { agentId?: string; limit?: number } = {},\n ): Promise<InboundEmailRejectionResponse[]> {\n return listItems<InboundEmailRejectionResponse>(\n await this.request(\"GET\", \"/agents/inbound-email-rejections\", {\n query: { agent_id: opts.agentId, limit: opts.limit },\n }),\n );\n }\n\n /**\n * Get the account's inbound-email overload status — whether the circuit\n * breaker has paused new inbound email, and the size of the QUEUED\n * (over-quota parked) run backlog.\n */\n async getInboundEmailStatus(): Promise<InboundEmailStatusResponse> {\n return (await this.request(\"GET\", \"/agents/inbound-email-status\")) as InboundEmailStatusResponse;\n }\n\n /**\n * Cancel all of the account's QUEUED (over-quota parked) inbound-email runs\n * at once.\n *\n * A queued run consumed no quota or credits at queue time. Each ends\n * `cancelled`, or `failed` with an `apiVersion` before `2026-11-08`.\n * Requires an account owner/admin.\n *\n * @returns The count cancelled.\n */\n async cancelQueuedEmailRuns(): Promise<CancelQueuedRunsResponse> {\n return (await this.request(\"POST\", \"/agents/inbound-email-status/cancel-queued\")) as CancelQueuedRunsResponse;\n }\n\n /**\n * Manually lift the account-wide inbound-email pause.\n *\n * If the queued backlog is still above the ceiling the breaker re-arms on the\n * next evaluation — this is a one-shot override, not a permanent disable.\n * Requires an account owner/admin.\n */\n async resumeInboundEmail(): Promise<ResumeInboundResponse> {\n return (await this.request(\"POST\", \"/agents/inbound-email-status/resume\")) as ResumeInboundResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Knowledge Bases\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List knowledge bases.\n *\n * @param opts - Pagination and sorting options.\n * @returns Paginated list of knowledge bases.\n */\n async listKnowledgeBases(opts: SortableListOptions = {}): Promise<KnowledgeBaseListResponse> {\n return keyedList<KnowledgeBaseListResponse>(\n await this.request(\"GET\", \"/knowledge_bases\", {\n query: { page: opts.page, limit: opts.limit, sort: opts.sort, order: opts.order },\n }),\n \"knowledge_bases\",\n PAGE_COUNTERS,\n );\n }\n\n /**\n * Create a new knowledge base.\n *\n * @param body - Knowledge base configuration.\n * @returns The created knowledge base.\n */\n async createKnowledgeBase(body: CreateKnowledgeBaseBody): Promise<KnowledgeBaseResponse> {\n return (await this.request(\"POST\", \"/knowledge_bases\", { json: body })) as KnowledgeBaseResponse;\n }\n\n /**\n * Get a knowledge base by ID.\n *\n * @param knowledgeBaseId - Knowledge base identifier.\n * @returns Knowledge base details.\n */\n async getKnowledgeBase(knowledgeBaseId: string): Promise<KnowledgeBaseResponse> {\n return (await this.request(\"GET\", `/knowledge_bases/${knowledgeBaseId}`)) as KnowledgeBaseResponse;\n }\n\n /**\n * Get the item-metadata keys seen in a knowledge base's content.\n *\n * Reports, for all time and the last 30 and 7 days, each key's item count,\n * number of distinct values and five most frequent values.\n *\n * @param knowledgeBaseId - Knowledge base identifier.\n * @returns The key statistics per window.\n */\n async getKnowledgeBaseMetadataKeyStats(knowledgeBaseId: string): Promise<KnowledgeBaseMetadataKeyStatsResponse> {\n return (await this.request(\n \"GET\",\n `/knowledge_bases/${knowledgeBaseId}/metadata-key-stats`,\n )) as KnowledgeBaseMetadataKeyStatsResponse;\n }\n\n /**\n * Update a knowledge base.\n *\n * @param knowledgeBaseId - Knowledge base identifier.\n * @param body - Fields to update.\n * @returns Updated knowledge base.\n */\n async updateKnowledgeBase(knowledgeBaseId: string, body: UpdateKnowledgeBaseBody): Promise<KnowledgeBaseResponse> {\n return (await this.request(\"PUT\", `/knowledge_bases/${knowledgeBaseId}`, { json: body })) as KnowledgeBaseResponse;\n }\n\n /**\n * Delete a knowledge base.\n *\n * @param knowledgeBaseId - Knowledge base identifier.\n */\n async deleteKnowledgeBase(knowledgeBaseId: string): Promise<void> {\n await this.request(\"DELETE\", `/knowledge_bases/${knowledgeBaseId}`);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Memory Banks\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List memory banks.\n *\n * @param opts - Pagination, sorting and a `type` filter.\n * @returns Paginated list of memory banks.\n */\n async listMemoryBanks(opts: ListMemoryBanksOptions = {}): Promise<MemoryBankListResponse> {\n return keyedList<MemoryBankListResponse>(\n await this.request(\"GET\", \"/memory_banks\", {\n query: { page: opts.page, limit: opts.limit, sort: opts.sort, order: opts.order, type: opts.type },\n }),\n \"memory_banks\",\n PAGE_COUNTERS,\n );\n }\n\n /**\n * Create a new memory bank.\n *\n * Memory banks give agents persistent memory across conversations.\n * Types: `conversation` (chat-style history) or `general` (flat factual entries).\n *\n * @param body - Memory bank configuration.\n * @returns The created memory bank.\n */\n async createMemoryBank(body: CreateMemoryBankBody): Promise<MemoryBankResponse> {\n return (await this.request(\"POST\", \"/memory_banks\", { json: body })) as MemoryBankResponse;\n }\n\n /**\n * Get a memory bank by ID.\n *\n * @param memoryBankId - Memory bank identifier.\n * @returns Memory bank details.\n */\n async getMemoryBank(memoryBankId: string): Promise<MemoryBankResponse> {\n return (await this.request(\"GET\", `/memory_banks/${memoryBankId}`)) as MemoryBankResponse;\n }\n\n /**\n * Update a memory bank.\n *\n * @param memoryBankId - Memory bank identifier.\n * @param body - Fields to update.\n * @returns Updated memory bank.\n */\n async updateMemoryBank(memoryBankId: string, body: UpdateMemoryBankBody): Promise<MemoryBankResponse> {\n return (await this.request(\"PUT\", `/memory_banks/${memoryBankId}`, { json: body })) as MemoryBankResponse;\n }\n\n /**\n * Delete a memory bank.\n *\n * @param memoryBankId - Memory bank identifier.\n */\n async deleteMemoryBank(memoryBankId: string): Promise<void> {\n await this.request(\"DELETE\", `/memory_banks/${memoryBankId}`);\n }\n\n /**\n * Get agents that are using a specific memory bank.\n *\n * @param memoryBankId - Memory bank identifier.\n */\n async getAgentsUsingMemoryBank(memoryBankId: string): Promise<unknown> {\n return listItems<unknown>(await this.request(\"GET\", `/memory_banks/${memoryBankId}/agents`));\n }\n\n /**\n * Get stats for a memory bank.\n *\n * @param memoryBankId - Memory bank identifier.\n * @param opts - Date range. Only `startDate` and `endDate` together replace\n * `days`; either one alone is ignored and the last `days` days apply (server default 30).\n */\n async getMemoryBankStats(memoryBankId: string, opts: DateRangeOptions = {}): Promise<unknown> {\n return await this.request(\"GET\", `/memory_banks/${memoryBankId}/stats`, {\n query: { days: opts.days, start_date: opts.startDate, end_date: opts.endDate },\n });\n }\n\n /**\n * Compact a memory bank (trigger compaction).\n *\n * @param memoryBankId - Memory bank identifier.\n */\n async compactMemoryBank(memoryBankId: string): Promise<void> {\n await this.request(\"POST\", `/memory_banks/${memoryBankId}/compact`);\n }\n\n /**\n * Delete a memory bank source.\n *\n * @param memoryBankId - Memory bank identifier.\n */\n async deleteMemoryBankSource(memoryBankId: string): Promise<void> {\n await this.request(\"DELETE\", `/memory_banks/${memoryBankId}/source`);\n }\n\n /**\n * Test compaction for a specific memory bank.\n *\n * @param memoryBankId - Memory bank identifier.\n * @param body - Test compaction request.\n */\n async testMemoryBankCompaction(memoryBankId: string, body: TestCompactionRequest): Promise<CompactionTestResponse> {\n return (await this.request(\"POST\", `/memory_banks/${memoryBankId}/test-compaction`, { json: body })) as CompactionTestResponse;\n }\n\n /**\n * Test compaction prompt standalone (not tied to a specific memory bank).\n *\n * @param body - Standalone compaction test request.\n */\n async testCompactionPromptStandalone(body: StandaloneTestCompactionRequest): Promise<CompactionTestResponse> {\n return (await this.request(\"POST\", \"/memory_banks/test-compaction\", { json: body })) as CompactionTestResponse;\n }\n\n /**\n * List available memory bank templates.\n */\n async listMemoryBankTemplates(): Promise<unknown> {\n return listItems<unknown>(await this.request(\"GET\", \"/memory_banks/templates\"));\n }\n\n // ─── Memory Bank AI Assistant ──────────────────────────────────────────────\n\n /**\n * Generate memory bank configuration using AI.\n *\n * @param body - AI assistant request with user instructions.\n * @returns AI-generated memory bank config.\n */\n async generateMemoryBankConfig(body: MemoryBankAiAssistantRequest): Promise<MemoryBankAiAssistantResponse> {\n return (await this.request(\"POST\", \"/memory_banks/ai-assistant\", { json: body })) as MemoryBankAiAssistantResponse;\n }\n\n /**\n * Get the last AI conversation for memory banks.\n *\n * @param opts - Turns to return (server default 5) and most-recent turns to skip (default 0).\n */\n async getMemoryBankAiLastConversation(opts: OffsetPageOptions = {}): Promise<MemoryBankLastConversationResponse> {\n return (await this.request(\"GET\", \"/memory_banks/ai-assistant/last-conversation\", {\n query: { limit: opts.limit, offset: opts.offset },\n })) as MemoryBankLastConversationResponse;\n }\n\n /**\n * Accept a memory bank AI suggestion.\n *\n * @param conversationId - Conversation identifier.\n * @param body - Accept request payload.\n */\n async acceptMemoryBankAiSuggestion(conversationId: string, body: MemoryBankAcceptRequest): Promise<OkResponse> {\n return (await this.request(\"PATCH\", `/memory_banks/ai-assistant/${conversationId}`, { json: body })) as OkResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Sources\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List sources.\n *\n * @param opts - Pagination, sorting, and filter options.\n * @returns Paginated list of sources.\n */\n async listSources(\n opts: SortableListOptions & { accountId?: string } = {},\n ): Promise<SourceListResponse> {\n return (await this.request(\"GET\", \"/sources\", {\n query: {\n page: opts.page,\n limit: opts.limit,\n sort: opts.sort,\n order: opts.order,\n account_id: opts.accountId,\n },\n })) as SourceListResponse;\n }\n\n /**\n * Create a new content source.\n *\n * @param body - Source configuration (type, name, knowledge base link, etc.).\n * @returns The created source.\n */\n async createSource(body: CreateSourceBody): Promise<SourceResponse> {\n return (await this.request(\"POST\", \"/sources\", { json: body })) as SourceResponse;\n }\n\n /**\n * Get a source by ID.\n *\n * @param sourceId - Source connection identifier.\n * @returns Source details.\n */\n async getSource(sourceId: string): Promise<SourceResponse> {\n return (await this.request(\"GET\", `/sources/${sourceId}`)) as SourceResponse;\n }\n\n /**\n * Update a source.\n *\n * @param sourceId - Source connection identifier.\n * @param body - Fields to update.\n * @returns Updated source.\n */\n async updateSource(sourceId: string, body: UpdateSourceBody): Promise<SourceResponse> {\n return (await this.request(\"PUT\", `/sources/${sourceId}`, { json: body })) as SourceResponse;\n }\n\n /**\n * Delete a source.\n *\n * @param sourceId - Source connection identifier.\n */\n async deleteSource(sourceId: string): Promise<void> {\n await this.request(\"DELETE\", `/sources/${sourceId}`);\n }\n\n /**\n * Upload a file to a source.\n *\n * Maximum file size: 200 MiB. Supports text, PDF, DOCX, audio, video, images, and more.\n * If `mimeType` is omitted, it will be inferred from the `fileName` extension when possible.\n *\n * @param sourceId - Source connection identifier.\n * @param opts - File payload and optional metadata.\n * @returns Upload response details.\n */\n async uploadFileToSource(\n sourceId: string,\n opts: {\n file: Blob | Uint8Array | ArrayBuffer | BufferSource;\n title?: string;\n metadata?: Record<string, unknown>;\n fileName?: string;\n mimeType?: string;\n },\n ): Promise<FileUploadResponse> {\n return (await this.uploadFile(`/sources/${sourceId}/upload`, opts)) as FileUploadResponse;\n }\n\n /**\n * Upload inline text to a source.\n *\n * @param sourceId - Source connection identifier.\n * @param body - Inline text upload payload.\n * @returns Upload response.\n */\n async uploadInlineTextToSource(sourceId: string, body: InlineTextUploadRequest): Promise<FileUploadResponse> {\n return (await this.request(\"POST\", `/sources/${sourceId}`, { json: body })) as FileUploadResponse;\n }\n\n /**\n * List a source's content items and their indexing status.\n *\n * @param sourceId - Source connection identifier.\n * @param opts - Pagination, sorting, and filters. Pass the `content_version_id`\n * values the upload methods return as `contentVersionIds` to poll a batch of\n * uploads in one request — about 100 at a time, since the ids travel in the\n * query string and a URL over 8,192 bytes is rejected with a 414. An empty\n * `contentVersionIds` matches nothing, so it returns an empty page without\n * sending a request.\n * @returns The items under `data` with `pagination`, on every API version.\n */\n async listSourceContents(\n sourceId: string,\n opts: ListSourceContentsOptions = {},\n ): Promise<SourceContentStatusListResponse> {\n if (opts.contentVersionIds?.length === 0) {\n return {\n data: [],\n pagination: {\n page: opts.page ?? 1,\n limit: opts.limit ?? 20,\n total: 0,\n pages: 0,\n has_next: false,\n has_prev: false,\n },\n };\n }\n return (await this.request(\"GET\", `/sources/${sourceId}/contents`, {\n query: {\n page: opts.page,\n limit: opts.limit,\n sort: opts.sort,\n order: opts.order,\n status: opts.status,\n content_version_id: opts.contentVersionIds,\n },\n })) as SourceContentStatusListResponse;\n }\n\n /**\n * Get one content item's indexing status.\n *\n * @param sourceId - Source connection identifier.\n * @param contentVersionId - The `content_version_id` an upload returned.\n */\n async getSourceContentStatus(sourceId: string, contentVersionId: string): Promise<SourceContentStatusResponse> {\n return (await this.request(\n \"GET\",\n `/sources/${sourceId}/contents/${contentVersionId}`,\n )) as SourceContentStatusResponse;\n }\n\n /**\n * List mail an email content source refused, newest first.\n *\n * Each entry says who sent the message and why it was refused, never its\n * subject or body. To accept a refused sender, add its `from_address` or that\n * address's domain to the source's `email_allowed_senders` — which only helps\n * when `authenticated` is true. Requires an account owner or administrator;\n * the API answers 404 for a source that is not an email source.\n *\n * @param sourceId - Source connection identifier.\n * @param opts - Pagination options (`limit` 1-100).\n * @returns The rejections under `data` with `pagination`.\n */\n async listEmailSourceRejections(\n sourceId: string,\n opts: ListOptions = {},\n ): Promise<EmailSourceRejectionListResponse> {\n return (await this.request(\"GET\", `/sources/${sourceId}/email-rejections`, {\n query: { page: opts.page, limit: opts.limit },\n })) as EmailSourceRejectionListResponse;\n }\n\n // ─── Source Exports ────────────────────────────────────────────────────────\n\n /**\n * List exports for a source.\n *\n * @param sourceId - Source connection identifier.\n * @param opts - Pagination options.\n * @returns Paginated list of exports.\n */\n async listSourceExports(sourceId: string, opts: ListOptions = {}): Promise<ExportListResponse> {\n return (await this.request(\"GET\", `/sources/${sourceId}/exports`, {\n query: { page: opts.page, limit: opts.limit },\n })) as ExportListResponse;\n }\n\n /**\n * Create a source data export.\n *\n * @param sourceId - Source connection identifier.\n * @param body - Export configuration (format, etc.).\n * @returns Export response with job status.\n */\n async createSourceExport(sourceId: string, body: CreateExportRequest): Promise<ExportResponse> {\n return (await this.request(\"POST\", `/sources/${sourceId}/exports`, { json: body })) as ExportResponse;\n }\n\n /**\n * Get a specific source export.\n *\n * @param sourceId - Source connection identifier.\n * @param exportId - Export identifier.\n * @returns Export details.\n */\n async getSourceExport(sourceId: string, exportId: string): Promise<ExportResponse> {\n return (await this.request(\"GET\", `/sources/${sourceId}/exports/${exportId}`)) as ExportResponse;\n }\n\n /**\n * Cancel a source export.\n *\n * @param sourceId - Source connection identifier.\n * @param exportId - Export identifier.\n */\n async cancelSourceExport(sourceId: string, exportId: string): Promise<ExportResponse> {\n return (await this.request(\"POST\", `/sources/${sourceId}/exports/${exportId}/cancel`)) as ExportResponse;\n }\n\n /**\n * Download a source export file.\n *\n * Returns the raw `Response` so you can stream or save the binary data.\n *\n * @param sourceId - Source connection identifier.\n * @param exportId - Export identifier.\n * @param opts - Optional `signal`, which cancels the request; with a standard `fetch` this\n * includes reading the body, so `AbortSignal.timeout(ms)` bounds the whole\n * transfer.\n * @returns Raw response with the export file.\n */\n async downloadSourceExport(\n sourceId: string,\n exportId: string,\n opts: { signal?: AbortSignal } = {},\n ): Promise<Response> {\n return await this.requestRaw(\"GET\", `/sources/${sourceId}/exports/${exportId}/download`, {\n signal: opts.signal,\n });\n }\n\n /**\n * Estimate a source export.\n *\n * @param sourceId - Source connection identifier.\n * @param body - Estimate request.\n * @returns Export estimate.\n */\n async estimateSourceExport(sourceId: string, body: EstimateExportRequest): Promise<EstimateExportResponse> {\n return (await this.request(\"POST\", `/sources/${sourceId}/exports/estimate`, { json: body })) as EstimateExportResponse;\n }\n\n /**\n * Delete a source export.\n *\n * @param sourceId - Source connection identifier.\n * @param exportId - Export identifier.\n */\n async deleteSourceExport(sourceId: string, exportId: string): Promise<void> {\n await this.request(\"DELETE\", `/sources/${sourceId}/exports/${exportId}`);\n }\n\n // ─── Source Embedding Migrations ───────────────────────────────────────────\n\n /**\n * Get the status of a source embedding migration.\n *\n * @param sourceId - Source connection identifier.\n * @returns Migration status.\n */\n async getSourceEmbeddingMigration(sourceId: string): Promise<SourceEmbeddingMigrationResponse> {\n return (await this.request(\"GET\", `/sources/${sourceId}/embedding-migration`)) as SourceEmbeddingMigrationResponse;\n }\n\n /**\n * Start a source embedding migration.\n *\n * @param sourceId - Source connection identifier.\n * @param body - Migration configuration (target embedding model, etc.).\n * @returns Migration status.\n */\n async startSourceEmbeddingMigration(sourceId: string, body: StartSourceEmbeddingMigrationRequest): Promise<SourceEmbeddingMigrationResponse> {\n return (await this.request(\"POST\", `/sources/${sourceId}/embedding-migration`, { json: body })) as SourceEmbeddingMigrationResponse;\n }\n\n /**\n * Cancel a source embedding migration.\n *\n * @param sourceId - Source connection identifier.\n * @returns Updated migration status.\n */\n async cancelSourceEmbeddingMigration(sourceId: string): Promise<SourceEmbeddingMigrationResponse> {\n return (await this.request(\"POST\", `/sources/${sourceId}/embedding-migration/cancel`)) as SourceEmbeddingMigrationResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Content\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Get content detail for a specific content version.\n *\n * @param contentVersionId - Content version identifier.\n * @param opts - Range options for slicing large content.\n * @returns Content details for the requested range.\n */\n async getContentDetail(\n contentVersionId: string,\n opts: { start?: number; end?: number } = {},\n ): Promise<ContentDetailResponse> {\n return (await this.request(\"GET\", `/contents/${contentVersionId}`, {\n query: { start: opts.start ?? 0, end: opts.end ?? 5000 },\n })) as ContentDetailResponse;\n }\n\n /**\n * Replace content with inline text.\n *\n * @param contentVersionId - Content version identifier.\n * @param body - Inline text replacement payload.\n */\n async replaceContentWithInlineText(contentVersionId: string, body: InlineTextReplaceRequest): Promise<ContentFileUploadResponse> {\n return (await this.request(\"PUT\", `/contents/${contentVersionId}`, { json: body })) as ContentFileUploadResponse;\n }\n\n /**\n * Delete a specific content version.\n *\n * @param contentVersionId - Content version identifier.\n */\n async deleteContent(contentVersionId: string): Promise<void> {\n await this.request(\"DELETE\", `/contents/${contentVersionId}`);\n }\n\n /**\n * List embeddings for a content version.\n *\n * @param contentVersionId - Content version identifier.\n * @param opts - Pagination options.\n * @returns Paginated list of embeddings.\n */\n async listContentEmbeddings(\n contentVersionId: string,\n opts: ListOptions = {},\n ): Promise<ContentEmbeddingsListResponse> {\n return (await this.request(\"GET\", `/contents/${contentVersionId}/embeddings`, {\n query: { page: opts.page ?? 1, limit: opts.limit ?? 20 },\n })) as ContentEmbeddingsListResponse;\n }\n\n /**\n * List the files attached to a content item.\n *\n * Files arrive from an agent's `write_content_attachment` step, with an email\n * message, from an RSS feed's `feed_attachments`, from a web page's media, or\n * as the images inside a document. Each entry says whether it is indexed for\n * search and, when indexing failed, why.\n *\n * @param contentVersionId - Content version identifier.\n * @param opts - Pagination options.\n * @returns The attachments under `data` with `pagination`.\n */\n async listContentAttachments(\n contentVersionId: string,\n opts: ListOptions = {},\n ): Promise<ContentAttachmentsListResponse> {\n return (await this.request(\"GET\", `/contents/${contentVersionId}/attachments`, {\n query: { page: opts.page, limit: opts.limit },\n })) as ContentAttachmentsListResponse;\n }\n\n /**\n * Get one file attached to a content item: its indexing status and reason,\n * its metadata, and the text it is indexed by.\n *\n * @param contentVersionId - Content version identifier.\n * @param attachmentId - The `id` of an entry from {@link listContentAttachments}.\n * @param opts - `start` and `end` character offsets for paging through long text\n * (server defaults 0 and 5000). Both are sent as given, so `end: 0` asks for\n * the metadata without any text. A file that was not indexed has no text.\n * @returns The attachment with the requested range of its text.\n * @throws {SeclaiAPIStatusError} 402 when the account has no credits left\n * (`error.code` `insufficient_credits`).\n */\n async getContentAttachment(\n contentVersionId: string,\n attachmentId: string,\n opts: { start?: number; end?: number } = {},\n ): Promise<ContentAttachmentDetailResponse> {\n return (await this.request(\"GET\", `/contents/${contentVersionId}/attachments/${attachmentId}`, {\n query: { start: opts.start, end: opts.end },\n })) as ContentAttachmentDetailResponse;\n }\n\n /**\n * List the embeddings (chunk vectors) a content attachment is indexed by.\n * The list is empty for a file that has no completed index.\n *\n * @param contentVersionId - Content version identifier.\n * @param attachmentId - Attachment identifier.\n * @param opts - Pagination options (`limit` 1-100).\n * @returns Paginated list of embeddings.\n * @throws {SeclaiAPIStatusError} 402 when the account has no credits left\n * (`error.code` `insufficient_credits`).\n */\n async listContentAttachmentEmbeddings(\n contentVersionId: string,\n attachmentId: string,\n opts: ListOptions = {},\n ): Promise<ContentEmbeddingsListResponse> {\n return (await this.request(\"GET\", `/contents/${contentVersionId}/attachments/${attachmentId}/embeddings`, {\n query: { page: opts.page, limit: opts.limit },\n })) as ContentEmbeddingsListResponse;\n }\n\n /**\n * Download a content attachment's bytes.\n *\n * Returns the raw `Response` so you can stream or save the binary data. The\n * API answers 403 when the file is withheld — blocked or redacted by a\n * governance policy, or still being indexed after arriving from outside; the\n * attachment's `file_withheld` field says which before you ask.\n *\n * @param contentVersionId - Content version identifier.\n * @param attachmentId - Attachment identifier.\n * @param opts - Optional `signal`, which cancels the request; with a standard `fetch` this\n * includes reading the body, so `AbortSignal.timeout(ms)` bounds the whole\n * transfer.\n * @returns Raw response with the attachment bytes.\n * @throws {SeclaiAPIStatusError} 403 when the file is withheld, and 402 when\n * the account has no credits left (`error.code` `insufficient_credits`).\n */\n async downloadContentAttachment(\n contentVersionId: string,\n attachmentId: string,\n opts: { signal?: AbortSignal } = {},\n ): Promise<Response> {\n return await this.requestRaw(\"GET\", `/contents/${contentVersionId}/attachments/${attachmentId}/file`, {\n signal: opts.signal,\n });\n }\n\n /**\n * Upload a file to replace content for an existing content version.\n *\n * @param contentVersionId - Content version identifier.\n * @param opts - File payload and optional metadata.\n * @returns Upload response.\n */\n async uploadFileToContent(\n contentVersionId: string,\n opts: {\n file: Blob | Uint8Array | ArrayBuffer | BufferSource;\n title?: string;\n metadata?: Record<string, unknown>;\n fileName?: string;\n mimeType?: string;\n },\n ): Promise<ContentFileUploadResponse> {\n return (await this.uploadFile(`/contents/${contentVersionId}/upload`, opts)) as ContentFileUploadResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Solutions\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List solutions.\n *\n * @param opts - Pagination, sorting and a name `search`.\n * @returns Paginated list of solutions.\n */\n async listSolutions(opts: ListSolutionsOptions = {}): Promise<SolutionListResponse> {\n return (await this.request(\"GET\", \"/solutions\", {\n query: { page: opts.page, limit: opts.limit, sort: opts.sort, order: opts.order, search: opts.search },\n })) as SolutionListResponse;\n }\n\n /**\n * Create a new solution.\n *\n * @param body - Solution configuration.\n * @returns The created solution.\n */\n async createSolution(body: CreateSolutionRequest): Promise<SolutionResponse> {\n return (await this.request(\"POST\", \"/solutions\", { json: body })) as SolutionResponse;\n }\n\n /**\n * Get a solution by ID.\n *\n * @param solutionId - Solution identifier.\n * @returns Solution details.\n */\n async getSolution(solutionId: string): Promise<SolutionResponse> {\n return (await this.request(\"GET\", `/solutions/${solutionId}`)) as SolutionResponse;\n }\n\n /**\n * Update a solution.\n *\n * @param solutionId - Solution identifier.\n * @param body - Fields to update.\n * @returns Updated solution.\n */\n async updateSolution(solutionId: string, body: UpdateSolutionRequest): Promise<SolutionResponse> {\n return (await this.request(\"PATCH\", `/solutions/${solutionId}`, { json: body })) as SolutionResponse;\n }\n\n /**\n * Delete a solution.\n *\n * @param solutionId - Solution identifier.\n */\n async deleteSolution(solutionId: string): Promise<void> {\n await this.request(\"DELETE\", `/solutions/${solutionId}`);\n }\n\n // ─── Solution Resource Linking ─────────────────────────────────────────────\n\n /**\n * Link agents to a solution.\n *\n * @param solutionId - Solution identifier.\n * @param body - Resource IDs to link.\n * @returns Updated solution.\n */\n async linkAgentsToSolution(solutionId: string, body: LinkResourcesRequest): Promise<SolutionResponse> {\n return (await this.request(\"POST\", `/solutions/${solutionId}/agents`, { json: body })) as SolutionResponse;\n }\n\n /**\n * Unlink agents from a solution.\n *\n * @param solutionId - Solution identifier.\n * @param body - Resource IDs to unlink.\n * @returns Updated solution.\n */\n async unlinkAgentsFromSolution(solutionId: string, body: UnlinkResourcesRequest): Promise<SolutionResponse> {\n return (await this.request(\"DELETE\", `/solutions/${solutionId}/agents`, { json: body })) as SolutionResponse;\n }\n\n /**\n * Link knowledge bases to a solution.\n *\n * @param solutionId - Solution identifier.\n * @param body - Resource IDs to link.\n * @returns Updated solution.\n */\n async linkKnowledgeBasesToSolution(solutionId: string, body: LinkResourcesRequest): Promise<SolutionResponse> {\n return (await this.request(\"POST\", `/solutions/${solutionId}/knowledge-bases`, { json: body })) as SolutionResponse;\n }\n\n /**\n * Unlink knowledge bases from a solution.\n *\n * @param solutionId - Solution identifier.\n * @param body - Resource IDs to unlink.\n * @returns Updated solution.\n */\n async unlinkKnowledgeBasesFromSolution(solutionId: string, body: UnlinkResourcesRequest): Promise<SolutionResponse> {\n return (await this.request(\"DELETE\", `/solutions/${solutionId}/knowledge-bases`, { json: body })) as SolutionResponse;\n }\n\n /**\n * Link source connections to a solution.\n *\n * @param solutionId - Solution identifier.\n * @param body - Resource IDs to link.\n * @returns Updated solution.\n */\n async linkSourceConnectionsToSolution(solutionId: string, body: LinkResourcesRequest): Promise<SolutionResponse> {\n return (await this.request(\"POST\", `/solutions/${solutionId}/source-connections`, { json: body })) as SolutionResponse;\n }\n\n /**\n * Unlink source connections from a solution.\n *\n * @param solutionId - Solution identifier.\n * @param body - Resource IDs to unlink.\n * @returns Updated solution.\n */\n async unlinkSourceConnectionsFromSolution(solutionId: string, body: UnlinkResourcesRequest): Promise<SolutionResponse> {\n return (await this.request(\"DELETE\", `/solutions/${solutionId}/source-connections`, { json: body })) as SolutionResponse;\n }\n\n // ─── Solution Conversations ────────────────────────────────────────────────\n\n /**\n * List conversations for a solution.\n *\n * @param solutionId - Solution identifier.\n * @returns List of conversations.\n */\n async listSolutionConversations(solutionId: string): Promise<SolutionConversationResponse[]> {\n return listItems<SolutionConversationResponse>(\n await this.request(\"GET\", `/solutions/${solutionId}/conversations`),\n );\n }\n\n /**\n * Add a conversation turn to a solution.\n *\n * @param solutionId - Solution identifier.\n * @param body - Conversation turn payload.\n * @returns Updated conversation.\n */\n async addSolutionConversationTurn(solutionId: string, body: AddConversationTurnRequest): Promise<SolutionConversationResponse> {\n return (await this.request(\"POST\", `/solutions/${solutionId}/conversations`, { json: body })) as SolutionConversationResponse;\n }\n\n /**\n * Mark a conversation turn (e.g. accepted/rejected).\n *\n * @param solutionId - Solution identifier.\n * @param conversationId - Conversation identifier.\n * @param body - Mark payload.\n */\n async markSolutionConversationTurn(solutionId: string, conversationId: string, body: MarkConversationTurnRequest): Promise<void> {\n await this.request(\"PATCH\", `/solutions/${solutionId}/conversations/${conversationId}`, { json: body });\n }\n\n // ─── Solution AI Assistant ─────────────────────────────────────────────────\n\n /**\n * Generate a solution AI plan.\n *\n * @param solutionId - Solution identifier.\n * @param body - Generation request.\n * @returns AI-generated plan.\n */\n async generateSolutionAiPlan(solutionId: string, body: AiAssistantGenerateRequest): Promise<AiAssistantGenerateResponse> {\n return (await this.request(\"POST\", `/solutions/${solutionId}/ai-assistant/generate`, { json: body })) as AiAssistantGenerateResponse;\n }\n\n /**\n * Generate a knowledge base configuration via solution AI.\n *\n * @param solutionId - Solution identifier.\n * @param body - Generation request.\n * @returns AI-generated knowledge base config.\n */\n async generateSolutionAiKnowledgeBase(solutionId: string, body: AiAssistantGenerateRequest): Promise<AiAssistantGenerateResponse> {\n return (await this.request(\"POST\", `/solutions/${solutionId}/ai-assistant/knowledge-base`, { json: body })) as AiAssistantGenerateResponse;\n }\n\n /**\n * Generate a source configuration via solution AI.\n *\n * @param solutionId - Solution identifier.\n * @param body - Generation request.\n * @returns AI-generated source config.\n */\n async generateSolutionAiSource(solutionId: string, body: AiAssistantGenerateRequest): Promise<AiAssistantGenerateResponse> {\n return (await this.request(\"POST\", `/solutions/${solutionId}/ai-assistant/source`, { json: body })) as AiAssistantGenerateResponse;\n }\n\n /**\n * Accept a solution AI plan.\n *\n * @param solutionId - Solution identifier.\n * @param conversationId - Conversation identifier.\n * @param body - Accept request.\n * @returns Acceptance result with executed actions.\n */\n async acceptSolutionAiPlan(solutionId: string, conversationId: string, body: AiAssistantAcceptRequest): Promise<AiAssistantAcceptResponse> {\n return (await this.request(\"POST\", `/solutions/${solutionId}/ai-assistant/${conversationId}/accept`, { json: body })) as AiAssistantAcceptResponse;\n }\n\n /**\n * Decline a solution AI plan.\n *\n * @param solutionId - Solution identifier.\n * @param conversationId - Conversation identifier.\n */\n async declineSolutionAiPlan(solutionId: string, conversationId: string): Promise<void> {\n await this.request(\"POST\", `/solutions/${solutionId}/ai-assistant/${conversationId}/decline`);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Governance — AI Assistant\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Generate governance policy suggestions using AI.\n *\n * @param body - AI governance request.\n * @returns AI-generated governance suggestions.\n */\n async generateGovernanceAiPlan(body: GovernanceAiAssistantRequest): Promise<GovernanceAiAssistantResponse> {\n return (await this.request(\"POST\", \"/governance/ai-assistant\", { json: body })) as GovernanceAiAssistantResponse;\n }\n\n /**\n * List governance AI conversations.\n *\n * @param opts - `limit`: how many conversations (the server defaults to 20).\n */\n async listGovernanceAiConversations(opts: { limit?: number } = {}): Promise<GovernanceConversationResponse[]> {\n return listItems<GovernanceConversationResponse>(\n await this.request(\"GET\", \"/governance/ai-assistant/conversations\", { query: { limit: opts.limit } }),\n );\n }\n\n /**\n * Accept a governance AI plan.\n *\n * @param conversationId - Conversation identifier.\n * @returns Acceptance result.\n */\n async acceptGovernanceAiPlan(conversationId: string): Promise<GovernanceAiAcceptResponse> {\n return (await this.request(\"POST\", `/governance/ai-assistant/${conversationId}/accept`)) as GovernanceAiAcceptResponse;\n }\n\n /**\n * Decline a governance AI plan.\n *\n * @param conversationId - Conversation identifier.\n */\n async declineGovernanceAiPlan(conversationId: string): Promise<void> {\n await this.request(\"POST\", `/governance/ai-assistant/${conversationId}/decline`);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Alerts\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List alerts.\n *\n * @param opts - Pagination and filter options.\n * @returns Paginated list of alerts.\n */\n async listAlerts(opts: ListAlertsOptions = {}): Promise<AlertListResponse> {\n // `severity` is deliberately not forwarded: GET /alerts declares no such\n // filter, so it never filtered anything, and sending it is a 422 once\n // `apiVersion` is 2026-07-27 or later. Accepted and dropped so existing\n // call sites keep working.\n return (await this.request(\"GET\", \"/alerts\", {\n query: {\n page: opts.page,\n limit: opts.limit,\n status: opts.status,\n agent_id: opts.agentId,\n source_connection_id: opts.sourceConnectionId,\n time_from: opts.timeFrom,\n time_to: opts.timeTo,\n },\n })) as AlertListResponse;\n }\n\n /**\n * Get alert details by ID.\n *\n * @param alertId - Alert identifier.\n * @returns Alert details.\n */\n async getAlert(alertId: string): Promise<AlertDetailResponse> {\n return (await this.request(\"GET\", `/alerts/${alertId}`)) as AlertDetailResponse;\n }\n\n /**\n * Change the status of an alert.\n *\n * @param alertId - Alert identifier.\n * @param body - Status change request.\n */\n async changeAlertStatus(alertId: string, body: ChangeStatusRequest): Promise<AlertDetailResponse> {\n return (await this.request(\"POST\", `/alerts/${alertId}/status`, { json: body })) as AlertDetailResponse;\n }\n\n /**\n * Add a comment to an alert.\n *\n * @param alertId - Alert identifier.\n * @param body - Comment payload.\n */\n async addAlertComment(alertId: string, body: AddCommentRequest): Promise<AlertDetailResponse> {\n return (await this.request(\"POST\", `/alerts/${alertId}/comments`, { json: body })) as AlertDetailResponse;\n }\n\n /**\n * Subscribe to an alert.\n *\n * @param alertId - Alert identifier.\n */\n async subscribeToAlert(alertId: string): Promise<AlertDetailResponse> {\n return (await this.request(\"POST\", `/alerts/${alertId}/subscribe`)) as AlertDetailResponse;\n }\n\n /**\n * Unsubscribe from an alert.\n *\n * @param alertId - Alert identifier.\n */\n async unsubscribeFromAlert(alertId: string): Promise<AlertDetailResponse> {\n return (await this.request(\"POST\", `/alerts/${alertId}/unsubscribe`)) as AlertDetailResponse;\n }\n\n // ─── Alert Configs ─────────────────────────────────────────────────────────\n\n /**\n * List alert configurations.\n *\n * @param opts - Pagination options.\n * @returns Paginated list of alert configs.\n */\n /**\n * `configs` and `total` are populated on every API version; `data` and\n * `pagination` are also present once `apiVersion` is 2026-07-27 or later.\n */\n async listAlertConfigs(opts: ListAlertConfigsOptions = {}): Promise<AlertConfigListResponse> {\n return keyedList<AlertConfigListResponse>(\n await this.request(\"GET\", \"/alerts/configs\", {\n query: {\n page: opts.page,\n limit: opts.limit,\n agent_id: opts.agentId,\n source_connection_id: opts.sourceConnectionId,\n scope: opts.scope,\n },\n }),\n \"configs\",\n [\"total\"],\n );\n }\n\n /**\n * Create an alert configuration.\n *\n * @param body - Alert config definition.\n * @returns Created alert config.\n */\n async createAlertConfig(body: CreateAlertConfigRequest): Promise<AlertConfigResponse> {\n return (await this.request(\"POST\", \"/alerts/configs\", { json: body })) as AlertConfigResponse;\n }\n\n /**\n * Get an alert configuration by ID.\n *\n * @param configId - Alert config identifier.\n * @returns Alert config details.\n */\n async getAlertConfig(configId: string): Promise<AlertConfigResponse> {\n return (await this.request(\"GET\", `/alerts/configs/${configId}`)) as AlertConfigResponse;\n }\n\n /**\n * Update an alert configuration.\n *\n * @param configId - Alert config identifier.\n * @param body - Fields to update.\n * @returns Updated alert config.\n */\n async updateAlertConfig(configId: string, body: UpdateAlertConfigRequest): Promise<AlertConfigResponse> {\n return (await this.request(\"PATCH\", `/alerts/configs/${configId}`, { json: body })) as AlertConfigResponse;\n }\n\n /**\n * Delete an alert configuration.\n *\n * @param configId - Alert config identifier.\n */\n async deleteAlertConfig(configId: string): Promise<void> {\n await this.request(\"DELETE\", `/alerts/configs/${configId}`);\n }\n\n // ─── Organization Alert Preferences ────────────────────────────────────────\n\n /**\n * List organization alert preferences.\n *\n * @param opts - Organization filter, and whether to include default subscriptions.\n */\n async listOrganizationAlertPreferences(\n opts: ListOrganizationAlertPreferencesOptions = {},\n ): Promise<OrganizationAlertPreferenceListResponse> {\n return keyedList<OrganizationAlertPreferenceListResponse>(\n await this.request(\"GET\", \"/alerts/organization-preferences/list\", {\n query: { organization_id: opts.organizationId, include_defaults: opts.includeDefaults },\n }),\n \"preferences\",\n [\"total\"],\n );\n }\n\n /**\n * Update an organization alert preference.\n *\n * @param organizationId - Organization identifier.\n * @param alertType - Alert type.\n * @param body - Preference update.\n */\n async updateOrganizationAlertPreference(\n organizationId: string,\n alertType: string,\n body: UpdateOrganizationAlertPreferenceRequest,\n ): Promise<OrganizationAlertPreferenceResponse> {\n return (await this.request(\n \"PATCH\",\n `/alerts/organization-preferences/${organizationId}/${alertType}`,\n { json: body },\n )) as OrganizationAlertPreferenceResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Models & Model Alerts\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List model alerts.\n *\n * @param opts - Pagination, an agent filter and `unreadOnly`.\n */\n async listModelAlerts(opts: ListModelAlertsOptions = {}): Promise<ModelAlertListResponse> {\n // The endpoint declares limit/offset, not page, so `page` was ignored and\n // every page after the first returned page 1.\n const limit = opts.limit ?? 50;\n const offset = opts.page && opts.page > 1 ? (opts.page - 1) * limit : undefined;\n return keyedList<ModelAlertListResponse>(\n await this.request(\"GET\", \"/models/alerts\", {\n query: { offset, limit: opts.limit, agent_id: opts.agentId, unread_only: opts.unreadOnly },\n }),\n \"alerts\",\n [\"total\"],\n );\n }\n\n /**\n * Mark all model alerts as read.\n */\n async markAllModelAlertsRead(): Promise<void> {\n await this.request(\"POST\", \"/models/alerts/mark-all-read\");\n }\n\n /**\n * Get unread model alert count.\n */\n async getUnreadModelAlertCount(): Promise<UnreadCountResponse> {\n return (await this.request(\"GET\", \"/models/alerts/unread-count\")) as UnreadCountResponse;\n }\n\n /**\n * Mark a specific model alert as read.\n *\n * @param alertId - Model alert identifier.\n */\n async markModelAlertRead(alertId: string): Promise<void> {\n await this.request(\"PATCH\", `/models/alerts/${alertId}/read`);\n }\n\n /**\n * Get model recommendations.\n *\n * @param modelId - Model identifier.\n * @param opts - Capabilities and limits a recommended model must have.\n */\n async getModelRecommendations(\n modelId: string,\n opts: ModelRecommendationsOptions = {},\n ): Promise<ModelRecommendationsResponse> {\n return (await this.request(\"GET\", `/models/${modelId}/recommendations`, {\n query: {\n require_tool_use: opts.requireToolUse,\n require_structured_output: opts.requireStructuredOutput,\n require_thinking: opts.requireThinking,\n min_context_tokens: opts.minContextTokens,\n min_output_tokens: opts.minOutputTokens,\n },\n })) as ModelRecommendationsResponse;\n }\n\n /**\n * List all enabled LLM models grouped by provider.\n *\n * @param opts - Optional filters.\n */\n async listModels(\n opts: {\n provider?: string;\n supportsToolUse?: boolean;\n supportsThinking?: boolean;\n supportsInputMedia?: string;\n supportsOutputMedia?: string;\n } = {},\n ): Promise<ProviderGroupResponse[]> {\n return listItems<ProviderGroupResponse>(await this.request(\"GET\", \"/models\", {\n query: {\n provider: opts.provider,\n supports_tool_use: opts.supportsToolUse,\n supports_thinking: opts.supportsThinking,\n supports_input_media: opts.supportsInputMedia,\n supports_output_media: opts.supportsOutputMedia,\n },\n }));\n }\n\n /**\n * Get full details for a specific model.\n *\n * @param modelId - Model identifier.\n */\n async getModel(modelId: string): Promise<PromptModelResponse> {\n return (await this.request(\"GET\", `/models/${modelId}/details`)) as PromptModelResponse;\n }\n\n /**\n * List the media-generation quality tiers and the model + cost each resolves to.\n *\n * On a `prompt_call`'s `media_generation` tool — and the dedicated\n * `generate_*` steps via tier routing — the author/LLM picks a *tier*\n * (fast/balanced/thorough), never a model. This maps each\n * `(modality, tier)` to its concrete generator, raw `credits_per_unit`,\n * `unit_label`, and a human-readable scaled `price_label`.\n *\n * Global routing/pricing (the same for every account); read-only.\n */\n async getGenerationTiers(): Promise<GenerationTierListResponse> {\n return keyedList<GenerationTierListResponse>(await this.request(\"GET\", \"/models/generation-tiers\"), \"tiers\");\n }\n\n /**\n * List the embedding models a source can index with, and their pricing.\n *\n * The endpoint lists the embedders under `models` by default and under `data`\n * once the caller opts in with `apiVersion` 2026-07-27 or later; `models` is\n * populated on either, with the defaults and pricing beside it.\n *\n * @param opts.supportsInputMedia - Keep only embedders that can index this\n * input modality — a coarse kind (text, image, video, audio) or a full MIME.\n */\n async listEmbeddingModels(opts: { supportsInputMedia?: string } = {}): Promise<EmbeddingModelListResponse> {\n return keyedList<EmbeddingModelListResponse>(\n await this.request(\"GET\", \"/models/embedders\", {\n query: { supports_input_media: opts.supportsInputMedia },\n }),\n \"models\",\n );\n }\n\n /**\n * List the reranker models a knowledge base can use, and their pricing.\n *\n * `models` is populated on either wire shape, as for {@link Seclai.listEmbeddingModels}.\n */\n async listRerankerModels(): Promise<RerankerModelListResponse> {\n return keyedList<RerankerModelListResponse>(await this.request(\"GET\", \"/models/rerankers\"), \"models\");\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Model Playground Experiments\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List model playground experiments.\n *\n * @param opts - Date range and offset paging. Only `startDate` and `endDate`\n * together replace `days`; either one alone is ignored and the last `days`\n * days apply (server default 30).\n */\n async listExperiments(opts: DateRangeOptions & OffsetPageOptions = {}): Promise<ExperimentListResponse> {\n return keyedList<ExperimentListResponse>(\n await this.request(\"GET\", \"/models/playground/experiments\", {\n query: { days: opts.days, start_date: opts.startDate, end_date: opts.endDate, limit: opts.limit, offset: opts.offset },\n }),\n \"experiments\",\n [\"total\"],\n );\n }\n\n /**\n * Create a model playground experiment.\n *\n * @param body - Experiment configuration.\n */\n async createExperiment(body: CreateExperimentInput): Promise<CreateExperimentResponse> {\n return (await this.request(\"POST\", \"/models/playground/experiments\", { json: body })) as CreateExperimentResponse;\n }\n\n /**\n * Get a model playground experiment by ID.\n *\n * @param experimentId - Experiment identifier.\n */\n async getExperiment(experimentId: string): Promise<ExperimentDetailResponse> {\n return (await this.request(\"GET\", `/models/playground/experiments/${experimentId}`)) as ExperimentDetailResponse;\n }\n\n /**\n * Cancel a running model playground experiment.\n *\n * @param experimentId - Experiment identifier.\n */\n async cancelExperiment(experimentId: string): Promise<CancelExperimentResponse> {\n return (await this.request(\"POST\", `/models/playground/experiments/${experimentId}/cancel`)) as CancelExperimentResponse;\n }\n\n /**\n * Soft-delete a model playground experiment.\n *\n * Removes the experiment from list/detail views while preserving audit\n * history. Returns HTTP 204 with no body.\n *\n * @param experimentId - Experiment identifier.\n */\n async deleteExperiment(experimentId: string): Promise<void> {\n await this.request(\"DELETE\", `/models/playground/experiments/${experimentId}`);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Cloud Drives\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List the cloud-drive providers this deployment has configured.\n *\n * @returns The providers, read from either wire shape.\n */\n async listCloudDriveProviders(): Promise<CloudDriveProviderResponse[]> {\n return listItems<CloudDriveProviderResponse>(await this.request(\"GET\", \"/cloud-drives/providers\"));\n }\n\n /**\n * List the account's cloud-drive connections.\n *\n * @returns The connections, read from either wire shape.\n */\n async listCloudDrives(): Promise<CloudDriveResponse[]> {\n return listItems<CloudDriveResponse>(await this.request(\"GET\", \"/cloud-drives\"));\n }\n\n /**\n * Get a cloud-drive connection.\n *\n * @param connectionId - Cloud-drive connection identifier.\n */\n async getCloudDrive(connectionId: string): Promise<CloudDriveResponse> {\n return (await this.request(\"GET\", `/cloud-drives/${connectionId}`)) as CloudDriveResponse;\n }\n\n /**\n * Update a cloud-drive connection.\n *\n * @param connectionId - Cloud-drive connection identifier.\n * @param body - Fields to change — `name` and/or `folder_path`.\n * @returns The updated connection.\n */\n async updateCloudDrive(connectionId: string, body: CloudDriveUpdateRequest): Promise<CloudDriveResponse> {\n return (await this.request(\"PATCH\", `/cloud-drives/${connectionId}`, { json: body })) as CloudDriveResponse;\n }\n\n /**\n * Disconnect a cloud-drive connection, keeping the connection itself.\n *\n * @param connectionId - Cloud-drive connection identifier.\n * @returns The connection in its disconnected state.\n */\n async disconnectCloudDrive(connectionId: string): Promise<CloudDriveResponse> {\n return (await this.request(\"POST\", `/cloud-drives/${connectionId}/disconnect`)) as CloudDriveResponse;\n }\n\n /**\n * Delete a cloud-drive connection.\n *\n * @param connectionId - Cloud-drive connection identifier.\n */\n async deleteCloudDrive(connectionId: string): Promise<void> {\n await this.request(\"DELETE\", `/cloud-drives/${connectionId}`);\n }\n\n /**\n * List the agents that use a cloud-drive connection.\n *\n * @param connectionId - Cloud-drive connection identifier.\n * @returns The agents, read from either wire shape.\n */\n async getAgentsUsingCloudDrive(connectionId: string): Promise<AgentUsingCloudDriveResponse[]> {\n return listItems<AgentUsingCloudDriveResponse>(\n await this.request(\"GET\", `/cloud-drives/${connectionId}/agents`),\n );\n }\n\n /**\n * List the files a cloud-drive connection skipped, newest first.\n *\n * A skipped file fires no trigger, so this is where to look when an agent\n * did not run for a file.\n *\n * @param connectionId - Cloud-drive connection identifier.\n * @param opts.limit - Maximum number of rejections (1-200, default 50).\n * @returns The rejections with their reasons, read from either wire shape.\n */\n async listCloudDriveRejections(\n connectionId: string,\n opts: { limit?: number } = {},\n ): Promise<CloudDriveRejectionResponse[]> {\n return listItems<CloudDriveRejectionResponse>(\n await this.request(\"GET\", `/cloud-drives/${connectionId}/rejections`, {\n query: { limit: opts.limit },\n }),\n );\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Search\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Search across all resource types in your account.\n *\n * Accepts a free-text keyword query or a UUID. Results are ranked:\n * name-prefix > name-substring > description-substring.\n *\n * @param opts - Search options.\n * @param opts.query - Search query string (required, 1-200 chars).\n * @param opts.limit - Maximum results (1-50, default 10).\n * @param opts.entityType - Optional entity type filter (e.g. \"agent\", \"knowledge_base\").\n * @returns Search results.\n */\n async search(opts: { query: string; limit?: number; entityType?: string }): Promise<SearchResponse> {\n return (await this.request(\"GET\", \"/search\", {\n query: { q: opts.query, limit: opts.limit, entity_type: opts.entityType },\n })) as SearchResponse;\n }\n\n /**\n * Search the Seclai documentation by content.\n *\n * `mode: \"keyword\"` matches page titles and summaries (fast, no AI cost);\n * `mode: \"semantic\"` matches page body content by meaning (uses an embedding).\n *\n * Each result carries a `doc_slug` and an optional section `anchor` for\n * building a `https://seclai.com/docs/<doc_slug>[#<anchor>]` link, a `score`\n * (not comparable across modes), and — in semantic mode — a `highlight`\n * (best matching verbatim sentence; `null` for keyword).\n *\n * Documentation is global, so results are not account-scoped.\n *\n * @param opts - Search options.\n * @param opts.query - Search query string (required, 1-200 chars).\n * @param opts.mode - Search strategy (default `\"keyword\"`).\n * @param opts.limit - Maximum results (1-20, default 8).\n */\n async searchDocs(opts: { query: string; mode?: \"keyword\" | \"semantic\"; limit?: number }): Promise<Record<string, unknown>> {\n return (await this.request(\"GET\", \"/docs-search\", {\n query: { q: opts.query, mode: opts.mode, limit: opts.limit },\n })) as Record<string, unknown>;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Email Domains\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * List the account's vanity (`<slug>.seclai.com`) and custom\n * (`agent.mycompany.com`) agent-email domains.\n *\n * Includes each domain's verification status and the DNS records the customer\n * must publish, plus the plan capabilities (`can_add_vanity` /\n * `can_add_custom`) and whether one of each kind already exists\n * (`has_vanity` / `has_custom` — the per-kind limit is 1).\n *\n * Requires a user-bound credential; an account-only API key is refused with 403.\n */\n async listEmailDomains(): Promise<EmailDomainsListResponse> {\n return keyedList<EmailDomainsListResponse>(await this.request(\"GET\", \"/email-domains\"), \"domains\");\n }\n\n /**\n * Add and provision a new agent-email domain.\n *\n * Pass `kind: \"vanity\"` with `value: \"<slug>\"`, or `kind: \"custom\"` with\n * `value: \"agent.mycompany.com\"` (optionally `delegated: true` to let Seclai\n * manage a dedicated Route53 zone). Stands up the SES identity + DNS and\n * returns the records the customer must publish. Requires an account\n * owner/admin.\n *\n * @param body - The domain to add. `delegated` defaults to `false` server-side.\n */\n async addEmailDomain(body: AddEmailDomainInput): Promise<EmailDomainResponse> {\n return (await this.request(\"POST\", \"/email-domains\", { json: body })) as EmailDomainResponse;\n }\n\n /**\n * Remove a domain and tear down its SES identity + DNS / receipt-rule recipient.\n *\n * Returns a `cleanup_note` when the removed domain was Seclai-managed\n * (delegated), reminding you to delete the registrar NS delegation record\n * (dangling-delegation / subdomain-takeover guard). Requires an account\n * owner/admin.\n *\n * @param domainId - Domain identifier.\n */\n async removeEmailDomain(domainId: string): Promise<RemoveEmailDomainResponse> {\n return (await this.request(\"DELETE\", `/email-domains/${domainId}`)) as RemoveEmailDomainResponse;\n }\n\n /**\n * Run a verification check immediately (\"Check now\").\n *\n * Re-polls SES + DNS for this domain instead of waiting for the background\n * verification sweep, and returns its updated status + DNS-record check\n * results. Useful right after publishing the required records. Requires an\n * account owner/admin.\n *\n * @param domainId - Domain identifier.\n */\n async verifyEmailDomain(domainId: string): Promise<EmailDomainResponse> {\n return (await this.request(\"POST\", `/email-domains/${domainId}/verify`)) as EmailDomainResponse;\n }\n\n /**\n * Promote a verified domain to the account's primary domain.\n *\n * Agent email then sends FROM and receives ON this domain\n * (`<agentID>@<domain>`, `<alias>@<domain>`) instead of the shared\n * `agent.seclai.com`. The domain must be verified. Requires an account\n * owner/admin.\n *\n * @param domainId - Domain identifier.\n */\n async setPrimaryEmailDomain(domainId: string): Promise<EmailDomainResponse> {\n return (await this.request(\"POST\", `/email-domains/${domainId}/primary`)) as EmailDomainResponse;\n }\n\n /**\n * Revert to the shared `agent.seclai.com` sending/inbound domain.\n *\n * Clears the account's primary domain WITHOUT removing the configured\n * domain(s) — they stay verified and can be promoted again later. Requires an\n * account owner/admin.\n */\n async useSharedEmailDomain(): Promise<void> {\n await this.request(\"POST\", \"/email-domains/use-shared-domain\");\n }\n\n /**\n * Send a test message FROM a verified domain (`noreply@<domain>`) TO the\n * account owner's email.\n *\n * Confirms end-to-end that the domain actually sends (SES verified, DKIM/SPF\n * aligned). Never sends to any other address, so it can't be used as an open\n * relay. Requires an account owner/admin.\n *\n * @param domainId - Domain identifier.\n */\n async sendEmailDomainTestEmail(domainId: string): Promise<SendTestEmailResponse> {\n return (await this.request(\"POST\", `/email-domains/${domainId}/test-email`)) as SendTestEmailResponse;\n }\n\n /**\n * Get the DMARC aggregate-report summary for a domain.\n *\n * Pass rate, disposition breakdown (`none`/`quarantine`/`reject`), and top\n * failing source IPs from the DMARC `rua` reports over the last `days`\n * (clamped by the service).\n *\n * Populated for domains whose DNS zone Seclai controls (vanity + delegated\n * custom); a self-managed custom domain keeps its own DMARC reporting and\n * returns an all-zero summary.\n *\n * @param domainId - Domain identifier.\n * @param opts - Reporting window options.\n * @param opts.days - Window length in days (default 30).\n * @param opts.topSources - Number of top failing sources to return (default 10).\n */\n async getDmarcSummary(\n domainId: string,\n opts: { days?: number; topSources?: number } = {},\n ): Promise<DmarcSummaryResponse> {\n return (await this.request(\"GET\", `/email-domains/${domainId}/dmarc`, {\n query: { days: opts.days, top_sources: opts.topSources },\n })) as DmarcSummaryResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Top-Level AI Assistant\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Submit feedback on an AI assistant interaction.\n *\n * @param body - Feedback payload (thumbs up/down, optional comment).\n * @returns Feedback response.\n */\n async submitAiFeedback(body: AiAssistantFeedbackRequest): Promise<AiAssistantFeedbackResponse> {\n return (await this.request(\"POST\", \"/ai-assistant/feedback\", { json: body })) as AiAssistantFeedbackResponse;\n }\n\n /**\n * Generate a knowledge base configuration via AI assistant.\n *\n * @param body - Generation request.\n */\n async aiAssistantKnowledgeBase(body: AiAssistantGenerateRequest): Promise<AiAssistantGenerateResponse> {\n return (await this.request(\"POST\", \"/ai-assistant/knowledge-base\", { json: body })) as AiAssistantGenerateResponse;\n }\n\n /**\n * Generate a source configuration via AI assistant.\n *\n * @param body - Generation request.\n */\n async aiAssistantSource(body: AiAssistantGenerateRequest): Promise<AiAssistantGenerateResponse> {\n return (await this.request(\"POST\", \"/ai-assistant/source\", { json: body })) as AiAssistantGenerateResponse;\n }\n\n /**\n * Generate a solution via AI assistant.\n *\n * @param body - Generation request.\n */\n async aiAssistantSolution(body: AiAssistantGenerateRequest): Promise<AiAssistantGenerateResponse> {\n return (await this.request(\"POST\", \"/ai-assistant/solution\", { json: body })) as AiAssistantGenerateResponse;\n }\n\n /**\n * Generate a memory bank configuration via AI assistant.\n *\n * @param body - Generation request.\n */\n async aiAssistantMemoryBank(body: MemoryBankAiAssistantRequest): Promise<MemoryBankAiAssistantResponse> {\n return (await this.request(\"POST\", \"/ai-assistant/memory-bank\", { json: body })) as MemoryBankAiAssistantResponse;\n }\n\n /**\n * Get AI assistant memory bank conversation history.\n *\n * @param opts - Turns to return (server default 5) and most-recent turns to skip (default 0).\n */\n async getAiAssistantMemoryBankHistory(opts: OffsetPageOptions = {}): Promise<MemoryBankLastConversationResponse> {\n return (await this.request(\"GET\", \"/ai-assistant/memory-bank/last-conversation\", {\n query: { limit: opts.limit, offset: opts.offset },\n })) as MemoryBankLastConversationResponse;\n }\n\n /**\n * Accept an AI assistant suggestion.\n *\n * @param conversationId - Conversation identifier.\n * @param body - Acceptance request payload.\n */\n async acceptAiAssistantPlan(conversationId: string, body: AiAssistantAcceptRequest): Promise<AiAssistantAcceptResponse> {\n return (await this.request(\"POST\", `/ai-assistant/${conversationId}/accept`, { json: body })) as AiAssistantAcceptResponse;\n }\n\n /**\n * Decline an AI assistant suggestion.\n *\n * @param conversationId - Conversation identifier.\n */\n async declineAiAssistantPlan(conversationId: string): Promise<void> {\n await this.request(\"POST\", `/ai-assistant/${conversationId}/decline`);\n }\n\n /**\n * Accept/mark an AI memory bank suggestion.\n *\n * @param conversationId - Conversation identifier.\n * @param body - Acceptance payload for the memory bank suggestion.\n */\n async acceptAiMemoryBankSuggestion(conversationId: string, body: MemoryBankAcceptRequest): Promise<OkResponse> {\n return (await this.request(\"PATCH\", `/ai-assistant/memory-bank/${conversationId}`, { json: body })) as OkResponse;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // Pagination Helpers\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Auto-paginate through a list endpoint.\n *\n * Yields individual items from each page, fetching the next page until the\n * response reports there is none. A fetcher that answers with a bare array has\n * no further pages, so its items are yielded once.\n *\n * @param fetchPage - A function that fetches a single page given `{ page, limit }`.\n * @param opts - Page size (default: 50).\n * @throws {@link SeclaiError} When a page carries its items under neither `data` nor `items`.\n *\n * @example\n * ```ts\n * for await (const agent of client.paginate(\n * (opts) => client.listAgents(opts),\n * )) {\n * console.log(agent.name);\n * }\n * ```\n */\n async *paginate<T>(\n fetchPage: (opts: { page: number; limit: number }) => Promise<PaginatedPage<T>>,\n opts?: { limit?: number },\n ): AsyncGenerator<T, void, undefined> {\n const limit = opts?.limit ?? 50;\n let page = 1;\n\n while (true) {\n const result = (await fetchPage({ page, limit })) as unknown;\n if (Array.isArray(result)) {\n yield* result as T[];\n return;\n }\n const body = (result ?? {}) as {\n data?: T[] | null;\n items?: T[] | null;\n pagination?: { pages?: number; total_pages?: number; has_next?: boolean } | null;\n total?: number;\n limit?: number;\n };\n const items = \"data\" in body ? body.data ?? [] : body.items;\n if (!Array.isArray(items)) {\n throw new SeclaiError(\n \"paginate() could not find the page's items: expected an array, or an object with a `data` or `items` array.\",\n );\n }\n yield* items;\n\n const pagination = body.pagination;\n if (items.length === 0) return;\n if (!pagination) {\n // The flat `{data, total, page, limit}` shape. Counted from the page\n // requested, so a server that ignores `page` cannot loop this forever.\n if (typeof body.total !== \"number\") return;\n const pageSize = typeof body.limit === \"number\" && body.limit > 0 ? body.limit : limit;\n if (page * pageSize >= body.total) return;\n } else if (typeof pagination.has_next === \"boolean\") {\n if (!pagination.has_next) return;\n } else {\n const pages = pagination.pages ?? pagination.total_pages;\n if (items.length < limit || pages === undefined || page >= pages) return;\n }\n page++;\n }\n }\n}\n"],"mappings":";AAUO,IAAM,mBAAmB;AAAA,EAC9B,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA;AAAA,EAEb,SAAS;AAAA;AAAA,EAET,QAAQ;AACV;AAaO,IAAM,qBAAwC,OAAO,QAAQ,gBAAgB,EACjF,OAAO,CAAC,CAAC,CAAC,MAAM,EAAE,WAAW,GAAG,CAAC,EACjC,IAAI,CAAC,CAAC,EAAE,CAAC,MAAM,CAAC;;;ACtCZ,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,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