@gradiated/grad 0.0.0-stage → 0.2.0-alpha.1

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.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +83 -2
  3. package/dist/client.d.ts +71 -0
  4. package/dist/client.js +188 -0
  5. package/dist/config.d.ts +21 -0
  6. package/dist/config.js +90 -0
  7. package/dist/core.d.ts +13 -0
  8. package/dist/core.js +1 -0
  9. package/dist/errors.d.ts +37 -0
  10. package/dist/errors.js +70 -0
  11. package/dist/generated/client.d.ts +532 -0
  12. package/dist/generated/client.js +596 -0
  13. package/dist/generated/index.d.ts +2 -0
  14. package/dist/generated/index.js +3 -0
  15. package/dist/generated/models.d.ts +998 -0
  16. package/dist/generated/models.js +9 -0
  17. package/dist/index.d.ts +19 -0
  18. package/dist/index.js +16 -0
  19. package/dist/node/files.d.ts +26 -0
  20. package/dist/node/files.js +130 -0
  21. package/dist/pagination.d.ts +39 -0
  22. package/dist/pagination.js +73 -0
  23. package/dist/pending.d.ts +14 -0
  24. package/dist/pending.js +20 -0
  25. package/dist/polling.d.ts +25 -0
  26. package/dist/polling.js +63 -0
  27. package/dist/recipes.d.ts +220 -0
  28. package/dist/recipes.js +255 -0
  29. package/dist/resources/artifacts.d.ts +82 -0
  30. package/dist/resources/artifacts.js +122 -0
  31. package/dist/resources/datasets.d.ts +178 -0
  32. package/dist/resources/datasets.js +318 -0
  33. package/dist/resources/evals.d.ts +110 -0
  34. package/dist/resources/evals.js +258 -0
  35. package/dist/resources/misc.d.ts +31 -0
  36. package/dist/resources/misc.js +45 -0
  37. package/dist/resources/runs.d.ts +119 -0
  38. package/dist/resources/runs.js +245 -0
  39. package/dist/resources/sources.d.ts +118 -0
  40. package/dist/resources/sources.js +156 -0
  41. package/dist/rubrics.d.ts +87 -0
  42. package/dist/rubrics.js +167 -0
  43. package/dist/trajectory.d.ts +16 -0
  44. package/dist/trajectory.js +13 -0
  45. package/dist/transport.d.ts +229 -0
  46. package/dist/transport.js +678 -0
  47. package/package.json +53 -4
