@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.
@@ -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.mts.map