@typesafe-ai/sdk 0.0.0-bootstrap.0 → 0.5.7
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/README.md +34 -7
- package/dist/index.cjs +734 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +415 -0
- package/dist/index.d.mts +415 -0
- package/dist/index.mjs +714 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +70 -8
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../src/api-promise.ts","../src/env.ts","../src/retry.ts","../src/errors.ts","../src/logging.ts","../src/questions.ts","../src/resources/models.ts","../src/runtime.ts","../src/version.ts","../src/client.ts"],"sourcesContent":["export const REQUEST_ID_HEADER = \"x-typesafe-request-id\";\n\nexport const requestIdFrom = (headers: Headers): string | undefined =>\n headers.get(REQUEST_ID_HEADER) ?? undefined;\n\n/** Parsed data with its HTTP response and request ID. */\nexport interface WithResponse<T> {\n /** The parsed response body. */\n data: T;\n /** The HTTP response, with its body consumed by parsing. */\n response: Response;\n /** Request ID from `x-typesafe-request-id`, or `undefined` when absent. */\n requestId: string | undefined;\n}\n\n/**\n * A promise for the parsed result with access to the HTTP response.\n *\n * Non-2xx responses reject with an `APIError`, including through `asResponse()`.\n */\nexport class APIPromise<T> extends Promise<T> {\n readonly #responsePromise: Promise<Response>;\n readonly #parseResponse: (response: Response) => Promise<T>;\n #parsed: Promise<T> | undefined;\n\n constructor(\n responsePromise: Promise<Response>,\n parseResponse: (response: Response) => Promise<T>,\n ) {\n // The inherited promise is never used; all consumers go through `parse()`.\n super((resolve) => resolve(undefined as T));\n this.#responsePromise = responsePromise;\n this.#parseResponse = parseResponse;\n }\n\n /**\n * Resolves to the raw `Response` without parsing the body. SDK requests buffer the full\n * body under the request timeout before handoff; reading it afterwards is caller-owned.\n * The caller owns the body; don't also `await` the parsed result on the same promise.\n */\n asResponse(): Promise<Response> {\n return this.#responsePromise;\n }\n\n /** Return the parsed result, HTTP response, and request ID. */\n async withResponse(): Promise<WithResponse<T>> {\n const [data, response] = await Promise.all([this.#parse(), this.#responsePromise]);\n return { data, response, requestId: requestIdFrom(response.headers) };\n }\n\n /** Transform the parsed result, sharing the HTTP response and a single body parse. */\n map<U>(fn: (data: T) => U): APIPromise<U> {\n return new APIPromise<U>(this.#responsePromise, () => this.#parse().then(fn));\n }\n\n #parse(): Promise<T> {\n this.#parsed ??= this.#responsePromise.then(this.#parseResponse);\n return this.#parsed;\n }\n\n // biome-ignore lint/suspicious/noThenProperty: this is a Promise subclass; overriding then is the point\n override then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.#parse().then(onfulfilled, onrejected);\n }\n\n override catch<TResult = never>(\n onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null,\n ): Promise<T | TResult> {\n return this.#parse().catch(onrejected);\n }\n\n override finally(onfinally?: (() => void) | null): Promise<T> {\n return this.#parse().finally(onfinally);\n }\n}\n","/** Environment variable names for client configuration. Explicit options take precedence. */\nexport const ENV = {\n /** Required API key; used when `apiKey` is omitted. */\n apiKey: \"TYPESAFE_API_KEY\",\n /** API root; defaults to `https://api.typesafe.ai`. */\n baseURL: \"TYPESAFE_BASE_URL\",\n /** Default model name; defaults to `jev-latest`. */\n defaultModel: \"TYPESAFE_DEFAULT_MODEL\",\n /** Log level; defaults to `warn`. */\n logLevel: \"TYPESAFE_LOG_LEVEL\",\n} as const;\n\nexport type EnvVar = (typeof ENV)[keyof typeof ENV];\n\n/** Read a trimmed environment value, returning `undefined` for missing or blank values. */\nexport const readEnv = (name: EnvVar): string | undefined => {\n if (typeof process === \"undefined\" || !process.env) return undefined;\n return process.env[name]?.trim() || undefined;\n};\n\n/** Return the explicit value, falling back to the environment. */\nexport const fromCodeOrEnv = (fromCode: string | undefined, envVar: EnvVar): string | undefined =>\n fromCode ?? readEnv(envVar);\n","/** Retry defaults, delay calculation, and cancellable waits. */\n\nimport type { RetryPolicy } from \"./types\";\n\nexport const DEFAULT_TIMEOUT_MS = 10_000;\n\nconst range = (from: number, to: number): number[] =>\n Array.from({ length: to - from }, (_, i) => from + i);\n\n/** Default SDK retry policy. */\nexport const DEFAULT_RETRY_POLICY: RetryPolicy = {\n maxRetries: 2,\n backoffInitialMs: 500,\n backoffMaxMs: 5_000,\n backoffJitter: 0.25,\n /** HTTP 408, 429, and 5xx responses. */\n httpStatuses: new Set([408, 429, ...range(500, 600)]),\n respectRetryAfter: true,\n /** Maximum server retry delay before falling back to backoff. */\n maxRetryAfterMs: 60_000,\n apiConnectionError: true,\n apiTimeoutError: true,\n};\n\nexport const DEFAULT_MAX_RETRIES: number = DEFAULT_RETRY_POLICY.maxRetries;\n\n/** Whether the policy retries an HTTP status code. */\nexport const isRetryableStatus = (\n status: number,\n policy: RetryPolicy = DEFAULT_RETRY_POLICY,\n): boolean => policy.httpStatuses.has(status);\n\n/**\n * Parse `retry-after-ms` or `Retry-After` into milliseconds, preferring `retry-after-ms`.\n *\n * Return `undefined` when neither header contains a valid delay.\n */\nexport const parseRetryAfter = (headers: Headers, now: number = Date.now()): number | undefined => {\n const ms = Number(headers.get(\"retry-after-ms\"));\n if (headers.has(\"retry-after-ms\") && Number.isFinite(ms) && ms >= 0) return ms;\n\n const raw = headers.get(\"retry-after\");\n if (raw === null) return undefined;\n const seconds = Number(raw);\n if (Number.isFinite(seconds)) return seconds >= 0 ? seconds * 1000 : undefined;\n const date = Date.parse(raw);\n if (!Number.isNaN(date)) return Math.max(0, date - now);\n return undefined;\n};\n\n/**\n * Calculate the delay in milliseconds for a zero-based retry attempt.\n *\n * Use an allowed server delay; otherwise use capped exponential backoff with jitter.\n */\nexport const retryDelayMs = (\n attempt: number,\n headers?: Headers,\n policy: RetryPolicy = DEFAULT_RETRY_POLICY,\n random: () => number = Math.random,\n): number => {\n if (policy.respectRetryAfter && headers !== undefined) {\n const retryAfter = parseRetryAfter(headers);\n if (retryAfter !== undefined && retryAfter <= policy.maxRetryAfterMs) return retryAfter;\n }\n const exponential = Math.min(policy.backoffInitialMs * 2 ** attempt, policy.backoffMaxMs);\n return Math.round(exponential * (1 - random() * policy.backoffJitter));\n};\n\n/** Wait `ms` milliseconds, rejecting with `signal.reason` on cancellation. */\nexport const sleep = (ms: number, signal?: AbortSignal): Promise<void> =>\n new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason);\n const onAbort = (): void => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n","import { requestIdFrom } from \"./api-promise\";\nimport { parseRetryAfter } from \"./retry\";\n\n/** Base class for SDK errors. */\nexport class TypeSafeError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = new.target.name;\n }\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\n/** Extract a message from a text, error, or validation response body. */\nconst extractMessage = (body: unknown): string | undefined => {\n if (typeof body === \"string\") return body || undefined;\n if (!isRecord(body)) return undefined;\n const { error, message, detail } = body;\n if (typeof error === \"string\") return error;\n if (isRecord(error) && typeof error.message === \"string\") return error.message;\n if (typeof message === \"string\") return message;\n if (typeof detail === \"string\") return detail;\n if (isRecord(detail) && typeof detail.message === \"string\") return detail.message;\n if (Array.isArray(detail)) return describeValidationErrors(detail);\n return undefined;\n};\n\n/** Format validation errors as semicolon-separated `path: message` entries. */\nconst describeValidationErrors = (errors: unknown[]): string | undefined => {\n const parts = errors.flatMap((e) => {\n if (!isRecord(e) || typeof e.msg !== \"string\") return [];\n const loc = Array.isArray(e.loc) ? e.loc.filter((x) => x !== \"body\").join(\".\") : \"\";\n return [loc ? `${loc}: ${e.msg}` : e.msg];\n });\n return parts.length > 0 ? parts.join(\"; \") : undefined;\n};\n\nconst MAX_RAW_BODY_IN_MESSAGE = 200;\n\n/** An unsuccessful HTTP response from the API. */\nexport class APIError extends TypeSafeError {\n /** HTTP response status code. */\n readonly status: number;\n /** HTTP response headers. */\n readonly headers: Headers;\n /** Parsed JSON, response text, or `undefined` for an empty body. */\n readonly body: unknown;\n /** Request ID from `x-typesafe-request-id`, or `undefined` when absent. */\n readonly requestId: string | undefined;\n\n constructor(status: number, body: unknown, headers: Headers, message?: string) {\n super(message ?? APIError.describe(status, body));\n this.status = status;\n this.body = body;\n this.headers = headers;\n this.requestId = requestIdFrom(headers);\n }\n\n private static describe(status: number, body: unknown): string {\n const detail = extractMessage(body);\n if (detail) return `${status} ${detail}`;\n if (body === undefined) return `${status} status code (no body)`;\n const raw = typeof body === \"string\" ? body : JSON.stringify(body);\n return `${status} ${raw.length > MAX_RAW_BODY_IN_MESSAGE ? `${raw.slice(0, MAX_RAW_BODY_IN_MESSAGE)}…` : raw}`;\n }\n\n /** Create the error subclass for an HTTP status code. */\n static fromResponse(status: number, body: unknown, headers: Headers): APIError {\n if (status === 400) return new BadRequestError(status, body, headers);\n if (status === 401) return new AuthenticationError(status, body, headers);\n if (status === 403) return new PermissionDeniedError(status, body, headers);\n if (status === 404) return new NotFoundError(status, body, headers);\n if (status === 422) return new UnprocessableEntityError(status, body, headers);\n if (status === 429) return new RateLimitError(status, body, headers);\n if (status >= 500) return new InternalServerError(status, body, headers);\n return new APIError(status, body, headers);\n }\n}\n\n/** HTTP 400: the request is invalid. */\nexport class BadRequestError extends APIError {}\n/** HTTP 401: authentication failed. */\nexport class AuthenticationError extends APIError {}\n/** HTTP 403: access is denied. */\nexport class PermissionDeniedError extends APIError {}\n/** HTTP 404: the resource was not found. */\nexport class NotFoundError extends APIError {}\n/** HTTP 422: request validation failed. */\nexport class UnprocessableEntityError extends APIError {}\n/** HTTP 429: the rate limit was exceeded. */\nexport class RateLimitError extends APIError {\n /** Server retry delay in milliseconds, or `undefined` when absent or invalid. */\n readonly retryAfterMs: number | undefined = parseRetryAfter(this.headers);\n}\n/** HTTP 5xx: the server failed to handle the request. */\nexport class InternalServerError extends APIError {}\n\n/** The request or response-body delivery failed (DNS, TLS, connection closed, etc.). */\nexport class APIConnectionError extends TypeSafeError {\n constructor(message = \"Connection error.\", options?: ErrorOptions) {\n super(message, options);\n }\n}\n\n/** The full response did not arrive within the timeout. A kind of `APIConnectionError`. */\nexport class APITimeoutError extends APIConnectionError {\n /** Configured timeout in milliseconds. */\n readonly timeoutMs: number;\n\n constructor(timeoutMs: number, options?: ErrorOptions) {\n super(`Request timed out after ${timeoutMs}ms.`, options);\n this.timeoutMs = timeoutMs;\n }\n}\n\n/** The caller cancelled the request through an `AbortSignal`. */\nexport class APIUserAbortError extends TypeSafeError {\n constructor(message = \"Request was aborted.\", options?: ErrorOptions) {\n super(message, options);\n }\n}\n","import { TypeSafeError } from \"./errors\";\nimport type { Logger, LogLevel } from \"./types\";\n\n/** Supported log levels, from most to least verbose. */\nexport const LOG_LEVELS: readonly LogLevel[] = [\"debug\", \"info\", \"warn\", \"error\", \"off\"];\n\nexport const DEFAULT_LOG_LEVEL: LogLevel = \"warn\";\n\nconst isLogLevel = (value: string): value is LogLevel =>\n (LOG_LEVELS as readonly string[]).includes(value);\n\n/** Validate a configured log level, throwing `TypeSafeError` for unknown values. */\nexport const parseLogLevel = (value: string, source: string): LogLevel => {\n if (isLogLevel(value)) return value;\n throw new TypeSafeError(\n `Invalid log level \"${value}\" from ${source}. Expected one of: ${LOG_LEVELS.join(\", \")}.`,\n );\n};\n\n// ---------------------------------------------------------------------------\n// Loggers\n// ---------------------------------------------------------------------------\n\nconst PREFIX = \"[typesafe-sdk]\";\n\n/** Default console logger with the `[typesafe-sdk]` prefix. */\nexport const consoleLogger: Logger = {\n debug: (message, ...args) => console.debug(`${PREFIX} ${message}`, ...args),\n info: (message, ...args) => console.info(`${PREFIX} ${message}`, ...args),\n warn: (message, ...args) => console.warn(`${PREFIX} ${message}`, ...args),\n error: (message, ...args) => console.error(`${PREFIX} ${message}`, ...args),\n};\n\nconst RANK: Record<LogLevel, number> = { debug: 0, info: 1, warn: 2, error: 3, off: 4 };\n\nconst drop = (): void => {};\n\n/** Filter logger calls to the configured level and above. */\nexport const withLevel = (sink: Logger, level: LogLevel): Logger => {\n const enabled = (at: LogLevel): boolean => RANK[at] >= RANK[level];\n return {\n debug: enabled(\"debug\") ? (message, ...args) => sink.debug(message, ...args) : drop,\n info: enabled(\"info\") ? (message, ...args) => sink.info(message, ...args) : drop,\n warn: enabled(\"warn\") ? (message, ...args) => sink.warn(message, ...args) : drop,\n error: enabled(\"error\") ? (message, ...args) => sink.error(message, ...args) : drop,\n };\n};\n\n// ---------------------------------------------------------------------------\n// Redaction\n// ---------------------------------------------------------------------------\n\n/** Credential headers that retain a key suffix for identification. */\nconst KEY_HEADERS: ReadonlySet<string> = new Set([\n \"authorization\",\n \"proxy-authorization\",\n \"x-api-key\",\n]);\n\n/** Headers whose values are redacted in full. */\nconst OPAQUE_HEADERS: ReadonlySet<string> = new Set([\"cookie\", \"set-cookie\"]);\n\n/** Mask a key, preserving its scheme and the last four characters of secrets longer than eight. */\nconst redactKey = (value: string): string => {\n const [scheme, secret] = value.includes(\" \") ? value.split(/\\s+/, 2) : [undefined, value];\n const tail = secret && secret.length > 8 ? secret.slice(-4) : \"\";\n return `${scheme ? `${scheme} ` : \"\"}***${tail}`;\n};\n\nconst redact = (name: string, value: string): string => {\n const lower = name.toLowerCase();\n if (KEY_HEADERS.has(lower)) return redactKey(value);\n if (OPAQUE_HEADERS.has(lower)) return \"***\";\n return value;\n};\n\n/** Copy headers with known credential values redacted. */\nexport const redactHeaders = (headers: Record<string, string>): Record<string, string> =>\n Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, redact(name, value)]));\n","import { TypeSafeError } from \"./errors\";\nimport type {\n ChoiceCriteria,\n ChoiceQuestion,\n EntryType,\n NoulQuestion,\n Questions,\n ScoreCriteria,\n ScoreList,\n ScoreMap,\n ScoreQuestion,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Builders\n// ---------------------------------------------------------------------------\n\n/**\n * Create a yes/no question with optional descriptions for either outcome.\n *\n * @param instructions - The question as text, a JSON object or array; defaults to `null`.\n * @param criteria - Optional descriptions of the yes and no outcomes.\n */\nexport const noul = (\n instructions: EntryType = null,\n criteria?: NoulQuestion[\"criteria\"],\n): NoulQuestion => ({\n type: \"noul\",\n instructions,\n criteria,\n});\n\n/**\n * Create a score question using an ordered rubric.\n *\n * @param instructions - The question as text, a JSON object or array, or `null`.\n * @param criteria - A nonempty array or map indexed from zero with no gaps; descriptions may be `null`.\n */\nexport const score = <const T extends ScoreCriteria>(\n instructions: EntryType,\n criteria: T,\n): ScoreQuestion<T> => ({\n type: \"score\",\n instructions,\n criteria,\n});\n\n/**\n * Create a question that selects between named alternatives.\n *\n * @param instructions - The question as text, a JSON object or array, or `null`.\n * @param criteria - Labels mapped to descriptions, or `null` for undescribed labels.\n */\nexport const choice = <const T extends ChoiceCriteria>(\n instructions: EntryType,\n criteria: T,\n): ChoiceQuestion<T> => {\n if (Array.isArray(criteria)) {\n throw new TypeSafeError(\"Choice criteria must be a map of labels to descriptions, not a list.\");\n }\n return { type: \"choice\", instructions, criteria };\n};\n\n// ---------------------------------------------------------------------------\n// Wire normalization\n// ---------------------------------------------------------------------------\n\nconst isScoreList = (criteria: ScoreCriteria): criteria is ScoreList => Array.isArray(criteria);\n\n/** Validate score keys and convert the map to a nonempty array indexed from zero. */\nexport const scoreMapToList = (map: ScoreMap, name: string): ScoreList => {\n const keys = Object.keys(map)\n .map((key) => {\n const n = Number(key);\n if (!Number.isInteger(n) || n < 0) {\n throw new TypeSafeError(\n `Score question \"${name}\" has criteria key \"${key}\"; keys must be non-negative integers.`,\n );\n }\n return n;\n })\n .sort((a, b) => a - b);\n if (keys.length === 0) throw noScores(name);\n\n const expected = keys.map((_, i) => i);\n if (keys.some((k, i) => k !== expected[i])) {\n throw new TypeSafeError(\n `Score question \"${name}\" defines scores ${keys.join(\", \")}, but scores must run from 0 ` +\n `with no gaps (expected ${expected.join(\", \")}).`,\n );\n }\n return keys.map((k) => map[k]) as unknown as ScoreList;\n};\n\nconst noScores = (name: string): TypeSafeError =>\n new TypeSafeError(`Score question \"${name}\" has no criteria; at least one score is required.`);\n\n/** Validate nonempty questions and score criteria, converting score maps to arrays. */\nexport const toWireQuestions = <Q extends Questions>(questions: Q): Q => {\n if (Object.keys(questions).length === 0) {\n throw new TypeSafeError(\"At least one question is required.\");\n }\n let changed = false;\n const wire: Questions = Object.create(null);\n for (const [name, question] of Object.entries(questions)) {\n if (question.type !== \"score\") {\n wire[name] = question;\n } else if (isScoreList(question.criteria)) {\n if (question.criteria.length === 0) throw noScores(name);\n wire[name] = question;\n } else {\n wire[name] = { ...question, criteria: scoreMapToList(question.criteria, name) };\n changed = true;\n }\n }\n return changed ? (wire as Q) : questions;\n};\n","import type { APIPromise } from \"../api-promise\";\nimport type { Transport } from \"../client\";\nimport { TypeSafeError } from \"../errors\";\nimport type { ModelCard, RequestOptions } from \"../types\";\n\n/** Access to the Models API resource. */\nexport class Models {\n readonly #transport: Transport;\n\n constructor(transport: Transport) {\n this.#transport = transport;\n }\n\n /** List the models available to the account. */\n list(options: RequestOptions = {}): APIPromise<ModelCard[]> {\n return this.#transport.request<ModelsWire>(\"GET\", \"/v1/models\", options).map(unwrapModels);\n }\n}\n\n/** Model list response from `GET /v1/models`. */\ntype ModelsWire = { models: ModelCard[] };\n\nconst unwrapModels = (wire: ModelsWire): ModelCard[] => {\n if (Array.isArray(wire?.models)) return wire.models;\n throw new TypeSafeError(\n \"Unexpected response shape from GET /v1/models; expected { models: [...] }.\",\n );\n};\n","/** Runtime detection for browser guards and request headers. */\n\ninterface RuntimeGlobals {\n window?: { document?: unknown };\n navigator?: { userAgent?: string };\n process?: { versions?: Record<string, string | undefined>; platform?: string; arch?: string };\n Deno?: { version?: { deno?: string } };\n Bun?: { version?: string };\n EdgeRuntime?: unknown;\n}\n\nconst g = globalThis as RuntimeGlobals;\n\n/** Whether browser page globals are present. */\nexport const isBrowser = (): boolean =>\n typeof g.window !== \"undefined\" &&\n typeof g.window.document !== \"undefined\" &&\n typeof g.navigator !== \"undefined\";\n\n/** Runtime name, version, and platform for the `X-TypeSafe-Runtime` header. */\nexport const describeRuntime = (): string => {\n const platform =\n g.process?.platform && g.process?.arch ? ` (${g.process.platform}; ${g.process.arch})` : \"\";\n if (g.Bun?.version) return `bun/${g.Bun.version}${platform}`;\n if (g.Deno?.version?.deno) return `deno/${g.Deno.version.deno}${platform}`;\n if (g.EdgeRuntime !== undefined) return \"vercel-edge\";\n if (g.navigator?.userAgent === \"Cloudflare-Workers\") return \"cloudflare-workers\";\n if (g.process?.versions?.node) return `node/${g.process.versions.node}${platform}`;\n if (isBrowser()) return \"browser\";\n return \"unknown\";\n};\n","// Keep in sync with package.json \"version\". Checked by `npm run check:version`.\nexport const VERSION = \"0.5.7\";\n","import { APIPromise, requestIdFrom } from \"./api-promise\";\nimport { ENV, fromCodeOrEnv, readEnv } from \"./env\";\nimport {\n APIConnectionError,\n APIError,\n APITimeoutError,\n APIUserAbortError,\n TypeSafeError,\n} from \"./errors\";\nimport {\n consoleLogger,\n DEFAULT_LOG_LEVEL,\n parseLogLevel,\n redactHeaders,\n withLevel,\n} from \"./logging\";\nimport { toWireQuestions } from \"./questions\";\nimport { Models } from \"./resources/models\";\nimport {\n DEFAULT_RETRY_POLICY,\n DEFAULT_TIMEOUT_MS,\n isRetryableStatus,\n retryDelayMs,\n sleep,\n} from \"./retry\";\nimport { describeRuntime, isBrowser } from \"./runtime\";\nimport type {\n Fetch,\n Logger,\n LogLevel,\n Questions,\n RequestOptions,\n RetryPolicy,\n SystemOneRequest,\n SystemOneRequestPayload,\n SystemOneResult,\n TypeSafeClientConfig,\n} from \"./types\";\nimport { VERSION } from \"./version\";\n\nexport const DEFAULT_BASE_URL = \"https://api.typesafe.ai\";\nexport const DEFAULT_MODEL = \"jev-latest\";\n\n// ---------------------------------------------------------------------------\n// Construction-time checks\n// ---------------------------------------------------------------------------\n\nconst missingApiKey = (): never => {\n throw new TypeSafeError(\n `No API key was provided. Pass \\`apiKey\\` to the TypeSafeClient constructor or set the ${ENV.apiKey} environment variable.`,\n );\n};\n\nconst missingFetch = (): never => {\n throw new TypeSafeError(\n \"No global `fetch` is available in this runtime. Pass a `fetch` implementation to the TypeSafeClient constructor.\",\n );\n};\n\nconst refuseBrowser = (): never => {\n throw new TypeSafeError(\n \"TypeSafeClient is running in a browser, which would expose your API key to anyone using the page. \" +\n \"Call the API from a server instead, or pass `dangerouslyAllowBrowser: true` if you understand the risk.\",\n );\n};\n\n/** Call global `fetch` with its required receiver in browsers. */\nconst defaultFetch: Fetch = (input, init) => globalThis.fetch(input, init);\n\nconst assertNonNegativeInteger = (name: string, value: number): number => {\n if (!Number.isInteger(value) || value < 0) {\n throw new TypeSafeError(`\\`${name}\\` must be a non-negative integer, got ${String(value)}.`);\n }\n return value;\n};\n\nconst assertPositiveMs = (name: string, value: number): number => {\n if (!Number.isFinite(value) || value <= 0) {\n throw new TypeSafeError(\n `\\`${name}\\` must be a positive number of milliseconds, got ${String(value)}.`,\n );\n }\n return value;\n};\n\nconst assertNonNegativeMs = (name: string, value: number): number => {\n if (!Number.isFinite(value) || value < 0) {\n throw new TypeSafeError(\n `\\`${name}\\` must be a non-negative number of milliseconds, got ${String(value)}.`,\n );\n }\n return value;\n};\n\nconst assertFraction = (name: string, value: number): number => {\n if (!Number.isFinite(value) || value < 0 || value > 1) {\n throw new TypeSafeError(`\\`${name}\\` must be between 0 and 1, got ${String(value)}.`);\n }\n return value;\n};\n\nconst assertStatusSet = (name: string, statuses: ReadonlySet<number>): ReadonlySet<number> => {\n for (const status of statuses) {\n if (!Number.isInteger(status) || status < 100 || status > 999) {\n throw new TypeSafeError(`\\`${name}\\` must contain HTTP status codes, got ${String(status)}.`);\n }\n }\n return statuses;\n};\n\n/** Merge and validate retry overrides, copying the status set to isolate later mutations. */\nconst resolveRetryPolicy = (\n base: RetryPolicy,\n overrides: Partial<RetryPolicy> | undefined,\n): RetryPolicy => {\n const o = overrides ?? {};\n return {\n maxRetries:\n o.maxRetries === undefined\n ? base.maxRetries\n : assertNonNegativeInteger(\"retry.maxRetries\", o.maxRetries),\n backoffInitialMs:\n o.backoffInitialMs === undefined\n ? base.backoffInitialMs\n : assertNonNegativeMs(\"retry.backoffInitialMs\", o.backoffInitialMs),\n backoffMaxMs:\n o.backoffMaxMs === undefined\n ? base.backoffMaxMs\n : assertNonNegativeMs(\"retry.backoffMaxMs\", o.backoffMaxMs),\n backoffJitter:\n o.backoffJitter === undefined\n ? base.backoffJitter\n : assertFraction(\"retry.backoffJitter\", o.backoffJitter),\n httpStatuses: new Set(\n o.httpStatuses === undefined\n ? base.httpStatuses\n : assertStatusSet(\"retry.httpStatuses\", o.httpStatuses),\n ),\n respectRetryAfter: o.respectRetryAfter ?? base.respectRetryAfter,\n maxRetryAfterMs:\n o.maxRetryAfterMs === undefined\n ? base.maxRetryAfterMs\n : assertNonNegativeMs(\"retry.maxRetryAfterMs\", o.maxRetryAfterMs),\n apiConnectionError: o.apiConnectionError ?? base.apiConnectionError,\n apiTimeoutError: o.apiTimeoutError ?? base.apiTimeoutError,\n };\n};\n\n/** Whether the policy retries a connection error or timeout. */\nconst isRetryableError = (err: unknown, policy: RetryPolicy): boolean => {\n if (err instanceof APITimeoutError) return policy.apiTimeoutError;\n if (err instanceof APIConnectionError) return policy.apiConnectionError;\n return false;\n};\n\n/** Resolve and validate the log level from configuration or the environment. */\nconst resolveLogLevel = (fromCode: LogLevel | undefined): LogLevel => {\n if (fromCode !== undefined) return parseLogLevel(fromCode, \"the `logLevel` option\");\n const fromEnv = readEnv(ENV.logLevel);\n if (fromEnv !== undefined) return parseLogLevel(fromEnv, ENV.logLevel);\n return DEFAULT_LOG_LEVEL;\n};\n\nconst stripTrailingSlashes = (url: string): string => url.replace(/\\/+$/, \"\");\n\n/** Last value wins regardless of casing; undefined removes a protected header. */\nconst mergeHeaders = (\n ...sources: Readonly<Record<string, string | undefined>>[]\n): Record<string, string> => {\n const entries = new Map<string, [string, string]>();\n for (const source of sources) {\n for (const [name, value] of Object.entries(source)) {\n if (value === undefined) entries.delete(name.toLowerCase());\n else entries.set(name.toLowerCase(), [name, value]);\n }\n }\n return Object.fromEntries(entries.values());\n};\n\n/** Drain a clone so the original response retains its metadata and a readable, buffered body. */\nconst bufferResponse = async (response: Response, signal: AbortSignal): Promise<void> => {\n const reader = response.clone().body?.getReader();\n if (!reader) return;\n const cancel = (): void => {\n // Cancel both tee branches without waiting for an underlying source to acknowledge it.\n void reader.cancel(signal.reason).catch(() => {});\n void response.body?.cancel(signal.reason).catch(() => {});\n };\n signal.addEventListener(\"abort\", cancel, { once: true });\n try {\n if (signal.aborted) cancel();\n signal.throwIfAborted();\n while (!(await reader.read()).done) {\n signal.throwIfAborted();\n }\n signal.throwIfAborted();\n } finally {\n signal.removeEventListener(\"abort\", cancel);\n reader.releaseLock();\n }\n};\n\n// ---------------------------------------------------------------------------\n// Client\n// ---------------------------------------------------------------------------\n\ntype Method = \"GET\" | \"POST\";\n\n/** Per-call transport options with an optional JSON body. */\nexport interface RawRequestOptions extends RequestOptions {\n body?: unknown;\n}\n\n/** Internal transport interface used by API resources. */\nexport interface Transport {\n request<T>(method: \"GET\" | \"POST\", path: string, options?: RawRequestOptions): APIPromise<T>;\n readonly defaultModel: string;\n}\n\ninterface ResolvedRequest {\n method: Method;\n path: string;\n body: unknown;\n headers: Record<string, string>;\n signal: AbortSignal | undefined;\n timeout: number;\n retry: RetryPolicy;\n}\n\n/** Runtime description cached for the process lifetime. */\nconst RUNTIME = describeRuntime();\n\n/** Client for the TypeSafe AI API. */\nexport class TypeSafeClient {\n /** API key excluded from serialization and public properties. */\n readonly #apiKey: string;\n /** API root with trailing slashes removed. */\n readonly baseURL: string;\n /** Model used when a request omits `model`. */\n readonly defaultModel: string;\n /** Configured log verbosity. */\n readonly logLevel: LogLevel;\n /** The configured logger, filtered to `logLevel`. */\n readonly logger: Logger;\n /** Retry settings with constructor overrides applied. */\n readonly retry: RetryPolicy;\n /** Timeout per attempt in milliseconds. */\n readonly timeout: number;\n /** Additional headers sent with each request. */\n readonly defaultHeaders: Readonly<Record<string, string>>;\n /** HTTP fetch implementation. */\n readonly fetch: Fetch;\n\n /** The models available to the account. */\n readonly models: Models;\n\n #requestCount = 0;\n\n /**\n * Create a client for the TypeSafe AI API.\n *\n * Explicit options take precedence over environment variables, then SDK defaults.\n * Empty or whitespace-only environment values are ignored.\n *\n * @throws {TypeSafeError} The API key is missing, configuration is invalid, or the runtime is unsupported.\n */\n constructor(config: TypeSafeClientConfig = {}) {\n if (isBrowser() && !config.dangerouslyAllowBrowser) refuseBrowser();\n\n this.#apiKey = fromCodeOrEnv(config.apiKey, ENV.apiKey) ?? missingApiKey();\n this.baseURL = stripTrailingSlashes(\n fromCodeOrEnv(config.baseURL, ENV.baseURL) ?? DEFAULT_BASE_URL,\n );\n this.defaultModel = fromCodeOrEnv(config.defaultModel, ENV.defaultModel) ?? DEFAULT_MODEL;\n this.logLevel = resolveLogLevel(config.logLevel);\n this.logger = withLevel(config.logger ?? consoleLogger, this.logLevel);\n this.retry = resolveRetryPolicy(DEFAULT_RETRY_POLICY, config.retry);\n this.timeout = assertPositiveMs(\"timeout\", config.timeout ?? DEFAULT_TIMEOUT_MS);\n this.defaultHeaders = { ...config.defaultHeaders };\n\n if (config.fetch === undefined && typeof globalThis.fetch !== \"function\") missingFetch();\n this.fetch = config.fetch ?? defaultFetch;\n\n const transport: Transport = {\n request: (method, path, options) => this.#request(method, path, options),\n defaultModel: this.defaultModel,\n };\n this.models = new Models(transport);\n }\n\n /**\n * Answer named questions about text or structured state.\n *\n * @param request - State, questions, and an optional model override.\n * @param options - Per-call timeout, retry, headers, and cancellation settings.\n * @returns Answers typed by question name and criteria, with model and token usage.\n * @throws {TypeSafeError} Questions or score criteria are empty, or score keys are invalid.\n * @throws {APIError} The server returns a non-2xx response after retries.\n * @throws {APIConnectionError} The request cannot connect or times out after retries.\n * @throws {APIUserAbortError} The caller aborts the request.\n *\n * @example\n * ```ts\n * const { answers } = await client.systemOne({\n * state: \"I was charged twice. Please help.\",\n * questions: { billing: noul(\"Is this about billing?\") },\n * });\n * console.log(answers.billing.noul);\n * ```\n */\n systemOne<const Q extends Questions>(\n request: SystemOneRequest<Q>,\n options: RequestOptions = {},\n ): APIPromise<SystemOneResult<Q>> {\n const body = {\n ...request,\n model: request.model ?? this.defaultModel,\n questions: toWireQuestions(request.questions),\n } satisfies SystemOneRequestPayload;\n\n return this.#request<SystemOneResult<Q>>(\"POST\", \"/v1/systemone\", {\n ...options,\n body,\n });\n }\n\n /** Send a request and parse its response body. */\n #request<T>(method: Method, path: string, options: RawRequestOptions = {}): APIPromise<T> {\n const resolved: ResolvedRequest = {\n method,\n path,\n body: options.body,\n headers: mergeHeaders(this.defaultHeaders, options.headers ?? {}),\n signal: options.signal,\n timeout:\n options.timeout === undefined ? this.timeout : assertPositiveMs(\"timeout\", options.timeout),\n retry: resolveRetryPolicy(this.retry, options.retry),\n };\n // Numbered so concurrent requests, and the attempts within one, can be told apart in the logs.\n const tag = `#${++this.#requestCount} ${method} ${path}`;\n\n return new APIPromise<T>(this.fetchWithRetries(tag, resolved), async (res) => {\n const parsed = await parseBody(res);\n this.logger.debug(`${tag} <- body`, parsed);\n return parsed as T;\n });\n }\n\n /** Retry eligible failures, logging attempt summaries at `info` and headers and bodies at `debug`. */\n private async fetchWithRetries(tag: string, req: ResolvedRequest): Promise<Response> {\n const url = `${this.baseURL}${req.path}`;\n // User-supplied headers go first so they can't clobber auth or the JSON content type.\n const headers = mergeHeaders(req.headers, {\n Authorization: `Bearer ${this.#apiKey}`,\n Accept: \"application/json\",\n \"User-Agent\": `typesafe-sdk/${VERSION}`,\n \"X-TypeSafe-SDK\": `typesafe-sdk/${VERSION}`,\n \"X-TypeSafe-Runtime\": RUNTIME,\n \"Content-Type\": req.body === undefined ? undefined : \"application/json\",\n \"X-TypeSafe-Retry-Count\": undefined,\n });\n const body = req.body === undefined ? undefined : JSON.stringify(req.body);\n\n for (let attempt = 0; ; attempt++) {\n const retriesLeft = req.retry.maxRetries - attempt;\n const attemptHeaders =\n attempt === 0 ? headers : { ...headers, \"X-TypeSafe-Retry-Count\": String(attempt) };\n this.logger.debug(`${tag} -> ${url}`, {\n headers: redactHeaders(attemptHeaders),\n body: req.body,\n });\n\n const started = Date.now();\n let res: Response;\n try {\n res = await this.attempt(\n tag,\n url,\n { method: req.method, headers: attemptHeaders, body },\n req,\n );\n } catch (err) {\n if (err instanceof APIUserAbortError || retriesLeft <= 0) throw err;\n if (!isRetryableError(err, req.retry)) throw err;\n await this.backOff(tag, attempt, retriesLeft, (err as Error).message, undefined, req);\n continue;\n }\n\n const requestId = requestIdFrom(res.headers);\n this.logger.info(\n `${tag} <- ${res.status} in ${Date.now() - started}ms${requestId ? ` (request ${requestId})` : \"\"}`,\n );\n if (res.ok) return res;\n\n const errorBody = await parseBody(res);\n this.logger.debug(`${tag} <- error body`, errorBody);\n const error = APIError.fromResponse(res.status, errorBody, res.headers);\n if (retriesLeft <= 0 || !isRetryableStatus(res.status, req.retry)) throw error;\n await this.backOff(tag, attempt, retriesLeft, `${res.status}`, res.headers, req);\n }\n }\n\n /**\n * One HTTP round trip, including body delivery, with a timeout. The caller's signal and our\n * timer both abort the same controller; we check which fired to choose the error class.\n */\n private async attempt(\n tag: string,\n url: string,\n init: { method: Method; headers: Record<string, string>; body: string | undefined },\n { signal, timeout }: ResolvedRequest,\n ): Promise<Response> {\n const controller = new AbortController();\n const abortFromCaller = (): void => controller.abort(signal?.reason);\n if (signal?.aborted) abortFromCaller();\n signal?.addEventListener(\"abort\", abortFromCaller, { once: true });\n\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeout);\n\n const started = Date.now();\n const elapsed = (): string => `${Date.now() - started}ms`;\n try {\n const response = await this.fetch(url, { ...init, signal: controller.signal });\n await bufferResponse(response, controller.signal);\n return response;\n } catch (err) {\n if (signal?.aborted) {\n this.logger.info(`${tag} aborted by caller after ${elapsed()}`);\n throw new APIUserAbortError(undefined, { cause: err });\n }\n if (timedOut) {\n this.logger.info(`${tag} timed out after ${elapsed()}`);\n throw new APITimeoutError(timeout, { cause: err });\n }\n this.logger.info(`${tag} connection error after ${elapsed()}`, err);\n throw new APIConnectionError(\n err instanceof Error ? `Connection error: ${err.message}` : undefined,\n { cause: err },\n );\n } finally {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", abortFromCaller);\n }\n }\n\n /** Wait before retrying; caller cancellation throws `APIUserAbortError`. */\n private async backOff(\n tag: string,\n attempt: number,\n retriesLeft: number,\n reason: string,\n headers: Headers | undefined,\n { retry, signal }: ResolvedRequest,\n ): Promise<void> {\n const delay = retryDelayMs(attempt, headers, retry);\n const nth = attempt + 1;\n const total = attempt + retriesLeft;\n this.logger.info(`${tag} retrying in ${delay}ms (retry ${nth}/${total}) after ${reason}`);\n try {\n await sleep(delay, signal);\n } catch (err) {\n this.logger.info(`${tag} aborted by caller while waiting to retry`);\n throw new APIUserAbortError(undefined, { cause: err });\n }\n }\n}\n\nconst parseBody = async (res: Response): Promise<unknown> => {\n const text = await res.text();\n if (text.length === 0) return undefined;\n const contentType = res.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"application/json\")) {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n // Be lenient: servers and proxies don't always set content-type.\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n};\n"],"mappings":";AAEA,MAAa,iBAAiB,YAC5B,QAAQ,IAAA,uBAAqB,KAAK,KAAA;;;;;;AAiBpC,IAAa,aAAb,MAAa,mBAAsB,QAAW;CAC5C;CACA;CACA;CAEA,YACE,iBACA,eACA;EAEA,OAAO,YAAY,QAAQ,KAAA,CAAc,CAAC;EAC1C,KAAK,mBAAmB;EACxB,KAAK,iBAAiB;CACx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AAI,eAAe,MAAM,YAAY,IAAI,GAAG,MAAM,UAAU,QAAQ;EACxF,IAAI;GACF,MAAM,MAAM,OAAO,MAAM;EAC3B,SAAS,KAAK;GACZ,KAAK,OAAO,KAAK,GAAG,IAAI,0CAA0C;GAClE,MAAM,IAAI,kBAAkB,KAAA,GAAW,EAAE,OAAO,IAAI,CAAC;EACvD;CACF;AACF;AAEA,MAAM,YAAY,OAAO,QAAoC;CAC3D,MAAM,OAAO,MAAM,IAAI,KAAK;CAC5B,IAAI,KAAK,WAAW,GAAG,OAAO,KAAA;CAE9B,KADoB,IAAI,QAAQ,IAAI,cAAc,KAAK,GAAA,CACvC,SAAS,kBAAkB,GACzC,IAAI;EACF,OAAO,KAAK,MAAM,IAAI;CACxB,QAAQ;EACN,OAAO;CACT;CAGF,IAAI;EACF,OAAO,KAAK,MAAM,IAAI;CACxB,QAAQ;EACN,OAAO;CACT;AACF"}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
//#region src/api-promise.d.ts
|
|
2
|
+
/** Parsed data with its HTTP response and request ID. */
|
|
3
|
+
interface WithResponse<T> {
|
|
4
|
+
/** The parsed response body. */
|
|
5
|
+
data: T;
|
|
6
|
+
/** The HTTP response, with its body consumed by parsing. */
|
|
7
|
+
response: Response;
|
|
8
|
+
/** Request ID from `x-typesafe-request-id`, or `undefined` when absent. */
|
|
9
|
+
requestId: string | undefined;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* A promise for the parsed result with access to the HTTP response.
|
|
13
|
+
*
|
|
14
|
+
* Non-2xx responses reject with an `APIError`, including through `asResponse()`.
|
|
15
|
+
*/
|
|
16
|
+
declare class APIPromise<T> extends Promise<T> {
|
|
17
|
+
#private;
|
|
18
|
+
constructor(responsePromise: Promise<Response>, parseResponse: (response: Response) => Promise<T>);
|
|
19
|
+
/**
|
|
20
|
+
* Resolves to the raw `Response` without parsing the body. SDK requests buffer the full
|
|
21
|
+
* body under the request timeout before handoff; reading it afterwards is caller-owned.
|
|
22
|
+
* The caller owns the body; don't also `await` the parsed result on the same promise.
|
|
23
|
+
*/
|
|
24
|
+
asResponse(): Promise<Response>;
|
|
25
|
+
/** Return the parsed result, HTTP response, and request ID. */
|
|
26
|
+
withResponse(): Promise<WithResponse<T>>;
|
|
27
|
+
/** Transform the parsed result, sharing the HTTP response and a single body parse. */
|
|
28
|
+
map<U>(fn: (data: T) => U): APIPromise<U>;
|
|
29
|
+
override then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
|
|
30
|
+
override catch<TResult = never>(onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null): Promise<T | TResult>;
|
|
31
|
+
override finally(onfinally?: (() => void) | null): Promise<T>;
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
//#region src/types.d.ts
|
|
35
|
+
/** A JSON-compatible value. */
|
|
36
|
+
type JsonValue = string | number | boolean | null | JsonValue[] | {
|
|
37
|
+
[key: string]: JsonValue;
|
|
38
|
+
};
|
|
39
|
+
/** Text, a JSON object or array, or `null` for state, instructions, and criteria. */
|
|
40
|
+
type EntryType = string | {
|
|
41
|
+
[key: string]: JsonValue;
|
|
42
|
+
} | JsonValue[] | null;
|
|
43
|
+
/** A criterion description; `null` leaves the label undescribed. */
|
|
44
|
+
type Description = EntryType;
|
|
45
|
+
/** A yes/no question with optional descriptions for either outcome. */
|
|
46
|
+
interface NoulQuestion {
|
|
47
|
+
type: "noul";
|
|
48
|
+
/** The question as text, a JSON object, or an array; optional or `null`. */
|
|
49
|
+
instructions?: EntryType;
|
|
50
|
+
/** Optional descriptions of the yes and no outcomes. */
|
|
51
|
+
criteria?: {
|
|
52
|
+
/** Description of the yes outcome. */
|
|
53
|
+
true?: EntryType;
|
|
54
|
+
/** Description of the no outcome. */
|
|
55
|
+
false?: EntryType;
|
|
56
|
+
} | null;
|
|
57
|
+
}
|
|
58
|
+
/** Labels mapped to descriptions, or `null` for undescribed labels. */
|
|
59
|
+
type ChoiceCriteria = {
|
|
60
|
+
[label: string]: Description;
|
|
61
|
+
};
|
|
62
|
+
/** A question that selects between named alternatives. */
|
|
63
|
+
interface ChoiceQuestion<T extends ChoiceCriteria = ChoiceCriteria> {
|
|
64
|
+
type: "choice";
|
|
65
|
+
/** The question as text, a JSON object, or an array; optional or `null`. */
|
|
66
|
+
instructions?: EntryType;
|
|
67
|
+
/** Descriptions of the available outcomes. */
|
|
68
|
+
criteria: T;
|
|
69
|
+
}
|
|
70
|
+
/** A nonempty array indexed by score from zero; `null` leaves a score undescribed. */
|
|
71
|
+
type ScoreList = readonly [EntryType, ...EntryType[]];
|
|
72
|
+
/** Score descriptions keyed from zero with no gaps; `null` leaves a score undescribed. */
|
|
73
|
+
type ScoreMap = {
|
|
74
|
+
readonly [score: number]: EntryType;
|
|
75
|
+
};
|
|
76
|
+
/** An ordered rubric expressed as an array or score map. */
|
|
77
|
+
type ScoreCriteria = ScoreList | ScoreMap;
|
|
78
|
+
/** A question that assigns a score using an ordered rubric. */
|
|
79
|
+
interface ScoreQuestion<T extends ScoreCriteria = ScoreCriteria> {
|
|
80
|
+
type: "score";
|
|
81
|
+
/** The question as text, a JSON object, or an array; optional or `null`. */
|
|
82
|
+
instructions?: EntryType;
|
|
83
|
+
/** Descriptions of the available outcomes. */
|
|
84
|
+
criteria: T;
|
|
85
|
+
}
|
|
86
|
+
/** A question identified by its `type` field. */
|
|
87
|
+
type Question = NoulQuestion | ScoreQuestion | ChoiceQuestion;
|
|
88
|
+
/** Questions keyed by the names used to identify their answers. */
|
|
89
|
+
interface Questions {
|
|
90
|
+
[name: string]: Question;
|
|
91
|
+
}
|
|
92
|
+
/** A yes/no answer. */
|
|
93
|
+
interface NoulResponse {
|
|
94
|
+
readonly type: "noul";
|
|
95
|
+
/** Probability of a yes answer, from zero to one. */
|
|
96
|
+
readonly noul: number;
|
|
97
|
+
}
|
|
98
|
+
/** A selected label and its probabilities. */
|
|
99
|
+
interface ChoiceResponse<T extends ChoiceCriteria = ChoiceCriteria> {
|
|
100
|
+
readonly type: "choice";
|
|
101
|
+
/** The selected label. */
|
|
102
|
+
readonly choice: keyof T & string;
|
|
103
|
+
/** Reported confidence in the selected label. */
|
|
104
|
+
readonly confidence: number;
|
|
105
|
+
/** Probabilities keyed by label. */
|
|
106
|
+
readonly probabilities: { readonly [label in keyof T]: number; };
|
|
107
|
+
}
|
|
108
|
+
/** Score keys inferred from the rubric; tuple keys are numeric strings, map keys are numbers. */
|
|
109
|
+
type ScoreOf<T extends ScoreCriteria> = T extends readonly unknown[] ? number extends T["length"] ? number : Extract<keyof T, `${number}`> : Extract<keyof T, number>;
|
|
110
|
+
/** Rubric descriptions keyed by score. */
|
|
111
|
+
type ScoreLegend<T extends ScoreCriteria> = { readonly [score in ScoreOf<T>]: T[score]; };
|
|
112
|
+
/** An expected score with its rubric and probabilities. */
|
|
113
|
+
interface ScoreResponse<T extends ScoreCriteria = ScoreCriteria> {
|
|
114
|
+
readonly type: "score";
|
|
115
|
+
/** Expected score, which may fall between integer rubric levels. */
|
|
116
|
+
readonly score: number;
|
|
117
|
+
/** Reported confidence in the score. */
|
|
118
|
+
readonly confidence: number;
|
|
119
|
+
/** Rubric descriptions keyed by score. */
|
|
120
|
+
readonly legend: ScoreLegend<T>;
|
|
121
|
+
/** Probabilities keyed by score. */
|
|
122
|
+
readonly probabilities: { readonly [score in ScoreOf<T>]: number; };
|
|
123
|
+
}
|
|
124
|
+
/** The answer type for a question, preserving its criteria keys. */
|
|
125
|
+
type ResultFor<T extends Question> = T extends NoulQuestion ? NoulResponse : T extends ScoreQuestion<infer S> ? ScoreResponse<S> : T extends ChoiceQuestion<infer E> ? ChoiceResponse<E> : never;
|
|
126
|
+
/** Token usage for a request. */
|
|
127
|
+
interface Usage {
|
|
128
|
+
/** Number of input tokens used. */
|
|
129
|
+
readonly input_tokens: number;
|
|
130
|
+
/** Number of output tokens used. */
|
|
131
|
+
readonly output_tokens: number;
|
|
132
|
+
}
|
|
133
|
+
/** Answers keyed by question name, with model and usage metadata. */
|
|
134
|
+
interface SystemOneResult<Q extends Questions> {
|
|
135
|
+
/** The model used to answer the request. */
|
|
136
|
+
readonly model: string;
|
|
137
|
+
/** Answers with types inferred from the supplied questions. */
|
|
138
|
+
readonly answers: { readonly [K in keyof Q]: ResultFor<Q[K]>; };
|
|
139
|
+
/** Token usage for the request. */
|
|
140
|
+
readonly usage: Usage;
|
|
141
|
+
}
|
|
142
|
+
/** Metadata for an available model. */
|
|
143
|
+
interface ModelCard {
|
|
144
|
+
readonly name: string;
|
|
145
|
+
readonly description: string;
|
|
146
|
+
readonly release_date: string;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* State and named questions for `systemOne`.
|
|
150
|
+
*
|
|
151
|
+
* Additional properties on a request variable are forwarded, including `null` values.
|
|
152
|
+
* Score maps are converted to arrays before sending.
|
|
153
|
+
*/
|
|
154
|
+
interface SystemOneRequest<Q extends Questions = Questions> {
|
|
155
|
+
/** Text, a JSON object or array, or `null` to evaluate. */
|
|
156
|
+
state: EntryType;
|
|
157
|
+
/** Nonempty questions keyed by the names used to identify their answers. */
|
|
158
|
+
questions: Q;
|
|
159
|
+
/** Model override; omitted values inherit `defaultModel`. */
|
|
160
|
+
model?: string;
|
|
161
|
+
}
|
|
162
|
+
/** Request body for `POST /v1/systemone`, with the model resolved. */
|
|
163
|
+
interface SystemOneRequestPayload extends SystemOneRequest {
|
|
164
|
+
model: string;
|
|
165
|
+
}
|
|
166
|
+
/** Retry configuration. Partial overrides inherit unset fields from the client or SDK defaults. */
|
|
167
|
+
interface RetryPolicy {
|
|
168
|
+
/** Maximum retries after the initial attempt; `0` disables retries. Default: 2. */
|
|
169
|
+
readonly maxRetries: number;
|
|
170
|
+
/** First backoff delay in milliseconds, doubled up to `backoffMaxMs`. Default: 500. */
|
|
171
|
+
readonly backoffInitialMs: number;
|
|
172
|
+
/** Maximum backoff delay in milliseconds. Default: 5000. */
|
|
173
|
+
readonly backoffMaxMs: number;
|
|
174
|
+
/** Fraction of each backoff delay randomly subtracted, from 0 to 1. Default: 0.25. */
|
|
175
|
+
readonly backoffJitter: number;
|
|
176
|
+
/** HTTP status codes to retry. Default: 408, 429, and 500–599. */
|
|
177
|
+
readonly httpStatuses: ReadonlySet<number>;
|
|
178
|
+
/** Honor `Retry-After` and `retry-after-ms` up to `maxRetryAfterMs`. Default: true. */
|
|
179
|
+
readonly respectRetryAfter: boolean;
|
|
180
|
+
/** Maximum server retry delay in milliseconds; longer delays use backoff. Default: 60000. */
|
|
181
|
+
readonly maxRetryAfterMs: number;
|
|
182
|
+
/** Retry connection failures, including interrupted response bodies (`APIConnectionError`). Default: true. */
|
|
183
|
+
readonly apiConnectionError: boolean;
|
|
184
|
+
/** Whether to retry `APITimeoutError`. Default: true. */
|
|
185
|
+
readonly apiTimeoutError: boolean;
|
|
186
|
+
}
|
|
187
|
+
/** Per-call options that override client settings. */
|
|
188
|
+
interface RequestOptions {
|
|
189
|
+
/** Cancellation signal for the request and pending retries. */
|
|
190
|
+
signal?: AbortSignal;
|
|
191
|
+
/** Timeout per attempt in milliseconds; there is no total retry budget. */
|
|
192
|
+
timeout?: number;
|
|
193
|
+
/** Retry overrides for this call; omitted fields inherit client settings. */
|
|
194
|
+
retry?: Partial<RetryPolicy>;
|
|
195
|
+
/** Additional headers, merged over `defaultHeaders`. */
|
|
196
|
+
headers?: Record<string, string>;
|
|
197
|
+
}
|
|
198
|
+
/** HTTP fetch implementation compatible with the global `fetch`. */
|
|
199
|
+
type Fetch = (input: string, init?: RequestInit) => Promise<Response>;
|
|
200
|
+
/** Log verbosity; `off` disables logging. */
|
|
201
|
+
type LogLevel = "debug" | "info" | "warn" | "error" | "off";
|
|
202
|
+
/** Log methods accepting a message and structured values; compatible with `console`. */
|
|
203
|
+
interface Logger {
|
|
204
|
+
debug(message: string, ...args: unknown[]): void;
|
|
205
|
+
info(message: string, ...args: unknown[]): void;
|
|
206
|
+
warn(message: string, ...args: unknown[]): void;
|
|
207
|
+
error(message: string, ...args: unknown[]): void;
|
|
208
|
+
}
|
|
209
|
+
/** Client options. Explicit values take precedence over environment variables, then SDK defaults. */
|
|
210
|
+
interface TypeSafeClientConfig {
|
|
211
|
+
/** Required API key; falls back to `TYPESAFE_API_KEY`. */
|
|
212
|
+
apiKey?: string;
|
|
213
|
+
/** API root; falls back to `TYPESAFE_BASE_URL`, then `https://api.typesafe.ai`. */
|
|
214
|
+
baseURL?: string;
|
|
215
|
+
/** Default model; falls back to `TYPESAFE_DEFAULT_MODEL`, then `jev-latest`. */
|
|
216
|
+
defaultModel?: string;
|
|
217
|
+
/**
|
|
218
|
+
* Log level; falls back to `TYPESAFE_LOG_LEVEL`, then `warn`.
|
|
219
|
+
* `info` logs request summaries; `debug` adds headers and bodies.
|
|
220
|
+
* Known credential headers are redacted; bodies are not.
|
|
221
|
+
*/
|
|
222
|
+
logLevel?: LogLevel;
|
|
223
|
+
/** Logger filtered to `logLevel` and above. Default: prefixed `console`. */
|
|
224
|
+
logger?: Logger;
|
|
225
|
+
/** Retry overrides; omitted fields use the defaults in `RetryPolicy`. */
|
|
226
|
+
retry?: Partial<RetryPolicy>;
|
|
227
|
+
/** Timeout per attempt in milliseconds, without a total retry budget. Default: 10000. */
|
|
228
|
+
timeout?: number;
|
|
229
|
+
/** Additional request headers; per-call headers take precedence. */
|
|
230
|
+
defaultHeaders?: Record<string, string>;
|
|
231
|
+
/** Allow browser use, exposing the API key to page users. Default: false. */
|
|
232
|
+
dangerouslyAllowBrowser?: boolean;
|
|
233
|
+
/** Custom HTTP fetch implementation for transport configuration or tests. Default: global `fetch`. */
|
|
234
|
+
fetch?: Fetch;
|
|
235
|
+
}
|
|
236
|
+
//#endregion
|
|
237
|
+
//#region src/resources/models.d.ts
|
|
238
|
+
/** Access to the Models API resource. */
|
|
239
|
+
declare class Models {
|
|
240
|
+
#private;
|
|
241
|
+
constructor(transport: Transport);
|
|
242
|
+
/** List the models available to the account. */
|
|
243
|
+
list(options?: RequestOptions): APIPromise<ModelCard[]>;
|
|
244
|
+
}
|
|
245
|
+
//#endregion
|
|
246
|
+
//#region src/client.d.ts
|
|
247
|
+
/** Per-call transport options with an optional JSON body. */
|
|
248
|
+
interface RawRequestOptions extends RequestOptions {
|
|
249
|
+
body?: unknown;
|
|
250
|
+
}
|
|
251
|
+
/** Internal transport interface used by API resources. */
|
|
252
|
+
interface Transport {
|
|
253
|
+
request<T>(method: "GET" | "POST", path: string, options?: RawRequestOptions): APIPromise<T>;
|
|
254
|
+
readonly defaultModel: string;
|
|
255
|
+
}
|
|
256
|
+
/** Client for the TypeSafe AI API. */
|
|
257
|
+
declare class TypeSafeClient {
|
|
258
|
+
#private;
|
|
259
|
+
/** API root with trailing slashes removed. */
|
|
260
|
+
readonly baseURL: string;
|
|
261
|
+
/** Model used when a request omits `model`. */
|
|
262
|
+
readonly defaultModel: string;
|
|
263
|
+
/** Configured log verbosity. */
|
|
264
|
+
readonly logLevel: LogLevel;
|
|
265
|
+
/** The configured logger, filtered to `logLevel`. */
|
|
266
|
+
readonly logger: Logger;
|
|
267
|
+
/** Retry settings with constructor overrides applied. */
|
|
268
|
+
readonly retry: RetryPolicy;
|
|
269
|
+
/** Timeout per attempt in milliseconds. */
|
|
270
|
+
readonly timeout: number;
|
|
271
|
+
/** Additional headers sent with each request. */
|
|
272
|
+
readonly defaultHeaders: Readonly<Record<string, string>>;
|
|
273
|
+
/** HTTP fetch implementation. */
|
|
274
|
+
readonly fetch: Fetch;
|
|
275
|
+
/** The models available to the account. */
|
|
276
|
+
readonly models: Models;
|
|
277
|
+
/**
|
|
278
|
+
* Create a client for the TypeSafe AI API.
|
|
279
|
+
*
|
|
280
|
+
* Explicit options take precedence over environment variables, then SDK defaults.
|
|
281
|
+
* Empty or whitespace-only environment values are ignored.
|
|
282
|
+
*
|
|
283
|
+
* @throws {TypeSafeError} The API key is missing, configuration is invalid, or the runtime is unsupported.
|
|
284
|
+
*/
|
|
285
|
+
constructor(config?: TypeSafeClientConfig);
|
|
286
|
+
/**
|
|
287
|
+
* Answer named questions about text or structured state.
|
|
288
|
+
*
|
|
289
|
+
* @param request - State, questions, and an optional model override.
|
|
290
|
+
* @param options - Per-call timeout, retry, headers, and cancellation settings.
|
|
291
|
+
* @returns Answers typed by question name and criteria, with model and token usage.
|
|
292
|
+
* @throws {TypeSafeError} Questions or score criteria are empty, or score keys are invalid.
|
|
293
|
+
* @throws {APIError} The server returns a non-2xx response after retries.
|
|
294
|
+
* @throws {APIConnectionError} The request cannot connect or times out after retries.
|
|
295
|
+
* @throws {APIUserAbortError} The caller aborts the request.
|
|
296
|
+
*
|
|
297
|
+
* @example
|
|
298
|
+
* ```ts
|
|
299
|
+
* const { answers } = await client.systemOne({
|
|
300
|
+
* state: "I was charged twice. Please help.",
|
|
301
|
+
* questions: { billing: noul("Is this about billing?") },
|
|
302
|
+
* });
|
|
303
|
+
* console.log(answers.billing.noul);
|
|
304
|
+
* ```
|
|
305
|
+
*/
|
|
306
|
+
systemOne<const Q extends Questions>(request: SystemOneRequest<Q>, options?: RequestOptions): APIPromise<SystemOneResult<Q>>;
|
|
307
|
+
/** Retry eligible failures, logging attempt summaries at `info` and headers and bodies at `debug`. */
|
|
308
|
+
private fetchWithRetries;
|
|
309
|
+
/**
|
|
310
|
+
* One HTTP round trip, including body delivery, with a timeout. The caller's signal and our
|
|
311
|
+
* timer both abort the same controller; we check which fired to choose the error class.
|
|
312
|
+
*/
|
|
313
|
+
private attempt;
|
|
314
|
+
/** Wait before retrying; caller cancellation throws `APIUserAbortError`. */
|
|
315
|
+
private backOff;
|
|
316
|
+
}
|
|
317
|
+
//#endregion
|
|
318
|
+
//#region src/env.d.ts
|
|
319
|
+
/** Environment variable names for client configuration. Explicit options take precedence. */
|
|
320
|
+
declare const ENV: {
|
|
321
|
+
/** Required API key; used when `apiKey` is omitted. */
|
|
322
|
+
readonly apiKey: "TYPESAFE_API_KEY";
|
|
323
|
+
/** API root; defaults to `https://api.typesafe.ai`. */
|
|
324
|
+
readonly baseURL: "TYPESAFE_BASE_URL";
|
|
325
|
+
/** Default model name; defaults to `jev-latest`. */
|
|
326
|
+
readonly defaultModel: "TYPESAFE_DEFAULT_MODEL";
|
|
327
|
+
/** Log level; defaults to `warn`. */
|
|
328
|
+
readonly logLevel: "TYPESAFE_LOG_LEVEL";
|
|
329
|
+
};
|
|
330
|
+
type EnvVar = (typeof ENV)[keyof typeof ENV];
|
|
331
|
+
//#endregion
|
|
332
|
+
//#region src/errors.d.ts
|
|
333
|
+
/** Base class for SDK errors. */
|
|
334
|
+
declare class TypeSafeError extends Error {
|
|
335
|
+
constructor(message: string, options?: ErrorOptions);
|
|
336
|
+
}
|
|
337
|
+
/** An unsuccessful HTTP response from the API. */
|
|
338
|
+
declare class APIError extends TypeSafeError {
|
|
339
|
+
/** HTTP response status code. */
|
|
340
|
+
readonly status: number;
|
|
341
|
+
/** HTTP response headers. */
|
|
342
|
+
readonly headers: Headers;
|
|
343
|
+
/** Parsed JSON, response text, or `undefined` for an empty body. */
|
|
344
|
+
readonly body: unknown;
|
|
345
|
+
/** Request ID from `x-typesafe-request-id`, or `undefined` when absent. */
|
|
346
|
+
readonly requestId: string | undefined;
|
|
347
|
+
constructor(status: number, body: unknown, headers: Headers, message?: string);
|
|
348
|
+
private static describe;
|
|
349
|
+
/** Create the error subclass for an HTTP status code. */
|
|
350
|
+
static fromResponse(status: number, body: unknown, headers: Headers): APIError;
|
|
351
|
+
}
|
|
352
|
+
/** HTTP 400: the request is invalid. */
|
|
353
|
+
declare class BadRequestError extends APIError {}
|
|
354
|
+
/** HTTP 401: authentication failed. */
|
|
355
|
+
declare class AuthenticationError extends APIError {}
|
|
356
|
+
/** HTTP 403: access is denied. */
|
|
357
|
+
declare class PermissionDeniedError extends APIError {}
|
|
358
|
+
/** HTTP 404: the resource was not found. */
|
|
359
|
+
declare class NotFoundError extends APIError {}
|
|
360
|
+
/** HTTP 422: request validation failed. */
|
|
361
|
+
declare class UnprocessableEntityError extends APIError {}
|
|
362
|
+
/** HTTP 429: the rate limit was exceeded. */
|
|
363
|
+
declare class RateLimitError extends APIError {
|
|
364
|
+
/** Server retry delay in milliseconds, or `undefined` when absent or invalid. */
|
|
365
|
+
readonly retryAfterMs: number | undefined;
|
|
366
|
+
}
|
|
367
|
+
/** HTTP 5xx: the server failed to handle the request. */
|
|
368
|
+
declare class InternalServerError extends APIError {}
|
|
369
|
+
/** The request or response-body delivery failed (DNS, TLS, connection closed, etc.). */
|
|
370
|
+
declare class APIConnectionError extends TypeSafeError {
|
|
371
|
+
constructor(message?: string, options?: ErrorOptions);
|
|
372
|
+
}
|
|
373
|
+
/** The full response did not arrive within the timeout. A kind of `APIConnectionError`. */
|
|
374
|
+
declare class APITimeoutError extends APIConnectionError {
|
|
375
|
+
/** Configured timeout in milliseconds. */
|
|
376
|
+
readonly timeoutMs: number;
|
|
377
|
+
constructor(timeoutMs: number, options?: ErrorOptions);
|
|
378
|
+
}
|
|
379
|
+
/** The caller cancelled the request through an `AbortSignal`. */
|
|
380
|
+
declare class APIUserAbortError extends TypeSafeError {
|
|
381
|
+
constructor(message?: string, options?: ErrorOptions);
|
|
382
|
+
}
|
|
383
|
+
//#endregion
|
|
384
|
+
//#region src/logging.d.ts
|
|
385
|
+
/** Supported log levels, from most to least verbose. */
|
|
386
|
+
declare const LOG_LEVELS: readonly LogLevel[];
|
|
387
|
+
//#endregion
|
|
388
|
+
//#region src/questions.d.ts
|
|
389
|
+
/**
|
|
390
|
+
* Create a yes/no question with optional descriptions for either outcome.
|
|
391
|
+
*
|
|
392
|
+
* @param instructions - The question as text, a JSON object or array; defaults to `null`.
|
|
393
|
+
* @param criteria - Optional descriptions of the yes and no outcomes.
|
|
394
|
+
*/
|
|
395
|
+
declare const noul: (instructions?: EntryType, criteria?: NoulQuestion["criteria"]) => NoulQuestion;
|
|
396
|
+
/**
|
|
397
|
+
* Create a score question using an ordered rubric.
|
|
398
|
+
*
|
|
399
|
+
* @param instructions - The question as text, a JSON object or array, or `null`.
|
|
400
|
+
* @param criteria - A nonempty array or map indexed from zero with no gaps; descriptions may be `null`.
|
|
401
|
+
*/
|
|
402
|
+
declare const score$1: <const T extends ScoreCriteria>(instructions: EntryType, criteria: T) => ScoreQuestion<T>;
|
|
403
|
+
/**
|
|
404
|
+
* Create a question that selects between named alternatives.
|
|
405
|
+
*
|
|
406
|
+
* @param instructions - The question as text, a JSON object or array, or `null`.
|
|
407
|
+
* @param criteria - Labels mapped to descriptions, or `null` for undescribed labels.
|
|
408
|
+
*/
|
|
409
|
+
declare const choice: <const T extends ChoiceCriteria>(instructions: EntryType, criteria: T) => ChoiceQuestion<T>;
|
|
410
|
+
//#endregion
|
|
411
|
+
//#region src/version.d.ts
|
|
412
|
+
declare const VERSION = "0.5.7";
|
|
413
|
+
//#endregion
|
|
414
|
+
export { APIConnectionError, APIError, APIPromise, APITimeoutError, APIUserAbortError, AuthenticationError, BadRequestError, type ChoiceCriteria, type ChoiceQuestion, type ChoiceResponse, type Description, ENV, type EntryType, type EnvVar, type Fetch, InternalServerError, type JsonValue, LOG_LEVELS, type LogLevel, type Logger, type ModelCard, type Models, NotFoundError, type NoulQuestion, type NoulResponse, PermissionDeniedError, type Question, type Questions, RateLimitError, type RequestOptions, type ResultFor, type RetryPolicy, type ScoreCriteria, type ScoreLegend, type ScoreList, type ScoreMap, type ScoreOf, type ScoreQuestion, type ScoreResponse, type SystemOneRequest, type SystemOneRequestPayload, type SystemOneResult, TypeSafeClient, type TypeSafeClientConfig, TypeSafeError, UnprocessableEntityError, type Usage, VERSION, type WithResponse, choice, noul, score$1 as score };
|
|
415
|
+
//# sourceMappingURL=index.d.cts.map
|