@@ -0,0 +1,156 @@
1
+ import { GradUsageError } from "../errors.js";
2
+ import { Paginator } from "../pagination.js";
3
+ import { Pending } from "../pending.js";
4
+ import { datasetName, ImportJob } from "./datasets.js";
5
+ export class SecretRef {
6
+ constructor(data) {
7
+ Object.assign(this, data);
8
+ }
9
+ toString() {
10
+ return this.name;
11
+ }
12
+ }
13
+ export const secretName = (secret) => {
14
+ const name = typeof secret === "string" ? secret : secret?.name;
15
+ if (typeof name !== "string" || name === "") {
16
+ throw new GradUsageError("secret must be a SecretRef from grad.secrets.get(...) or a secret name.", "invalid_secret");
17
+ }
18
+ return name;
19
+ };
20
+ const provider = (kind, options = {}) => ({
21
+ kind,
22
+ ...(options.host !== undefined ? { host: options.host } : {}),
23
+ ...(options.secret !== undefined ? { secret: secretName(options.secret) } : {}),
24
+ ...(options.project !== undefined ? { project: options.project } : {}),
25
+ ...(options.filters !== undefined && Object.keys(options.filters).length > 0 ? { filters: options.filters } : {}),
26
+ });
27
+ /**
28
+ * Observability providers a dataset can sync from:
29
+ * `dataset.addSource({ provider: sources.langfuse({ host, secret }), schedule: "*\/15 * * * *" })`.
30
+ */
31
+ export const sources = {
32
+ /** Langfuse traces and scores; the secret is `PUBLIC_KEY:SECRET_KEY`. */
33
+ langfuse: (options) => provider("langfuse", options),
34
+ /** LangSmith runs and feedback, including corrections. */
35
+ langsmith: (options) => provider("langsmith", options),
36
+ /** Braintrust project logs, scores and `expected` answers (`project` is required). */
37
+ braintrust: (options) => provider("braintrust", options),
38
+ /** PostHog LLM events and survey feedback (`project` is the numeric project id). */
39
+ posthog: (options) => provider("posthog", options),
40
+ /** Arize Phoenix spans and annotations (`host` is required). */
41
+ phoenix: (options) => provider("phoenix", options),
42
+ /** Gradiated Cloud gateway traces and feedback (Cloud only; no host or secret). */
43
+ gradiated: (options = {}) => {
44
+ const filters = { ...(options.filters ?? {}) };
45
+ for (const key of ["models", "tasks", "versions"]) {
46
+ const values = options[key];
47
+ if (values && values.length > 0)
48
+ filters[key] = values;
49
+ }
50
+ return provider("gradiated", { filters });
51
+ },
52
+ };
53
+ export class Source {
54
+ #core;
55
+ constructor(core, data) {
56
+ this.#core = core;
57
+ Object.assign(this, data);
58
+ }
59
+ async refresh(options) {
60
+ Object.assign(this, await this.#core.api.getSource(this.id, options));
61
+ return this;
62
+ }
63
+ /**
64
+ * Syncs now; `await source.sync().wait()` blocks until the new version exists.
65
+ * `full: true` rebuilds the dataset from the provider. A sync in progress is returned as is
66
+ * (a full request then runs right after it); within a minute of the last sync's start, that
67
+ * sync is returned. Resumes a paused source.
68
+ */
69
+ sync(options = {}) {
70
+ return new Pending(syncSource(this.#core, this.id, options));
71
+ }
72
+ /** Disconnects the source; the dataset and its versions stay. */
73
+ async remove(options) {
74
+ await this.#core.api.deleteSource(this.id, options);
75
+ }
76
+ toJSON() {
77
+ return { ...this };
78
+ }
79
+ }
80
+ const syncSource = async (core, id, options) => {
81
+ const { full = false, ...request } = options;
82
+ return new ImportJob(core, await core.api.syncSource(id, { full }, request));
83
+ };
84
+ export const addSource = async (core, dataset, options) => {
85
+ const { provider: body, schedule, ...request } = options;
86
+ const data = await core.api.createDatasetSource(datasetName(dataset), { provider: body, ...(schedule !== undefined ? { schedule } : {}) }, request);
87
+ return new Source(core, data);
88
+ };
89
+ export class SecretsResource {
90
+ core;
91
+ constructor(core) {
92
+ this.core = core;
93
+ }
94
+ /**
95
+ * Creates or replaces a secret. The value is encrypted at rest and never returned.
96
+ * `allowedHosts` are the only hosts the server sends it to (a source's host,
97
+ * huggingface.co for HF imports, a logger's host); leave it out for the public
98
+ * provider hosts. A secret for a self-hosted tool must name its host.
99
+ */
100
+ async set(name, value, options = {}) {
101
+ if (typeof value !== "string" || value === "") {
102
+ throw new GradUsageError("A secret value must be a non-empty string.", "invalid_secret");
103
+ }
104
+ const { allowedHosts, ...request } = options;
105
+ return new SecretRef(await this.core.api.setSecret({ name, value, ...(allowedHosts !== undefined ? { allowedHosts: [...allowedHosts] } : {}) }, request));
106
+ }
107
+ /** A reference to pass as `secret` (checks that it exists; never the value). */
108
+ async get(name, options) {
109
+ return new SecretRef(await this.core.api.getSecret(name, options));
110
+ }
111
+ list(options = {}) {
112
+ const { limit, ...request } = options;
113
+ return new Paginator(async (cursor) => {
114
+ const page = await this.core.api.listSecrets({ ...(limit !== undefined ? { limit } : {}), ...(cursor ? { cursor } : {}) }, request);
115
+ return { data: page.data.map((s) => new SecretRef(s)), nextCursor: page.nextCursor };
116
+ }, request.signal);
117
+ }
118
+ /** Deletes a secret (409 ConflictError while a source uses it). */
119
+ async delete(secret, options) {
120
+ await this.core.api.deleteSecret(secretName(secret), options);
121
+ }
122
+ }
123
+ export class SourcesResource {
124
+ core;
125
+ constructor(core) {
126
+ this.core = core;
127
+ }
128
+ /**
129
+ * Connects `provider` to `dataset` (see also `dataset.addSource`). A source feeds one dataset;
130
+ * a dataset can have several sources.
131
+ */
132
+ create(dataset, options) {
133
+ return addSource(this.core, dataset, options);
134
+ }
135
+ async get(id, options) {
136
+ return new Source(this.core, await this.core.api.getSource(id, options));
137
+ }
138
+ /** Sources, newest first; `dataset` keeps one dataset's. */
139
+ list(options = {}) {
140
+ const { dataset, limit, ...request } = options;
141
+ return new Paginator(async (cursor) => {
142
+ const page = await this.core.api.listSources({
143
+ ...(limit !== undefined ? { limit } : {}),
144
+ ...(cursor ? { cursor } : {}),
145
+ ...(dataset !== undefined ? { dataset: datasetName(dataset) } : {}),
146
+ }, request);
147
+ return { data: page.data.map((s) => new Source(this.core, s)), nextCursor: page.nextCursor };
148
+ }, request.signal);
149
+ }
150
+ sync(id, options = {}) {
151
+ return new Pending(syncSource(this.core, id, options));
152
+ }
153
+ async remove(id, options) {
154
+ await this.core.api.deleteSource(id, options);
155
+ }
156
+ }
@@ -0,0 +1,87 @@
1
+ import type { ChatMessage, DatasetRecord, EvalRubricItem } from "./generated/models.js";
2
+ /** What a local scorer function sees for one model output. */
3
+ export interface ScoreInput {
4
+ output: string | null;
5
+ expectedOutput: unknown;
6
+ record: DatasetRecord;
7
+ input: ChatMessage[];
8
+ model: string;
9
+ taskId: string;
10
+ sampleIndex: number;
11
+ }
12
+ /** A scorer that runs in this process (`runtime: "local"`); return a score in [0, 1] or a boolean. */
13
+ export type ScoreFn = (output: string | null, input: ScoreInput) => number | boolean | Promise<number | boolean>;
14
+ /** A check the server runs itself (no code leaves your machine). */
15
+ export interface BuiltinValidator {
16
+ readonly builtin: "json" | "non_empty" | "exact_match" | "regex";
17
+ readonly pattern?: string;
18
+ readonly flags?: string;
19
+ }
20
+ /** Built-in validators. `json`, `nonEmpty`, `exactMatch` and `regex` run on the server; `numericMatch` runs locally. */
21
+ export declare const validators: {
22
+ /** Output parses as JSON. */
23
+ json: () => BuiltinValidator;
24
+ /** Output is not blank. */
25
+ nonEmpty: () => BuiltinValidator;
26
+ /** Output equals the record's expected output (trimmed). */
27
+ exactMatch: () => BuiltinValidator;
28
+ /** Output matches an ECMAScript regex (bounded server-side; max 256 chars, flags from `imsu`). */
29
+ regex: (pattern: string, options?: {
30
+ flags?: string;
31
+ }) => BuiltinValidator;
32
+ /**
33
+ * The last number in the output equals the expected number: `record[field]`
34
+ * when `field` is given (top level or `metadata`), else the expected output.
35
+ * GSM8K-style answers (`#### 42`, `1,234`) are handled.
36
+ */
37
+ numericMatch: (options?: {
38
+ field?: string;
39
+ tolerance?: number;
40
+ }) => ScoreFn;
41
+ };
42
+ /** A named check: a built-in validator (server-side) or your own function (local). */
43
+ export declare class Scorer {
44
+ readonly name: string;
45
+ readonly weight: number | undefined;
46
+ readonly fn: BuiltinValidator | ScoreFn;
47
+ constructor(name: string, options: {
48
+ fn: BuiltinValidator | ScoreFn;
49
+ weight?: number;
50
+ });
51
+ /** True when the function runs in this process. */
52
+ get isLocal(): boolean;
53
+ toWire(): EvalRubricItem;
54
+ }
55
+ /** An LLM judge. `model` is required: there is no default judge that could change under you. */
56
+ export declare class Judge {
57
+ readonly name: string;
58
+ readonly model: string;
59
+ readonly prompt: string | undefined;
60
+ readonly weight: number | undefined;
61
+ constructor(options: {
62
+ name: string;
63
+ model: string | {
64
+ id: string;
65
+ } | {
66
+ name: string;
67
+ version: string;
68
+ };
69
+ prompt?: string;
70
+ weight?: number;
71
+ });
72
+ toWire(): EvalRubricItem;
73
+ }
74
+ export type RubricItem = Scorer | Judge;
75
+ /** A weighted set of checks. */
76
+ export declare class Rubric {
77
+ readonly items: readonly RubricItem[];
78
+ constructor(items: RubricItem[]);
79
+ toWire(): EvalRubricItem[];
80
+ /** Local scorer functions by name. */
81
+ localScorers(): Map<string, ScoreFn>;
82
+ }
83
+ export type RubricInput = Rubric | RubricItem | RubricItem[] | EvalRubricItem[];
84
+ export declare const toRubric: (input: RubricInput) => {
85
+ wire: EvalRubricItem[];
86
+ local: Map<string, ScoreFn>;
87
+ };
@@ -0,0 +1,167 @@
1
+ import { GradUsageError } from "./errors.js";
2
+ const isBuiltin = (fn) => typeof fn === "object" && fn !== null && typeof fn.builtin === "string";
3
+ const lastNumber = (text) => {
4
+ const matches = text.replace(/(\d),(?=\d{3}\b)/g, "$1").match(/-?\d+(?:\.\d+)?/g);
5
+ const last = matches?.[matches.length - 1];
6
+ return last === undefined ? undefined : Number(last);
7
+ };
8
+ const expectedText = (value) => {
9
+ if (typeof value === "string")
10
+ return value;
11
+ if (typeof value === "number")
12
+ return String(value);
13
+ if (value && typeof value === "object" && typeof value.content === "string") {
14
+ return value.content;
15
+ }
16
+ return undefined;
17
+ };
18
+ /** Built-in validators. `json`, `nonEmpty`, `exactMatch` and `regex` run on the server; `numericMatch` runs locally. */
19
+ export const validators = {
20
+ /** Output parses as JSON. */
21
+ json: () => ({ builtin: "json" }),
22
+ /** Output is not blank. */
23
+ nonEmpty: () => ({ builtin: "non_empty" }),
24
+ /** Output equals the record's expected output (trimmed). */
25
+ exactMatch: () => ({ builtin: "exact_match" }),
26
+ /** Output matches an ECMAScript regex (bounded server-side; max 256 chars, flags from `imsu`). */
27
+ regex: (pattern, options = {}) => ({
28
+ builtin: "regex",
29
+ pattern,
30
+ ...(options.flags !== undefined ? { flags: options.flags } : {}),
31
+ }),
32
+ /**
33
+ * The last number in the output equals the expected number: `record[field]`
34
+ * when `field` is given (top level or `metadata`), else the expected output.
35
+ * GSM8K-style answers (`#### 42`, `1,234`) are handled.
36
+ */
37
+ numericMatch: (options = {}) => (output, input) => {
38
+ if (output === null)
39
+ return 0;
40
+ const record = input.record;
41
+ const raw = options.field !== undefined
42
+ ? (record[options.field] ?? record.metadata?.[options.field])
43
+ : input.expectedOutput;
44
+ const text = expectedText(raw);
45
+ const expected = text === undefined ? undefined : lastNumber(text);
46
+ const actual = lastNumber(output);
47
+ if (expected === undefined || actual === undefined)
48
+ return 0;
49
+ return Math.abs(expected - actual) <= (options.tolerance ?? 1e-6) ? 1 : 0;
50
+ },
51
+ };
52
+ const checkWeight = (name, weight) => {
53
+ if (weight === undefined)
54
+ return undefined;
55
+ if (typeof weight !== "number" || !Number.isFinite(weight) || weight <= 0) {
56
+ throw new GradUsageError(`Rubric item '${name}' needs a positive, finite weight (got ${String(weight)}).`, "invalid_rubric");
57
+ }
58
+ return weight;
59
+ };
60
+ /** A named check: a built-in validator (server-side) or your own function (local). */
61
+ export class Scorer {
62
+ name;
63
+ weight;
64
+ fn;
65
+ constructor(name, options) {
66
+ if (!name)
67
+ throw new GradUsageError("Scorer needs a name.", "invalid_rubric");
68
+ if (typeof options.fn !== "function" && !isBuiltin(options.fn)) {
69
+ throw new GradUsageError(`Scorer '${name}' needs fn: a validators.* check or a function.`, "invalid_rubric");
70
+ }
71
+ this.name = name;
72
+ this.weight = checkWeight(name, options.weight);
73
+ this.fn = options.fn;
74
+ }
75
+ /** True when the function runs in this process. */
76
+ get isLocal() {
77
+ return typeof this.fn === "function";
78
+ }
79
+ toWire() {
80
+ const weight = this.weight !== undefined ? { weight: this.weight } : {};
81
+ if (typeof this.fn === "function")
82
+ return { name: this.name, kind: "code", runtime: "local", ...weight };
83
+ if (this.fn.builtin === "regex") {
84
+ return {
85
+ name: this.name,
86
+ kind: "regex",
87
+ pattern: this.fn.pattern ?? "",
88
+ ...(this.fn.flags !== undefined ? { flags: this.fn.flags } : {}),
89
+ ...weight,
90
+ };
91
+ }
92
+ return { name: this.name, kind: "validator", validator: this.fn.builtin, ...weight };
93
+ }
94
+ }
95
+ /** An LLM judge. `model` is required: there is no default judge that could change under you. */
96
+ export class Judge {
97
+ name;
98
+ model;
99
+ prompt;
100
+ weight;
101
+ constructor(options) {
102
+ if (!options.name)
103
+ throw new GradUsageError("Judge needs a name.", "invalid_rubric");
104
+ const model = typeof options.model === "string"
105
+ ? options.model
106
+ : "version" in options.model && "name" in options.model
107
+ ? `${options.model.name}@${options.model.version}`
108
+ : options.model.id;
109
+ if (!model)
110
+ throw new GradUsageError(`Judge '${options.name}' needs an explicit model.`, "invalid_rubric");
111
+ this.name = options.name;
112
+ this.model = model;
113
+ this.prompt = options.prompt;
114
+ this.weight = checkWeight(options.name, options.weight);
115
+ }
116
+ toWire() {
117
+ return {
118
+ name: this.name,
119
+ kind: "judge",
120
+ model: this.model,
121
+ ...(this.prompt !== undefined ? { prompt: this.prompt } : {}),
122
+ ...(this.weight !== undefined ? { weight: this.weight } : {}),
123
+ };
124
+ }
125
+ }
126
+ /** A weighted set of checks. */
127
+ export class Rubric {
128
+ items;
129
+ constructor(items) {
130
+ if (items.length === 0)
131
+ throw new GradUsageError("A Rubric needs at least one item.", "invalid_rubric");
132
+ const names = new Set();
133
+ for (const item of items) {
134
+ if (names.has(item.name))
135
+ throw new GradUsageError(`Rubric item names must be unique ('${item.name}' repeats).`, "invalid_rubric");
136
+ names.add(item.name);
137
+ }
138
+ this.items = [...items];
139
+ }
140
+ toWire() {
141
+ return this.items.map((item) => item.toWire());
142
+ }
143
+ /** Local scorer functions by name. */
144
+ localScorers() {
145
+ const out = new Map();
146
+ for (const item of this.items) {
147
+ if (item instanceof Scorer && typeof item.fn === "function")
148
+ out.set(item.name, item.fn);
149
+ }
150
+ return out;
151
+ }
152
+ }
153
+ export const toRubric = (input) => {
154
+ if (input instanceof Rubric)
155
+ return { wire: input.toWire(), local: input.localScorers() };
156
+ if (input instanceof Scorer || input instanceof Judge) {
157
+ const rubric = new Rubric([input]);
158
+ return { wire: rubric.toWire(), local: rubric.localScorers() };
159
+ }
160
+ if (!Array.isArray(input))
161
+ throw new GradUsageError("A rubric is a Rubric, a Scorer or Judge, or a list of them.", "invalid_rubric");
162
+ if (input.every((item) => item instanceof Scorer || item instanceof Judge)) {
163
+ const rubric = new Rubric(input);
164
+ return { wire: rubric.toWire(), local: rubric.localScorers() };
165
+ }
166
+ return { wire: input, local: new Map() };
167
+ };
@@ -0,0 +1,16 @@
1
+ import type { ChatMessage, DatasetRecord } from "./generated/models.js";
2
+ /** A `grad.trajectory/1` record; `scores` and `metrics` start empty so you can fill them in. */
3
+ export type Trajectory = DatasetRecord & {
4
+ scores: Record<string, number>;
5
+ metrics: Record<string, number>;
6
+ metadata: Record<string, unknown>;
7
+ };
8
+ export declare const Trajectory: {
9
+ fromMessages: (messages: ChatMessage[], options?: {
10
+ sessionId?: string;
11
+ groupId?: string;
12
+ id?: string;
13
+ source?: string;
14
+ metadata?: Record<string, unknown>;
15
+ }) => Trajectory;
16
+ };
@@ -0,0 +1,13 @@
1
+ export const Trajectory = {
2
+ fromMessages: (messages, options = {}) => ({
3
+ schema: "grad.trajectory/1",
4
+ messages,
5
+ scores: {},
6
+ metrics: {},
7
+ metadata: options.metadata ?? {},
8
+ ...(options.id !== undefined ? { id: options.id } : {}),
9
+ ...(options.sessionId !== undefined ? { sessionId: options.sessionId } : {}),
10
+ ...(options.groupId !== undefined ? { groupId: options.groupId } : {}),
11
+ ...(options.source !== undefined ? { source: options.source } : {}),
12
+ }),
13
+ };
@@ -0,0 +1,229 @@
1
+ export declare const SDK_VERSION = "0.2.0-alpha.1";
2
+ export declare const readEnv: (name: string) => string | undefined;
3
+ export interface FieldError {
4
+ field: string;
5
+ message: string;
6
+ }
7
+ export interface GradErrorInit {
8
+ status?: number | undefined;
9
+ code: string;
10
+ requestId?: string | undefined;
11
+ cause?: unknown;
12
+ }
13
+ /** Base class of every error the SDK throws. */
14
+ export declare class GradError extends Error {
15
+ readonly status: number | undefined;
16
+ readonly code: string;
17
+ readonly requestId: string | undefined;
18
+ constructor(message: string, init: GradErrorInit);
19
+ }
20
+ export interface APIErrorInit {
21
+ status: number;
22
+ code: string;
23
+ title: string;
24
+ detail: string;
25
+ type: string;
26
+ requestId: string | undefined;
27
+ method: string;
28
+ url: string;
29
+ headers: Headers;
30
+ body: unknown;
31
+ fieldErrors: FieldError[];
32
+ retryAfterMs: number | undefined;
33
+ }
34
+ /** The server answered with a non-2xx status (RFC 7807 problem+json when it can). */
35
+ export declare class APIError extends GradError {
36
+ readonly status: number;
37
+ readonly title: string;
38
+ readonly detail: string;
39
+ readonly type: string;
40
+ readonly method: string;
41
+ readonly url: string;
42
+ readonly headers: Headers;
43
+ readonly body: unknown;
44
+ readonly fieldErrors: FieldError[];
45
+ readonly retryAfterMs: number | undefined;
46
+ constructor(message: string, init: APIErrorInit);
47
+ }
48
+ export declare class BadRequestError extends APIError {
49
+ }
50
+ export declare class AuthenticationError extends APIError {
51
+ }
52
+ export declare class PermissionDeniedError extends APIError {
53
+ }
54
+ export declare class NotFoundError extends APIError {
55
+ }
56
+ export declare class ConflictError extends APIError {
57
+ }
58
+ export declare class ValidationError extends APIError {
59
+ }
60
+ export declare class RateLimitError extends APIError {
61
+ }
62
+ export declare class ServerError extends APIError {
63
+ }
64
+ /** 501 `deploy_unavailable`: this server has no Cloud serving (self-hosted); download the artifact and serve it yourself. */
65
+ export declare class DeployUnavailableError extends APIError {
66
+ }
67
+ /** 501 `inference_unavailable`: no inference endpoint is configured, so evals cannot generate outputs. */
68
+ export declare class InferenceUnavailableError extends APIError {
69
+ }
70
+ /** The request never produced an HTTP response (DNS, refused, reset, TLS). */
71
+ export declare class APIConnectionError extends GradError {
72
+ }
73
+ /** The per-request timeout elapsed before a response (or a stream went idle). */
74
+ export declare class APITimeoutError extends APIConnectionError {
75
+ }
76
+ /** The caller's AbortSignal fired. */
77
+ export declare class APIUserAbortError extends GradError {
78
+ }
79
+ /** A redirect would leave the API origin (or change the method); refused so credentials never leak. */
80
+ export declare class RedirectError extends GradError {
81
+ }
82
+ /** A 2xx response body was not valid JSON. */
83
+ export declare class ResponseDecodeError extends GradError {
84
+ }
85
+ /** Parses `a.b: message; c: other` (the server's validation detail) or a problem `errors` array. */
86
+ export declare const parseFieldErrors: (body: unknown, detail: string) => FieldError[];
87
+ export declare const parseRetryAfterMs: (headers: Headers, now?: number) => number | undefined;
88
+ export interface ErrorContext {
89
+ method: string;
90
+ url: string;
91
+ apiKeyConfigured: boolean;
92
+ }
93
+ /** Builds the typed error for a non-2xx response; tolerant of any body shape. */
94
+ export declare const makeAPIError: (status: number, headers: Headers, text: string, ctx: ErrorContext) => APIError;
95
+ /** Schema descriptor: 0 = copy verbatim, string = named schema, or a structural node. */
96
+ export type CodecNode = 0 | string | {
97
+ a: CodecNode;
98
+ } | {
99
+ m: CodecNode;
100
+ } | {
101
+ o: Array<[string, string, CodecNode]>;
102
+ x?: CodecNode;
103
+ } | {
104
+ u: {
105
+ a?: CodecNode;
106
+ o?: CodecNode;
107
+ };
108
+ };
109
+ export type CodecTable = Record<string, CodecNode>;
110
+ /** Renames declared keys between camelCase and wire names; user-keyed maps stay verbatim. */
111
+ export declare const convertKeys: (table: CodecTable, node: CodecNode, value: unknown, direction: "decode" | "encode") => unknown;
112
+ export interface ResponseInfo {
113
+ status: number;
114
+ headers: Headers;
115
+ requestId: string | undefined;
116
+ url: string;
117
+ }
118
+ export interface RequestOptions {
119
+ /** Cancels the request (and any retry wait). */
120
+ signal?: AbortSignal | undefined;
121
+ /** Per-attempt timeout until the response headers arrive (and, for JSON, the body). */
122
+ timeoutMs?: number | undefined;
123
+ /** Overrides the client's retry budget for this call. */
124
+ maxRetries?: number | undefined;
125
+ /** Extra headers for this call. */
126
+ headers?: Record<string, string> | undefined;
127
+ /**
128
+ * Idempotency-Key for an operation that accepts one (default: a fresh UUIDv4
129
+ * per call, reused by its retries). Pass your own to retry across processes.
130
+ */
131
+ idempotencyKey?: string | undefined;
132
+ /** Called with status, headers and request id of the final response. */
133
+ onResponse?: ((info: ResponseInfo) => void) | undefined;
134
+ }
135
+ export interface StreamOptions extends RequestOptions {
136
+ /** Abort a streaming body that yields nothing for this long (default 120 s). */
137
+ idleTimeoutMs?: number | undefined;
138
+ }
139
+ export interface SSEOptions extends StreamOptions {
140
+ /** Resume an event stream after this event id (`Last-Event-ID`). */
141
+ lastEventId?: string | undefined;
142
+ }
143
+ export interface RequestSpec {
144
+ method: string;
145
+ path: string;
146
+ query?: Array<[string, unknown]> | undefined;
147
+ headers?: Array<[string, unknown]> | undefined;
148
+ /** JSON-serializable body (already in wire casing). */
149
+ json?: unknown;
150
+ /** Raw, replayable body (for uploads); ignored when `json` is set. */
151
+ body?: Blob | Uint8Array | string | undefined;
152
+ accept?: string | undefined;
153
+ /** The operation accepts an Idempotency-Key, so it is sent with one and retried like a GET. */
154
+ idempotent?: boolean | undefined;
155
+ }
156
+ export interface RawResponse extends ResponseInfo {
157
+ /** The streaming body; read it once. Errors and idle timeouts surface as typed errors. */
158
+ body: ReadableStream<Uint8Array>;
159
+ /** Cancels the underlying request. */
160
+ cancel: () => Promise<void>;
161
+ }
162
+ export interface ServerSentEvent {
163
+ event: string;
164
+ data: string;
165
+ id: string | undefined;
166
+ retry: number | undefined;
167
+ }
168
+ export type Sleep = (ms: number, signal?: AbortSignal) => Promise<void>;
169
+ export interface TransportOptions {
170
+ baseURL: string;
171
+ /** A key, or a resolver (called once per request) for lazily loaded credentials. */
172
+ apiKey?: string | (() => Promise<string | undefined>) | undefined;
173
+ timeoutMs?: number | undefined;
174
+ maxRetries?: number | undefined;
175
+ fetch?: typeof fetch | undefined;
176
+ defaultHeaders?: Record<string, string> | undefined;
177
+ userAgent?: string | undefined;
178
+ /** Injected for tests: waits between retries. */
179
+ sleep?: Sleep | undefined;
180
+ /** Injected for tests: jitter source in [0, 1). */
181
+ random?: (() => number) | undefined;
182
+ }
183
+ export declare const DEFAULT_TIMEOUT_MS = 60000;
184
+ export declare const DEFAULT_MAX_RETRIES = 2;
185
+ export declare const DEFAULT_IDLE_TIMEOUT_MS = 120000;
186
+ export declare const MAX_RETRY_AFTER_MS = 60000;
187
+ export declare const defaultSleep: Sleep;
188
+ /** A UUIDv4 for the Idempotency-Key header. */
189
+ export declare const newIdempotencyKey: () => string;
190
+ export declare const encodePathParam: (value: unknown, name: string) => string;
191
+ export declare const defaultUserAgent: () => string | undefined;
192
+ /** What generated clients need from a transport (lets callers resolve configuration lazily). */
193
+ export interface TransportLike {
194
+ json(spec: RequestSpec, options?: RequestOptions): Promise<unknown>;
195
+ raw(spec: RequestSpec, options?: StreamOptions): Promise<RawResponse>;
196
+ sse(spec: RequestSpec, options?: SSEOptions): AsyncGenerator<ServerSentEvent, void, undefined>;
197
+ }
198
+ export declare class Transport implements TransportLike {
199
+ readonly baseURL: string;
200
+ private readonly origin;
201
+ private readonly apiKey;
202
+ private readonly timeoutMs;
203
+ private readonly maxRetries;
204
+ private readonly fetchImpl;
205
+ private readonly defaultHeaders;
206
+ private readonly userAgent;
207
+ private readonly sleep;
208
+ private readonly random;
209
+ constructor(options: TransportOptions);
210
+ buildURL(spec: RequestSpec): string;
211
+ private resolveKey;
212
+ /** Exponential backoff with jitter: 0.5 s, 1 s, 2 s ... capped at 8 s, scaled into [50%, 100%]. */
213
+ backoffMs(attempt: number): number;
214
+ private headersFor;
215
+ /**
216
+ * Sends with retries and same-origin redirects. Returns the successful
217
+ * response plus a `done` callback that releases the attempt's timer/signal.
218
+ * When `streaming`, the timeout stops once headers arrive.
219
+ */
220
+ private send;
221
+ private wait;
222
+ private abortError;
223
+ /** JSON request; resolves to the parsed body (undefined for empty bodies). */
224
+ json(spec: RequestSpec, options?: RequestOptions): Promise<unknown>;
225
+ /** Streaming request; the timeout covers only the headers, then an idle timeout guards the body. */
226
+ raw(spec: RequestSpec, options?: StreamOptions): Promise<RawResponse>;
227
+ /** Single SSE connection; yields events until the server closes the stream. */
228
+ sse(spec: RequestSpec, options?: SSEOptions): AsyncGenerator<ServerSentEvent, void, undefined>;
229
+ }