@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,9 @@
1
+ // AUTO-GENERATED from spec/openapi.yaml by scripts/generate-sdks.mjs. DO NOT EDIT.
2
+ /* eslint-disable */
3
+ export const ApiKeyScopeValues = ["admin", "datasets:read", "datasets:write", "runs:read", "runs:write", "artifacts:read", "artifacts:write", "secrets:read", "secrets:write", "sources:read", "sources:write", "deployments:write", "feedback:write", "env:serve"];
4
+ export const ArtifactFormatValues = ["peft_lora", "merged_safetensors", "prefix_kv", "cartridge", "encoder_safetensors", "router_bundle", "decision_bundle", "reward_bundle", "reference"];
5
+ export const EvalModeValues = ["eval", "score"];
6
+ export const EvalStatusValues = ["queued", "running", "awaiting_scores", "completed", "failed", "cancelled"];
7
+ export const ImportStatusValues = ["queued", "running", "completed", "failed"];
8
+ export const RecipeKindValues = ["sft", "dpo", "router", "decision", "cartridge", "embedding", "distill", "reward", "grpo"];
9
+ export const RunStatusValues = ["queued", "running", "completed", "failed", "cancelled", "stopped_budget", "stopped_balance"];
@@ -0,0 +1,19 @@
1
+ export { Grad, type GradOptions, type ResolvedConfig } from "./client.js";
2
+ export * from "./errors.js";
3
+ export { DEFAULT_BASE_URL } from "./config.js";
4
+ export { Paginator, type Page } from "./pagination.js";
5
+ export { Pending } from "./pending.js";
6
+ export type { WaitOptions } from "./polling.js";
7
+ export { adapters, Context, loggers, losses, optim, pooling, Recipe, recipes, rollouts, splits, type CheckpointEvalOptions, type CommonRecipeOptions, type ModelRef } from "./recipes.js";
8
+ export { Judge, Rubric, Scorer, validators, type BuiltinValidator, type RubricInput, type RubricItem, type ScoreFn, type ScoreInput } from "./rubrics.js";
9
+ export { Trajectory } from "./trajectory.js";
10
+ export { Artifact, ArtifactsResource, DeploymentsResource, type ArtifactRef, type ArtifactStream, type DeployOptions, type DownloadOptions, type DownloadResult, } from "./resources/artifacts.js";
11
+ export { Dataset, DatasetsResource, ImportJob, ImportsResource, type DatasetRef, type BenchmarkName, type FilterOptions, type FromBenchmarkOptions, type ViewOptions, type RecordPredicate, type ScoreOptions, type FromHfOptions, type ImportFileOptions, type PendingImport, type PushOptions, } from "./resources/datasets.js";
12
+ export { DatasetScoring, Eval, EvalFailures, EvalsResource, type PendingScoring, TERMINAL_EVAL_STATUSES, type EvalParams, type EvalWaitOptions, type PendingEval } from "./resources/evals.js";
13
+ export { KeysResource, ModelsResource, UsageResource } from "./resources/misc.js";
14
+ export { SecretRef, SecretsResource, Source, SourcesResource, sources, type AddSourceOptions, type GradiatedOptions, type ProviderOptions, type SecretLike, type SourceProvider, } from "./resources/sources.js";
15
+ export { Checkpoint, CheckpointsResource, Run, RunPlan, RunsResource, TERMINAL_RUN_STATUSES, type CompletedRun, type MetricsOptions, type PendingRun, type RunParams, type RunWaitOptions, } from "./resources/runs.js";
16
+ export { ApiClient, LIST_API_KEYS_LIMIT_MAX, LIST_ARTIFACTS_LIMIT_MAX, LIST_DATASET_RECORDS_LIMIT_MAX, LIST_DATASETS_LIMIT_MAX, LIST_DEPLOYMENTS_LIMIT_MAX, LIST_EVAL_FAILURES_LIMIT_MAX, LIST_EVAL_OUTPUTS_LIMIT_MAX, LIST_EVAL_RESULTS_LIMIT_MAX, LIST_EVALS_LIMIT_MAX, LIST_IMPORTS_LIMIT_MAX, LIST_RUN_CHECKPOINTS_LIMIT_MAX, LIST_RUN_METRICS_LIMIT_MAX, LIST_RUNS_LIMIT_MAX, LIST_USAGE_LIMIT_MAX, } from "./generated/client.js";
17
+ export { newIdempotencyKey, SDK_VERSION, type RawResponse, type RequestOptions, type ServerSentEvent, type SSEOptions, type StreamOptions } from "./transport.js";
18
+ export type * as models from "./generated/models.js";
19
+ export type { AdapterSpec, ApiKey, ApiKeyScope, ChatMessage, CreatedApiKey, DatasetRecord, Deployment, DeploymentStatus, EvalModelSummary, EvalOutput, EvalReport, EvalRubricItem, EvalTaskOutcome, MetricPoint, PlanEvalResponse, RecipeSpec, ResolvedRunConfig, RouterParetoSummary, RunStatus, SplitSpec, TrainableModel, UsageRecord, } from "./generated/models.js";
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ export { Grad } from "./client.js";
2
+ export * from "./errors.js";
3
+ export { DEFAULT_BASE_URL } from "./config.js";
4
+ export { Paginator } from "./pagination.js";
5
+ export { Pending } from "./pending.js";
6
+ export { adapters, Context, loggers, losses, optim, pooling, Recipe, recipes, rollouts, splits } from "./recipes.js";
7
+ export { Judge, Rubric, Scorer, validators } from "./rubrics.js";
8
+ export { Trajectory } from "./trajectory.js";
9
+ export { Artifact, ArtifactsResource, DeploymentsResource, } from "./resources/artifacts.js";
10
+ export { Dataset, DatasetsResource, ImportJob, ImportsResource, } from "./resources/datasets.js";
11
+ export { DatasetScoring, Eval, EvalFailures, EvalsResource, TERMINAL_EVAL_STATUSES } from "./resources/evals.js";
12
+ export { KeysResource, ModelsResource, UsageResource } from "./resources/misc.js";
13
+ export { SecretRef, SecretsResource, Source, SourcesResource, sources, } from "./resources/sources.js";
14
+ export { Checkpoint, CheckpointsResource, Run, RunPlan, RunsResource, TERMINAL_RUN_STATUSES, } from "./resources/runs.js";
15
+ export { ApiClient, LIST_API_KEYS_LIMIT_MAX, LIST_ARTIFACTS_LIMIT_MAX, LIST_DATASET_RECORDS_LIMIT_MAX, LIST_DATASETS_LIMIT_MAX, LIST_DEPLOYMENTS_LIMIT_MAX, LIST_EVAL_FAILURES_LIMIT_MAX, LIST_EVAL_OUTPUTS_LIMIT_MAX, LIST_EVAL_RESULTS_LIMIT_MAX, LIST_EVALS_LIMIT_MAX, LIST_IMPORTS_LIMIT_MAX, LIST_RUN_CHECKPOINTS_LIMIT_MAX, LIST_RUN_METRICS_LIMIT_MAX, LIST_RUNS_LIMIT_MAX, LIST_USAGE_LIMIT_MAX, } from "./generated/client.js";
16
+ export { newIdempotencyKey, SDK_VERSION } from "./transport.js";
@@ -0,0 +1,26 @@
1
+ import type { RawResponse } from "../transport.js";
2
+ export interface LocalFile {
3
+ path: string;
4
+ filename: string;
5
+ sizeBytes: number;
6
+ sha256: string;
7
+ blob: Blob;
8
+ }
9
+ export declare const sha256File: (file: string) => Promise<string>;
10
+ export declare const describeFile: (file: string) => Promise<LocalFile>;
11
+ export declare const readTextFile: (file: string) => Promise<string>;
12
+ /** Streams JSON Lines records from disk (blank lines skipped, line numbers in errors). */
13
+ export declare function readJsonl(file: string): AsyncGenerator<Record<string, unknown>>;
14
+ export declare const filenameFromDisposition: (header: string | null) => string | undefined;
15
+ export interface DownloadResult {
16
+ path: string;
17
+ sha256: string;
18
+ sizeBytes: number;
19
+ }
20
+ /**
21
+ * Streams `raw.body` to `dest` through a temp file in the same directory,
22
+ * hashing as it goes; verifies `expectedSha256` before the atomic rename.
23
+ * `dest` that is an existing directory (or ends with a separator) receives
24
+ * the server's file name.
25
+ */
26
+ export declare const streamToFile: (raw: RawResponse, dest: string, reference: string, expectedSha256: string | undefined) => Promise<DownloadResult>;
@@ -0,0 +1,130 @@
1
+ /* Node-only file helpers. Loaded with dynamic import so the browser build never touches node:fs. */
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import { createReadStream, openAsBlob } from "node:fs";
4
+ import { mkdir, open, rename, rm, stat } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { createInterface } from "node:readline";
7
+ import { ChecksumMismatchError, GradUsageError } from "../errors.js";
8
+ export const sha256File = async (file) => {
9
+ const hash = createHash("sha256");
10
+ for await (const chunk of createReadStream(file))
11
+ hash.update(chunk);
12
+ return hash.digest("hex");
13
+ };
14
+ export const describeFile = async (file) => {
15
+ const info = await stat(file).catch(() => {
16
+ throw new GradUsageError(`File not found: ${file}`, "file_not_found");
17
+ });
18
+ if (!info.isFile())
19
+ throw new GradUsageError(`${file} is not a regular file.`, "file_not_found");
20
+ return {
21
+ path: file,
22
+ filename: path.basename(file),
23
+ sizeBytes: info.size,
24
+ sha256: await sha256File(file),
25
+ blob: await openAsBlob(file),
26
+ };
27
+ };
28
+ export const readTextFile = async (file) => {
29
+ const { readFile } = await import("node:fs/promises");
30
+ return readFile(file, "utf8");
31
+ };
32
+ /** Streams JSON Lines records from disk (blank lines skipped, line numbers in errors). */
33
+ export async function* readJsonl(file) {
34
+ const lines = createInterface({ input: createReadStream(file, { encoding: "utf8" }), crlfDelay: Infinity });
35
+ let lineNo = 0;
36
+ for await (const line of lines) {
37
+ lineNo += 1;
38
+ if (line.trim() === "")
39
+ continue;
40
+ let value;
41
+ try {
42
+ value = JSON.parse(line);
43
+ }
44
+ catch (error) {
45
+ throw new GradUsageError(`${file}:${lineNo} is not valid JSON: ${error.message}`, "invalid_jsonl");
46
+ }
47
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
48
+ throw new GradUsageError(`${file}:${lineNo} must be a JSON object.`, "invalid_jsonl");
49
+ }
50
+ yield value;
51
+ }
52
+ }
53
+ const SAFE_NAME = /[^A-Za-z0-9._@-]+/g;
54
+ export const filenameFromDisposition = (header) => {
55
+ if (!header)
56
+ return undefined;
57
+ const star = /filename\*=(?:UTF-8'')?([^;]+)/i.exec(header);
58
+ const plain = /filename="?([^";]+)"?/i.exec(header);
59
+ let name = star?.[1] ?? plain?.[1];
60
+ if (!name)
61
+ return undefined;
62
+ try {
63
+ name = decodeURIComponent(name.trim());
64
+ }
65
+ catch {
66
+ // keep as-is
67
+ }
68
+ const base = path.basename(name.replace(/\\/g, "/")).replace(SAFE_NAME, "_");
69
+ return base && base !== "." && base !== ".." ? base : undefined;
70
+ };
71
+ /**
72
+ * Streams `raw.body` to `dest` through a temp file in the same directory,
73
+ * hashing as it goes; verifies `expectedSha256` before the atomic rename.
74
+ * `dest` that is an existing directory (or ends with a separator) receives
75
+ * the server's file name.
76
+ */
77
+ export const streamToFile = async (raw, dest, reference, expectedSha256) => {
78
+ let target = dest;
79
+ const isDirHint = dest.endsWith("/") || dest.endsWith(path.sep);
80
+ const existing = await stat(dest).catch(() => undefined);
81
+ if (isDirHint || existing?.isDirectory()) {
82
+ await mkdir(dest, { recursive: true });
83
+ const name = filenameFromDisposition(raw.headers.get("content-disposition")) ??
84
+ `${reference.replace(SAFE_NAME, "_")}.grad.tar.gz`;
85
+ target = path.join(dest, name);
86
+ }
87
+ else {
88
+ await mkdir(path.dirname(path.resolve(dest)), { recursive: true });
89
+ }
90
+ const dir = path.dirname(path.resolve(target));
91
+ const tmp = path.join(dir, `.${path.basename(target)}.grad-dl-${randomBytes(6).toString("hex")}`);
92
+ const handle = await open(tmp, "wx", 0o644);
93
+ const hash = createHash("sha256");
94
+ let size = 0;
95
+ let ok = false;
96
+ try {
97
+ const reader = raw.body.getReader();
98
+ while (true) {
99
+ const { done, value } = await reader.read();
100
+ if (done)
101
+ break;
102
+ hash.update(value);
103
+ size += value.byteLength;
104
+ let offset = 0;
105
+ while (offset < value.byteLength) {
106
+ const { bytesWritten } = await handle.write(value, offset, value.byteLength - offset);
107
+ offset += bytesWritten;
108
+ }
109
+ }
110
+ await handle.sync();
111
+ await handle.close();
112
+ const actual = hash.digest("hex");
113
+ if (expectedSha256 !== undefined && actual !== expectedSha256) {
114
+ throw new ChecksumMismatchError(reference, expectedSha256, actual);
115
+ }
116
+ await rename(tmp, target);
117
+ ok = true;
118
+ const dirHandle = await open(dir, "r").catch(() => undefined);
119
+ await dirHandle?.sync().catch(() => undefined);
120
+ await dirHandle?.close();
121
+ return { path: target, sha256: actual, sizeBytes: size };
122
+ }
123
+ finally {
124
+ if (!ok) {
125
+ await handle.close().catch(() => undefined);
126
+ await rm(tmp, { force: true });
127
+ await raw.cancel().catch(() => undefined);
128
+ }
129
+ }
130
+ };
@@ -0,0 +1,39 @@
1
+ import { type RequestOptions } from "./transport.js";
2
+ export interface Page<T> {
3
+ data: T[];
4
+ nextCursor: string | null;
5
+ }
6
+ /** Default cap for `Paginator.all()`; iterate with `for await` for larger lists. */
7
+ export declare const DEFAULT_MAX_ITEMS = 100000;
8
+ /**
9
+ * Walks a cursor-paged endpoint page by page. Stops when the server returns no
10
+ * cursor or an empty page, throws PaginationLoopError when a cursor repeats
11
+ * (following it would never end), and checks `signal` before every request.
12
+ * Each request still carries its own per-request timeout.
13
+ */
14
+ export declare function pages<T>(fetchPage: (cursor: string | undefined) => Promise<Page<T>>, signal?: AbortSignal, first?: Promise<Page<T>>): AsyncGenerator<Page<T>, void, undefined>;
15
+ /** Collects every item of a paged endpoint, bounded by `maxItems` (default 100,000). */
16
+ export declare const collect: <T>(source: AsyncIterable<Page<T>>, maxItems?: number) => Promise<T[]>;
17
+ /**
18
+ * A list call: `await` it for the first page, or `for await` it to walk every
19
+ * item across pages.
20
+ */
21
+ export declare class Paginator<T> implements PromiseLike<Page<T>>, AsyncIterable<T> {
22
+ private readonly fetchPage;
23
+ private readonly signal?;
24
+ private first;
25
+ constructor(fetchPage: (cursor: string | undefined) => Promise<Page<T>>, signal?: AbortSignal | undefined);
26
+ private firstPage;
27
+ then<R1 = Page<T>, R2 = never>(onfulfilled?: ((value: Page<T>) => R1 | PromiseLike<R1>) | null, onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null): Promise<R1 | R2>;
28
+ /** Every page, in order (stops on a repeated cursor with PaginationLoopError). */
29
+ pages(): AsyncGenerator<Page<T>, void, undefined>;
30
+ [Symbol.asyncIterator](): AsyncIterator<T>;
31
+ /** Collects every item; throws GradUsageError past `maxItems` (default 100,000). */
32
+ all(options?: {
33
+ maxItems?: number;
34
+ }): Promise<T[]>;
35
+ }
36
+ /** The list-call options every paged method accepts. */
37
+ export type ListOptions = {
38
+ limit?: number;
39
+ } & RequestOptions;
@@ -0,0 +1,73 @@
1
+ import { APIUserAbortError } from "./transport.js";
2
+ import { GradUsageError, PaginationLoopError } from "./errors.js";
3
+ /** Default cap for `Paginator.all()`; iterate with `for await` for larger lists. */
4
+ export const DEFAULT_MAX_ITEMS = 100_000;
5
+ const aborted = (signal) => new APIUserAbortError("Listing aborted.", { code: "aborted", cause: signal.reason });
6
+ /**
7
+ * Walks a cursor-paged endpoint page by page. Stops when the server returns no
8
+ * cursor or an empty page, throws PaginationLoopError when a cursor repeats
9
+ * (following it would never end), and checks `signal` before every request.
10
+ * Each request still carries its own per-request timeout.
11
+ */
12
+ export async function* pages(fetchPage, signal, first) {
13
+ const seen = new Set();
14
+ let cursor;
15
+ let pending = first;
16
+ while (true) {
17
+ if (signal?.aborted)
18
+ throw aborted(signal);
19
+ const page = await (pending ?? fetchPage(cursor));
20
+ pending = undefined;
21
+ yield page;
22
+ const next = page.nextCursor;
23
+ if (!next || page.data.length === 0)
24
+ return;
25
+ if (seen.has(next))
26
+ throw new PaginationLoopError(next);
27
+ seen.add(next);
28
+ cursor = next;
29
+ }
30
+ }
31
+ /** Collects every item of a paged endpoint, bounded by `maxItems` (default 100,000). */
32
+ export const collect = async (source, maxItems = DEFAULT_MAX_ITEMS) => {
33
+ const out = [];
34
+ for await (const page of source) {
35
+ if (out.length + page.data.length > maxItems) {
36
+ throw new GradUsageError(`The listing has more than ${maxItems} items; iterate it with \`for await\` instead of collecting it.`, "too_many_items");
37
+ }
38
+ out.push(...page.data);
39
+ }
40
+ return out;
41
+ };
42
+ /**
43
+ * A list call: `await` it for the first page, or `for await` it to walk every
44
+ * item across pages.
45
+ */
46
+ export class Paginator {
47
+ fetchPage;
48
+ signal;
49
+ first;
50
+ constructor(fetchPage, signal) {
51
+ this.fetchPage = fetchPage;
52
+ this.signal = signal;
53
+ }
54
+ firstPage() {
55
+ this.first ??= this.fetchPage(undefined);
56
+ return this.first;
57
+ }
58
+ then(onfulfilled, onrejected) {
59
+ return this.firstPage().then(onfulfilled, onrejected);
60
+ }
61
+ /** Every page, in order (stops on a repeated cursor with PaginationLoopError). */
62
+ pages() {
63
+ return pages(this.fetchPage, this.signal, this.signal?.aborted ? undefined : this.firstPage());
64
+ }
65
+ async *[Symbol.asyncIterator]() {
66
+ for await (const page of this.pages())
67
+ yield* page.data;
68
+ }
69
+ /** Collects every item; throws GradUsageError past `maxItems` (default 100,000). */
70
+ all(options = {}) {
71
+ return collect(this.pages(), options.maxItems);
72
+ }
73
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * A create call: `await` it for the created resource, or chain `.wait()` to
3
+ * block until it finishes (`grad.runs.create({...}).wait()`).
4
+ */
5
+ export declare class Pending<T extends {
6
+ wait(options?: O): Promise<R>;
7
+ }, R, O> implements PromiseLike<T> {
8
+ private readonly promise;
9
+ constructor(promise: Promise<T>);
10
+ then<R1 = T, R2 = never>(onfulfilled?: ((value: T) => R1 | PromiseLike<R1>) | null, onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null): Promise<R1 | R2>;
11
+ catch<R2 = never>(onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null): Promise<T | R2>;
12
+ /** Waits for the created resource to finish. */
13
+ wait(options?: O): Promise<R>;
14
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * A create call: `await` it for the created resource, or chain `.wait()` to
3
+ * block until it finishes (`grad.runs.create({...}).wait()`).
4
+ */
5
+ export class Pending {
6
+ promise;
7
+ constructor(promise) {
8
+ this.promise = promise;
9
+ }
10
+ then(onfulfilled, onrejected) {
11
+ return this.promise.then(onfulfilled, onrejected);
12
+ }
13
+ catch(onrejected) {
14
+ return this.promise.catch(onrejected);
15
+ }
16
+ /** Waits for the created resource to finish. */
17
+ async wait(options) {
18
+ return (await this.promise).wait(options);
19
+ }
20
+ }
@@ -0,0 +1,25 @@
1
+ import { type Sleep } from "./transport.js";
2
+ /** How long wait() polls when no timeoutMs is given. */
3
+ export declare const DEFAULT_WAIT_TIMEOUT_MS: number;
4
+ export interface WaitOptions {
5
+ /** Give up after this long (default 24 h, as every SDK: no wait hangs forever). */
6
+ timeoutMs?: number | undefined;
7
+ /** Stop waiting (the server-side resource keeps running). */
8
+ signal?: AbortSignal | undefined;
9
+ /** First poll interval (default 500 ms); it backs off ×1.5 up to `maxPollIntervalMs`. */
10
+ pollIntervalMs?: number | undefined;
11
+ /** Longest poll interval (default 5 s). */
12
+ maxPollIntervalMs?: number | undefined;
13
+ }
14
+ export interface PollContext {
15
+ sleep: Sleep;
16
+ now: () => number;
17
+ }
18
+ export declare const defaultPollContext: PollContext;
19
+ /** Errors worth riding out while polling: no response, timeouts, 408/429/5xx. */
20
+ export declare const isTransient: (error: unknown) => boolean;
21
+ /**
22
+ * Polls `fetchState` until `isDone` holds, backing off 0.5 s -> 5 s and riding
23
+ * out transient errors. One abort listener per sleep, always removed.
24
+ */
25
+ export declare const pollUntil: <T>(what: string, fetchState: (signal: AbortSignal | undefined) => Promise<T>, isDone: (state: T) => boolean | Promise<boolean>, options?: WaitOptions, ctx?: PollContext, onState?: (state: T) => void | Promise<void>) => Promise<T>;
@@ -0,0 +1,63 @@
1
+ import { APIConnectionError, APIError, APIUserAbortError, defaultSleep, } from "./transport.js";
2
+ import { WaitTimeoutError } from "./errors.js";
3
+ /** How long wait() polls when no timeoutMs is given. */
4
+ export const DEFAULT_WAIT_TIMEOUT_MS = 24 * 3600 * 1000;
5
+ export const defaultPollContext = { sleep: defaultSleep, now: () => Date.now() };
6
+ /** Errors worth riding out while polling: no response, timeouts, 408/429/5xx. */
7
+ export const isTransient = (error) => {
8
+ if (error instanceof APIUserAbortError)
9
+ return false;
10
+ if (error instanceof APIConnectionError)
11
+ return true;
12
+ if (error instanceof APIError) {
13
+ if (error.code === "deploy_unavailable" || error.code === "inference_unavailable")
14
+ return false;
15
+ return error.status === 408 || error.status === 429 || error.status >= 500;
16
+ }
17
+ return false;
18
+ };
19
+ const abortError = (what, signal) => new APIUserAbortError(`Stopped waiting for ${what}.`, { code: "aborted", cause: signal.reason });
20
+ /**
21
+ * Polls `fetchState` until `isDone` holds, backing off 0.5 s -> 5 s and riding
22
+ * out transient errors. One abort listener per sleep, always removed.
23
+ */
24
+ export const pollUntil = async (what, fetchState, isDone, options = {}, ctx = defaultPollContext, onState) => {
25
+ const started = ctx.now();
26
+ const timeoutMs = options.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
27
+ const deadline = started + timeoutMs;
28
+ const maxInterval = options.maxPollIntervalMs ?? 5_000;
29
+ let interval = Math.min(options.pollIntervalMs ?? 500, maxInterval);
30
+ const signal = options.signal;
31
+ while (true) {
32
+ if (signal?.aborted)
33
+ throw abortError(what, signal);
34
+ let state;
35
+ try {
36
+ state = await fetchState(signal);
37
+ }
38
+ catch (error) {
39
+ if (signal?.aborted)
40
+ throw abortError(what, signal);
41
+ if (!isTransient(error))
42
+ throw error;
43
+ }
44
+ if (state !== undefined) {
45
+ if (onState)
46
+ await onState(state);
47
+ if (await isDone(state))
48
+ return state;
49
+ }
50
+ const remaining = deadline - ctx.now();
51
+ if (remaining <= 0)
52
+ throw new WaitTimeoutError(what, timeoutMs);
53
+ try {
54
+ await ctx.sleep(Math.min(interval, remaining), signal);
55
+ }
56
+ catch {
57
+ if (signal?.aborted)
58
+ throw abortError(what, signal);
59
+ throw new APIUserAbortError(`Stopped waiting for ${what}.`, { code: "aborted" });
60
+ }
61
+ interval = Math.min(Math.round(interval * 1.5), maxInterval);
62
+ }
63
+ };
@@ -0,0 +1,220 @@
1
+ import type { AdapterSpec, LoggerSpec, LossSpec, PoolingSpec, RecipeKind, RecipeSpec, RolloutSpec, SplitSpec } from "./generated/models.js";
2
+ import { type RubricInput } from "./rubrics.js";
3
+ /** A catalog model id, or an Artifact (`name@version`) to keep training its adapter (SFT and DPO). */
4
+ export type ModelRef = string | {
5
+ name: string;
6
+ version: string;
7
+ };
8
+ export declare const adapters: {
9
+ /** LoRA adapter (`rank` default 32; `alpha` is fixed at 32 by the server's lr table). */
10
+ lora: (options?: {
11
+ rank?: number;
12
+ alpha?: number;
13
+ mergeOnExport?: boolean;
14
+ }) => AdapterSpec;
15
+ /** Trainable prefix KV tokens (cartridges); default 256 tokens. */
16
+ prefixKv: (options?: {
17
+ numTokens?: number;
18
+ }) => AdapterSpec;
19
+ /** Frozen backbone with a trained head (routers, decision models). */
20
+ frozenHead: () => AdapterSpec;
21
+ };
22
+ /** Train/eval splits (pass as `runs.create({ split })`). Default: by session, 10% held out (15% for routers and decision models). */
23
+ export declare const splits: {
24
+ bySession: (options?: {
25
+ evalFraction?: number;
26
+ seed?: number;
27
+ }) => SplitSpec;
28
+ byGroup: (options?: {
29
+ evalFraction?: number;
30
+ seed?: number;
31
+ }) => SplitSpec;
32
+ random: (options?: {
33
+ evalFraction?: number;
34
+ seed?: number;
35
+ }) => SplitSpec;
36
+ };
37
+ /** The loss each recipe trains with; only its parameters are tunable in v0. */
38
+ export declare const losses: {
39
+ crossEntropy: (options?: {
40
+ reduction?: "per_example" | "per_token";
41
+ }) => {
42
+ reduction?: "per_example" | "per_token";
43
+ kind: "cross_entropy";
44
+ };
45
+ dpo: (options?: {
46
+ beta?: number;
47
+ }) => {
48
+ beta?: number;
49
+ kind: "dpo";
50
+ };
51
+ infoNCE: (options?: {
52
+ temp?: number;
53
+ }) => {
54
+ temp?: number;
55
+ kind: "infonce";
56
+ };
57
+ topKKLDistill: (options?: {
58
+ topK?: number;
59
+ }) => LossSpec;
60
+ };
61
+ /** Distillation rollouts (`recipes.distill({ rollout })`). */
62
+ export declare const rollouts: {
63
+ /** The student writes each answer (default "auto": sized from your records) and the teacher scores those tokens. */
64
+ onPolicy: (options?: {
65
+ maxNewTokens?: number | "auto";
66
+ }) => RolloutSpec;
67
+ /** The teacher answers each prompt once through the inference endpoint (a labeling eval) and the student trains on them. */
68
+ offPolicy: (options?: {
69
+ maxNewTokens?: number;
70
+ }) => RolloutSpec;
71
+ };
72
+ /** AdamW settings (`lr` here is the same as the recipe's `lr`). */
73
+ export declare const optim: {
74
+ adamW: (options?: {
75
+ lr?: number;
76
+ betas?: [number, number];
77
+ weightDecay?: number;
78
+ gradClip?: number;
79
+ }) => {
80
+ lr?: number;
81
+ betas?: [number, number];
82
+ weightDecay?: number;
83
+ gradClip?: number;
84
+ kind: "adamw";
85
+ };
86
+ };
87
+ /** Embedding pooling. */
88
+ export declare const pooling: {
89
+ mean: () => PoolingSpec;
90
+ cls: () => PoolingSpec;
91
+ };
92
+ /** Text baked into a cartridge. */
93
+ export declare class Context {
94
+ private readonly source;
95
+ private constructor();
96
+ static fromText(text: string): Context;
97
+ /** Read from disk when the run is submitted (Node only). */
98
+ static fromFile(path: string): Context;
99
+ /** The RecipeSpec fields for this context. */
100
+ toSpec(): Promise<Pick<RecipeSpec, "contextText">>;
101
+ }
102
+ /** Options every recipe accepts (each language's casing of the documented names). */
103
+ export interface CommonRecipeOptions {
104
+ model?: ModelRef;
105
+ adapter?: AdapterSpec;
106
+ lr?: number | "auto";
107
+ lrScale?: number;
108
+ optimizer?: ReturnType<typeof optim.adamW>;
109
+ batchSize?: number;
110
+ epochs?: number;
111
+ schedule?: "linear" | "cosine" | "constant";
112
+ warmup?: number;
113
+ trainOn?: "last" | "all_assistant";
114
+ thinking?: "auto" | "on" | "off";
115
+ preserveThinking?: boolean;
116
+ reduction?: "per_example" | "per_token";
117
+ select?: "best" | "last";
118
+ checkpointTtlDays?: number;
119
+ /** "auto" (every 10% of steps) or a number of optimizer steps. */
120
+ evalEvery?: number | "auto";
121
+ /** Extra evals on each checkpoint: a dataset (or its name), or `{ dataset, rubric?, limit?, name?, version? }`. */
122
+ evals?: Array<string | {
123
+ name: string;
124
+ recordCount: number;
125
+ } | CheckpointEvalOptions>;
126
+ /** Experiment trackers: `[loggers.wandb({ project, secret })]` or `[loggers.mlflow({ trackingUri })]`. */
127
+ loggers?: LoggerSpec[];
128
+ }
129
+ /** One of a recipe's `evals`, scored on every checkpoint during training. */
130
+ export interface CheckpointEvalOptions {
131
+ dataset: string | {
132
+ name: string;
133
+ };
134
+ /** Judges, regexes and validators (local functions can't run during training). */
135
+ rubric?: RubricInput;
136
+ limit?: number;
137
+ name?: string;
138
+ version?: number;
139
+ }
140
+ /** Experiment trackers for recipe `loggers`; keys come from workspace secrets. A failing tracker never fails the run. */
141
+ export declare const loggers: {
142
+ /** Weights & Biases: `secret` names the workspace secret holding the API key. */
143
+ wandb: (options: {
144
+ project: string;
145
+ secret: string;
146
+ entity?: string;
147
+ runName?: string;
148
+ host?: string;
149
+ }) => LoggerSpec;
150
+ /** MLflow: `secret` names a workspace secret with a bearer token, if the server needs one. */
151
+ mlflow: (options: {
152
+ trackingUri: string;
153
+ experiment?: string;
154
+ secret?: string;
155
+ runName?: string;
156
+ }) => LoggerSpec;
157
+ };
158
+ /** A recipe ready to submit; build one with `recipes.*`. */
159
+ export declare class Recipe {
160
+ readonly kind: RecipeKind;
161
+ private readonly fields;
162
+ private readonly context?;
163
+ constructor(kind: RecipeKind, fields: Partial<RecipeSpec>, context?: Context | undefined);
164
+ /** The wire RecipeSpec (only the fields you set; the server applies documented defaults). */
165
+ toSpec(): Promise<RecipeSpec>;
166
+ }
167
+ export declare const recipes: {
168
+ /** Supervised fine-tuning on chat records. */
169
+ sft: (options?: CommonRecipeOptions & {
170
+ mergeOnExport?: boolean;
171
+ loss?: ReturnType<typeof losses.crossEntropy>;
172
+ }) => Recipe;
173
+ /** Direct preference optimization on chosen/rejected pairs (pass `model: sftRun.artifact` to continue an SFT run). */
174
+ dpo: (options?: CommonRecipeOptions & {
175
+ beta?: number;
176
+ loss?: ReturnType<typeof losses.dpo>;
177
+ }) => Recipe;
178
+ /** Learned router across candidate models (default backbone qwen/qwen3-0.6b). */
179
+ router: (options?: CommonRecipeOptions & {
180
+ models?: ModelRef[];
181
+ maxQualityDrop?: number;
182
+ /** A score name on your records, or Judge/validator items (the server labels your prompts with an eval first). */
183
+ rubric?: string | RubricInput;
184
+ /** USD per request for each candidate. */
185
+ pricing?: Record<string, number>;
186
+ fallback?: ModelRef;
187
+ }) => Recipe;
188
+ /** Decision model (default backbone gradiated/linden-1). */
189
+ decisionModel: (options?: CommonRecipeOptions) => Recipe;
190
+ /** Context cartridge: compress a document into trainable prefix KV tokens. */
191
+ cartridge: (options: CommonRecipeOptions & {
192
+ context: Context;
193
+ numTokens?: number;
194
+ teacher?: ModelRef;
195
+ loss?: LossSpec;
196
+ maxNewTokens?: number;
197
+ }) => Recipe;
198
+ /**
199
+ * Distillation: a LoRA student learns a teacher on your prompts. On-policy (default) the teacher
200
+ * must be a catalog model sharing the student's tokenizer; off-policy it can be an Artifact or any
201
+ * model the inference endpoint serves.
202
+ */
203
+ distill: (options: CommonRecipeOptions & {
204
+ teacher: ModelRef;
205
+ rollout?: RolloutSpec;
206
+ loss?: LossSpec;
207
+ context?: Context;
208
+ }) => Recipe;
209
+ /** Reward model: a scalar head trained on chosen/rejected pairs (and, with `rubric`, scored answers). */
210
+ rewardModel: (options?: CommonRecipeOptions & {
211
+ rubric?: string;
212
+ }) => Recipe;
213
+ /** Embedding model (full encoder fine-tune; default baai/bge-small-en-v1.5). */
214
+ embedding: (options?: CommonRecipeOptions & {
215
+ temp?: number;
216
+ loss?: ReturnType<typeof losses.infoNCE>;
217
+ pool?: PoolingSpec;
218
+ }) => Recipe;
219
+ };
220
+ export declare const toRecipeSpec: (recipe: Recipe | RecipeSpec) => Promise<RecipeSpec>;