omics-os 0.0.0-stage → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/LICENSE +664 -0
  2. package/README.md +385 -2
  3. package/package.json +38 -4
  4. package/packages/cli/dist/index.js +154 -0
  5. package/packages/cloud-client/dist/agents.d.ts +20 -0
  6. package/packages/cloud-client/dist/agents.js +69 -0
  7. package/packages/cloud-client/dist/apiClient.d.ts +44 -0
  8. package/packages/cloud-client/dist/apiClient.js +368 -0
  9. package/packages/cloud-client/dist/auth.d.ts +76 -0
  10. package/packages/cloud-client/dist/auth.js +462 -0
  11. package/packages/cloud-client/dist/biovault/approval.d.ts +40 -0
  12. package/packages/cloud-client/dist/biovault/approval.js +38 -0
  13. package/packages/cloud-client/dist/biovault/assurance.d.ts +10 -0
  14. package/packages/cloud-client/dist/biovault/assurance.js +14 -0
  15. package/packages/cloud-client/dist/biovault/client.d.ts +76 -0
  16. package/packages/cloud-client/dist/biovault/client.js +212 -0
  17. package/packages/cloud-client/dist/biovault/compat.d.ts +29 -0
  18. package/packages/cloud-client/dist/biovault/compat.js +90 -0
  19. package/packages/cloud-client/dist/biovault/entries.d.ts +143 -0
  20. package/packages/cloud-client/dist/biovault/entries.js +359 -0
  21. package/packages/cloud-client/dist/biovault/errors.d.ts +18 -0
  22. package/packages/cloud-client/dist/biovault/errors.js +90 -0
  23. package/packages/cloud-client/dist/biovault/fields.d.ts +7 -0
  24. package/packages/cloud-client/dist/biovault/fields.js +42 -0
  25. package/packages/cloud-client/dist/biovault/identity.d.ts +10 -0
  26. package/packages/cloud-client/dist/biovault/identity.js +43 -0
  27. package/packages/cloud-client/dist/biovault/index.d.ts +15 -0
  28. package/packages/cloud-client/dist/biovault/index.js +16 -0
  29. package/packages/cloud-client/dist/biovault/instructionMatch.d.ts +32 -0
  30. package/packages/cloud-client/dist/biovault/instructionMatch.js +118 -0
  31. package/packages/cloud-client/dist/biovault/pending.d.ts +41 -0
  32. package/packages/cloud-client/dist/biovault/pending.js +208 -0
  33. package/packages/cloud-client/dist/biovault/preCommit.d.ts +10 -0
  34. package/packages/cloud-client/dist/biovault/preCommit.js +10 -0
  35. package/packages/cloud-client/dist/biovault/provenance.d.ts +45 -0
  36. package/packages/cloud-client/dist/biovault/provenance.js +55 -0
  37. package/packages/cloud-client/dist/biovault/vendor/packageDeliveryV1.generated.d.ts +3981 -0
  38. package/packages/cloud-client/dist/biovault/vendor/packageDeliveryV1.generated.js +3632 -0
  39. package/packages/cloud-client/dist/biovault/vendor/runV1.generated.d.ts +2326 -0
  40. package/packages/cloud-client/dist/biovault/vendor/runV1.generated.js +491 -0
  41. package/packages/cloud-client/dist/biovault/wireShape.d.ts +25 -0
  42. package/packages/cloud-client/dist/biovault/wireShape.js +88 -0
  43. package/packages/cloud-client/dist/bootstrap.d.ts +4 -0
  44. package/packages/cloud-client/dist/bootstrap.js +19 -0
  45. package/packages/cloud-client/dist/config.d.ts +44 -0
  46. package/packages/cloud-client/dist/config.js +309 -0
  47. package/packages/cloud-client/dist/credentials.d.ts +96 -0
  48. package/packages/cloud-client/dist/credentials.js +395 -0
  49. package/packages/cloud-client/dist/editor.d.ts +77 -0
  50. package/packages/cloud-client/dist/editor.js +278 -0
  51. package/packages/cloud-client/dist/errors.d.ts +27 -0
  52. package/packages/cloud-client/dist/errors.js +102 -0
  53. package/packages/cloud-client/dist/exports.d.ts +19 -0
  54. package/packages/cloud-client/dist/exports.js +85 -0
  55. package/packages/cloud-client/dist/featureFlags.d.ts +10 -0
  56. package/packages/cloud-client/dist/featureFlags.js +36 -0
  57. package/packages/cloud-client/dist/files.d.ts +35 -0
  58. package/packages/cloud-client/dist/files.js +109 -0
  59. package/packages/cloud-client/dist/index.d.ts +29 -0
  60. package/packages/cloud-client/dist/index.js +22 -0
  61. package/packages/cloud-client/dist/multipartUpload.d.ts +99 -0
  62. package/packages/cloud-client/dist/multipartUpload.js +624 -0
  63. package/packages/cloud-client/dist/projects.d.ts +42 -0
  64. package/packages/cloud-client/dist/projects.js +119 -0
  65. package/packages/cloud-client/dist/resources.d.ts +8 -0
  66. package/packages/cloud-client/dist/resources.js +26 -0
  67. package/packages/cloud-client/dist/sessions.d.ts +67 -0
  68. package/packages/cloud-client/dist/sessions.js +187 -0
  69. package/packages/cloud-client/dist/templates.d.ts +4 -0
  70. package/packages/cloud-client/dist/templates.js +12 -0
  71. package/packages/cloud-client/dist/types.d.ts +431 -0
  72. package/packages/cloud-client/dist/types.js +94 -0
  73. package/packages/cloud-client/dist/uploads.d.ts +93 -0
  74. package/packages/cloud-client/dist/uploads.js +61 -0
  75. package/packages/cloud-client/dist/vault.d.ts +20 -0
  76. package/packages/cloud-client/dist/vault.js +43 -0
  77. package/packages/cloud-client/dist/vectorSearch.d.ts +3 -0
  78. package/packages/cloud-client/dist/vectorSearch.js +12 -0
  79. package/packages/tui/dist/lobster.mjs +273 -0
  80. package/skills/omics-os-cloud/SKILL.md +24 -0
  81. package/skills/omics-os-lobster/SKILL.md +24 -0
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Agent store REST API (/agents/store): browse, details, download URL.
3
+ *
4
+ * The store takes the same credentials as the other routes (CLI login, API key), so a 401 is "not logged in".
5
+ * Publishing is curated in Omics-OS Cloud; there is no CLI publish route.
6
+ */
7
+ import type { AppConfig, AgentDetail, AgentsListResponse } from "./types.js";
8
+ export declare const AGENT_STORE_UNAVAILABLE_MESSAGE = "The agent store is not available.";
9
+ /** List curated agent packages; the reply is returned as sent. */
10
+ export declare function listAgents(config: AppConfig, options?: {
11
+ limit?: number;
12
+ nextToken?: string;
13
+ category?: string;
14
+ }): Promise<AgentsListResponse>;
15
+ /** Get a package version ("latest" or none: the latest active one). Returns null only when it does not exist. */
16
+ export declare function getAgentInfo(config: AppConfig, name: string, version?: string): Promise<AgentDetail | null>;
17
+ /** Get a download URL for a package version; "latest" or none resolves the version first. */
18
+ export declare function downloadAgent(config: AppConfig, name: string, version?: string): Promise<{
19
+ download_url: string;
20
+ }>;
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Agent store REST API (/agents/store): browse, details, download URL.
3
+ *
4
+ * The store takes the same credentials as the other routes (CLI login, API key), so a 401 is "not logged in".
5
+ * Publishing is curated in Omics-OS Cloud; there is no CLI publish route.
6
+ */
7
+ import { ApiError, AuthError } from "./types.js";
8
+ import { apiFetch } from "./apiClient.js";
9
+ export const AGENT_STORE_UNAVAILABLE_MESSAGE = "The agent store is not available.";
10
+ function storeError(cause, kind, message) {
11
+ const error = new ApiError(cause.path, cause.status, cause.statusText, cause.detail, cause.body, cause.code, undefined, cause.types, { retryable: false, requestId: cause.requestId });
12
+ error.kind = kind;
13
+ error.publicMessage = message;
14
+ error.message = message;
15
+ error.exitCode = 1;
16
+ error.cause = cause;
17
+ return error;
18
+ }
19
+ /** Store-specific meaning for a disabled store. With no credential nothing is sent: the store answers 401. */
20
+ async function store(config, request) {
21
+ if (!config.token)
22
+ throw new AuthError("/agents/store");
23
+ try {
24
+ return await request();
25
+ }
26
+ catch (error) {
27
+ if (error instanceof ApiError && error.status === 404 && error.detail === "Agent store is not enabled") {
28
+ throw storeError(error, "unavailable", AGENT_STORE_UNAVAILABLE_MESSAGE);
29
+ }
30
+ throw error;
31
+ }
32
+ }
33
+ /** List curated agent packages; the reply is returned as sent. */
34
+ export async function listAgents(config, options = {}) {
35
+ const params = new URLSearchParams();
36
+ if (options.limit !== undefined)
37
+ params.set("limit", String(options.limit));
38
+ if (options.nextToken !== undefined)
39
+ params.set("next_token", options.nextToken);
40
+ if (options.category !== undefined)
41
+ params.set("category", options.category);
42
+ const qs = params.size ? `?${params}` : "";
43
+ return store(config, () => apiFetch(config, `/agents/store${qs}`));
44
+ }
45
+ /** Get a package version ("latest" or none: the latest active one). Returns null only when it does not exist. */
46
+ export async function getAgentInfo(config, name, version) {
47
+ const v = version === undefined || version === "latest" ? undefined : version;
48
+ try {
49
+ return await store(config, () => v === undefined
50
+ ? apiFetch(config, `/agents/store/${encodeURIComponent(name)}`)
51
+ : apiFetch(config, `/agents/store/${encodeURIComponent(name)}/${encodeURIComponent(v)}`));
52
+ }
53
+ catch (e) {
54
+ if (e instanceof ApiError && e.status === 404 && e.kind !== "unavailable")
55
+ return null;
56
+ throw e;
57
+ }
58
+ }
59
+ /** Get a download URL for a package version; "latest" or none resolves the version first. */
60
+ export async function downloadAgent(config, name, version) {
61
+ const v = version === undefined || version === "latest" ? await latestVersion(config, name) : version;
62
+ return store(config, () => apiFetch(config, `/agents/store/${encodeURIComponent(name)}/${encodeURIComponent(v)}/download`));
63
+ }
64
+ async function latestVersion(config, name) {
65
+ const latest = await getAgentInfo(config, name);
66
+ if (!latest)
67
+ throw new ApiError(`/agents/store/${encodeURIComponent(name)}`, 404, "Not Found", "Package not found");
68
+ return latest.version;
69
+ }
@@ -0,0 +1,44 @@
1
+ /** Auth-aware REST client with retry, error hierarchy, and streaming support. */
2
+ import type { AppConfig, ApiRequestOptions } from "./types.js";
3
+ import { ApiError } from "./types.js";
4
+ /**
5
+ * Retry-After in milliseconds, capped (by default at the longest wait before a retry); undefined when absent or invalid.
6
+ * Accepts both forms from RFC 9110: delta-seconds ("5") and an HTTP-date.
7
+ */
8
+ export declare function retryAfterMs(header: string | null, now?: number, cap?: number): number | undefined;
9
+ export declare function readErrorBody(resp: Response): Promise<Record<string, unknown> | undefined>;
10
+ /**
11
+ * Read an error body in any shape the backend sends:
12
+ * `{detail: "text"}`, `{detail: {error|code, message}}` and the flat worker
13
+ * refusal `{error, detail}`. Returns a readable message and a machine code.
14
+ */
15
+ export declare function describeErrorBody(body: Record<string, unknown> | undefined): {
16
+ detail?: string;
17
+ code?: string;
18
+ error?: string;
19
+ subcode?: string;
20
+ };
21
+ /** Fetch JSON without silently replaying writes or losing uncertain outcomes. */
22
+ /** One API request attempt, for --verbose. Never headers, bodies, query strings or credentials. */
23
+ export interface RequestTrace {
24
+ method: string;
25
+ /** URL path only; "?…" marks that a query string was sent. */
26
+ path: string;
27
+ /** HTTP status, or null when no response arrived. */
28
+ status: number | null;
29
+ requestId: string | null;
30
+ }
31
+ /** Set (or clear, with undefined) the observer told about each API request attempt. */
32
+ export declare function setRequestObserver(observer: ((trace: RequestTrace) => void) | undefined): void;
33
+ export declare function apiFetch<T>(config: AppConfig, path: string, options?: ApiRequestOptions): Promise<T>;
34
+ /**
35
+ * The error for a chat stream the server refused before it started, read the same way as apiFetch reads errors.
36
+ * A chat POST is never resent, so a 429 is thrown, not retried.
37
+ */
38
+ export declare function streamRefusal(path: string, resp: Response, text: string): ApiError;
39
+ /** Open a streaming SSE connection, returning the ReadableStream body. */
40
+ export declare function apiStream(config: AppConfig, path: string, options?: {
41
+ body?: unknown;
42
+ signal?: AbortSignal;
43
+ headers?: Record<string, string>;
44
+ }): Promise<ReadableStream<Uint8Array>>;
@@ -0,0 +1,368 @@
1
+ /** Auth-aware REST client with retry, error hierarchy, and streaming support. */
2
+ import { ApiError, AuthError, RateLimitError, NetworkError, UnknownOutcomeError, UnreadableResponseError } from "./types.js";
3
+ import { readApiError } from "./errors.js";
4
+ import { freshAuthHeaders, validateApiOrigin } from "./config.js";
5
+ const MAX_RETRIES = 2;
6
+ const RETRY_BASE_MS = 1000;
7
+ const MAX_RETRY_AFTER_MS = 30_000;
8
+ /**
9
+ * Only GET requests are retried automatically. A POST/PATCH/DELETE that failed
10
+ * after it reached the server may already have taken effect (an export job was
11
+ * started, a session was created), so replaying it can duplicate work. Callers
12
+ * that need to recover from a failed mutation must check its status instead.
13
+ */
14
+ function isRetryableMethod(method) {
15
+ return method === "GET";
16
+ }
17
+ function shouldRetryStatus(status, retryAfter) {
18
+ if (status >= 500)
19
+ return true;
20
+ // A 409 is only transient when the server says when to come back.
21
+ return status === 409 && retryAfter !== null;
22
+ }
23
+ /**
24
+ * Retry-After in milliseconds, capped (by default at the longest wait before a retry); undefined when absent or invalid.
25
+ * Accepts both forms from RFC 9110: delta-seconds ("5") and an HTTP-date.
26
+ */
27
+ export function retryAfterMs(header, now = Date.now(), cap = MAX_RETRY_AFTER_MS) {
28
+ if (!header)
29
+ return undefined;
30
+ const value = header.trim();
31
+ let ms;
32
+ if (/^\d+$/.test(value)) {
33
+ ms = Number.parseInt(value, 10) * 1000;
34
+ }
35
+ else {
36
+ const at = Date.parse(value);
37
+ if (Number.isNaN(at))
38
+ return undefined;
39
+ ms = Math.max(0, at - now);
40
+ }
41
+ return Math.min(ms, cap);
42
+ }
43
+ export async function readErrorBody(resp) {
44
+ try {
45
+ return (await resp.json());
46
+ }
47
+ catch {
48
+ return undefined; // response not JSON
49
+ }
50
+ }
51
+ /**
52
+ * Read an error body in any shape the backend sends:
53
+ * `{detail: "text"}`, `{detail: {error|code, message}}` and the flat worker
54
+ * refusal `{error, detail}`. Returns a readable message and a machine code.
55
+ */
56
+ export function describeErrorBody(body) {
57
+ if (!body)
58
+ return {};
59
+ const asText = (v) => typeof v === "string" && v.trim() ? v.trim() : undefined;
60
+ const nested = body.detail;
61
+ if (nested && typeof nested === "object" && !Array.isArray(nested)) {
62
+ const d = nested;
63
+ const error = asText(d.error);
64
+ const subcode = error ? asText(d.code) : undefined;
65
+ const code = asText(d.code) ?? error;
66
+ const message = asText(d.message) ?? asText(d.detail) ?? code;
67
+ return { detail: message?.slice(0, 200), code, error, subcode };
68
+ }
69
+ // Flat worker refusal: keep the type (`error`) and its sub-code (`code`).
70
+ const error = asText(nested) ? asText(body.error) : undefined;
71
+ const subcode = error ? asText(body.code) : undefined;
72
+ const code = asText(body.code) ?? error;
73
+ const message = asText(nested) ?? asText(body.message) ?? asText(body.error);
74
+ return { detail: message?.slice(0, 200), code, error, subcode };
75
+ }
76
+ /**
77
+ * A stored credential goes only to an allowed origin (freshAuthHeaders also checks the origins it was stored for).
78
+ * A key the user supplies for this call (environment or --token) goes to the endpoint the user named, on every path.
79
+ */
80
+ function assertSafeOrigin(config, targetUrl = config.apiUrl) {
81
+ if (config.token && config.tokenSource === "stored") {
82
+ const { safe, origin } = validateApiOrigin(targetUrl);
83
+ if (!safe) {
84
+ throw new AuthError(targetUrl, `Refusing to send credentials to untrusted origin: ${origin}. ` +
85
+ `Use OMICS_OS_API_KEY env var or remove --endpoint to use the default.`);
86
+ }
87
+ }
88
+ }
89
+ let requestObserver;
90
+ /** Set (or clear, with undefined) the observer told about each API request attempt. */
91
+ export function setRequestObserver(observer) {
92
+ requestObserver = observer;
93
+ }
94
+ function traceRequest(method, url, status, requestId) {
95
+ if (!requestObserver)
96
+ return;
97
+ let path;
98
+ try {
99
+ const parsed = new URL(url);
100
+ path = parsed.pathname + (parsed.search ? "?…" : "");
101
+ }
102
+ catch {
103
+ path = "(unreadable URL)";
104
+ }
105
+ try {
106
+ requestObserver({ method, path, status, requestId: requestId ?? null });
107
+ }
108
+ catch {
109
+ // Tracing never changes the request.
110
+ }
111
+ }
112
+ export async function apiFetch(config, path, options = {}) {
113
+ assertSafeOrigin(config);
114
+ const url = `${config.apiUrl}${path}`;
115
+ const method = options.method ?? "GET";
116
+ const safe = (options.retry ?? (isRetryableMethod(method) ? "safe" : "none")) === "safe";
117
+ const multipart = options.body instanceof FormData;
118
+ // Serialization and caller header validation happen before auth/dispatch.
119
+ const body = multipart ? options.body
120
+ : options.body === undefined ? undefined : JSON.stringify(options.body);
121
+ const defaults = { Accept: "application/json" };
122
+ if (options.body !== undefined && !multipart)
123
+ defaults["Content-Type"] = "application/json";
124
+ const custom = {};
125
+ for (const [key, value] of Object.entries(options.headers ?? {})) {
126
+ const lower = key.toLowerCase();
127
+ if (lower === "authorization" || lower === "x-api-key" || (multipart && lower === "content-type"))
128
+ continue;
129
+ for (const existing of Object.keys(defaults)) {
130
+ if (existing.toLowerCase() === lower)
131
+ delete defaults[existing];
132
+ }
133
+ custom[key] = value;
134
+ }
135
+ new Headers({ ...defaults, ...custom });
136
+ let dispatched = false;
137
+ let lastResponse;
138
+ const checkCaller = () => {
139
+ if (!options.signal?.aborted)
140
+ return;
141
+ if (method !== "GET" && dispatched)
142
+ throw new UnknownOutcomeError(path, lastResponse, options.signal.reason);
143
+ throw options.signal.reason;
144
+ };
145
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
146
+ checkCaller();
147
+ let auth;
148
+ try {
149
+ auth = await abortable(freshAuthHeaders(config), options.signal);
150
+ }
151
+ catch (error) {
152
+ checkCaller();
153
+ if (method !== "GET" && dispatched)
154
+ throw new UnknownOutcomeError(path, lastResponse, error);
155
+ throw error;
156
+ }
157
+ checkCaller();
158
+ const timeout = typeof options.timeoutMs === "number" ? new AbortController() : undefined;
159
+ const timer = timeout ? setTimeout(() => timeout.abort(new Error(`timed out after ${options.timeoutMs}ms`)), options.timeoutMs) : undefined;
160
+ const signals = [options.signal, timeout?.signal].filter((s) => s !== undefined);
161
+ const signal = signals.length ? AbortSignal.any(signals) : undefined;
162
+ let resp;
163
+ let traced = false;
164
+ let wait = RETRY_BASE_MS * (attempt + 1);
165
+ try {
166
+ checkCaller();
167
+ dispatched = true;
168
+ resp = await abortable(fetch(url, {
169
+ method, headers: { ...defaults, ...auth, ...custom },
170
+ ...(body !== undefined ? { body } : {}), signal, redirect: "manual",
171
+ }), signal);
172
+ lastResponse = { status: resp.status, statusText: resp.statusText };
173
+ if (resp.ok) {
174
+ traced = true;
175
+ traceRequest(method, url, resp.status, resp.headers.get("x-request-id"));
176
+ }
177
+ if (resp.status === 204)
178
+ return {};
179
+ const text = await responseText(resp, signal);
180
+ if (resp.ok) {
181
+ try {
182
+ const result = JSON.parse(text);
183
+ signal?.throwIfAborted();
184
+ return result;
185
+ }
186
+ catch (error) {
187
+ if (signal?.aborted)
188
+ throw signal.reason;
189
+ if (method !== "GET")
190
+ throw new UnknownOutcomeError(path, lastResponse, error);
191
+ throw new UnreadableResponseError(path, resp.status, resp.statusText, error);
192
+ }
193
+ }
194
+ // Read once under the timeout; readErrorBody keeps its handling of the error body.
195
+ const errBody = await readErrorBody(new Response(text));
196
+ signal?.throwIfAborted();
197
+ const metadata = readApiError(errBody);
198
+ const { detail, error, subcode } = describeErrorBody(errBody);
199
+ const code = metadata.code ?? undefined;
200
+ const retryAfter = resp.headers.get("retry-after");
201
+ const retryMs = retryAfterMs(retryAfter, Date.now(), resp.status === 429 ? undefined : options.maxRetryAfterMs);
202
+ const types = { error, subcode };
203
+ traced = true;
204
+ traceRequest(method, url, resp.status, metadata.requestId ?? resp.headers.get("x-request-id"));
205
+ lastResponse = { status: resp.status, statusText: resp.statusText, detail,
206
+ body: errBody, code, retryAfterMs: retryMs, types,
207
+ retryable: metadata.retryable, requestId: metadata.requestId };
208
+ if (resp.status >= 300 && resp.status < 400) {
209
+ if (method !== "GET")
210
+ throw new UnknownOutcomeError(path, lastResponse);
211
+ throw new ApiError(path, resp.status, resp.statusText, undefined, errBody, undefined, undefined, {}, metadata);
212
+ }
213
+ if (resp.status === 401)
214
+ throw new AuthError(path, undefined, lastResponse);
215
+ const retryStatus = resp.status === 429 || (resp.status >= 500) ||
216
+ (method === "GET" && shouldRetryStatus(resp.status, retryAfter));
217
+ if (safe && attempt < MAX_RETRIES && retryStatus && metadata.retryable !== false) {
218
+ wait = retryMs ?? wait;
219
+ }
220
+ else if (resp.status === 429) {
221
+ throw new RateLimitError(path, retryMs ?? wait, detail, errBody, code, types, metadata);
222
+ }
223
+ else if (method !== "GET" && (resp.status >= 500 || resp.status === 408)) {
224
+ throw new UnknownOutcomeError(path, lastResponse);
225
+ }
226
+ else {
227
+ throw new ApiError(path, resp.status, resp.statusText, detail, errBody, code, retryMs, types, metadata);
228
+ }
229
+ }
230
+ catch (error) {
231
+ if (!traced)
232
+ traceRequest(method, url, resp ? resp.status : null, resp?.headers.get("x-request-id"));
233
+ checkCaller();
234
+ if (error instanceof ApiError)
235
+ throw error;
236
+ if (method !== "GET" && (resp || timeout?.signal.aborted || !safe || attempt === MAX_RETRIES)) {
237
+ throw new UnknownOutcomeError(path, lastResponse, error);
238
+ }
239
+ if (!safe || attempt === MAX_RETRIES)
240
+ throw new NetworkError(path, error instanceof Error ? error : undefined);
241
+ }
242
+ finally {
243
+ if (timer !== undefined)
244
+ clearTimeout(timer);
245
+ }
246
+ try {
247
+ await delay(wait, options.signal);
248
+ }
249
+ catch (error) {
250
+ checkCaller();
251
+ throw error;
252
+ }
253
+ }
254
+ throw new NetworkError(path);
255
+ }
256
+ /** Abort the wait, not the credential resolver's own storage/refresh protocol. */
257
+ function abortable(promise, signal) {
258
+ if (!signal)
259
+ return promise;
260
+ return new Promise((resolve, reject) => {
261
+ const abort = () => { signal.removeEventListener("abort", abort); reject(signal.reason); };
262
+ signal.addEventListener("abort", abort, { once: true });
263
+ promise.then(value => {
264
+ signal.removeEventListener("abort", abort);
265
+ if (signal.aborted)
266
+ reject(signal.reason);
267
+ else
268
+ resolve(value);
269
+ }, error => {
270
+ signal.removeEventListener("abort", abort);
271
+ reject(signal.aborted ? signal.reason : error);
272
+ });
273
+ if (signal.aborted)
274
+ abort();
275
+ });
276
+ }
277
+ /** Separate transport reads from JSON decoding, and close an aborted reader. */
278
+ async function responseText(response, signal) {
279
+ if (!response.body)
280
+ return "";
281
+ const reader = response.body.getReader();
282
+ const decoder = new TextDecoder();
283
+ let text = "";
284
+ try {
285
+ while (true) {
286
+ const { done, value } = await abortable(reader.read(), signal);
287
+ if (done)
288
+ return text + decoder.decode();
289
+ text += decoder.decode(value, { stream: true });
290
+ }
291
+ }
292
+ catch (error) {
293
+ void reader.cancel(error).catch(() => { });
294
+ throw error;
295
+ }
296
+ finally {
297
+ reader.releaseLock();
298
+ }
299
+ }
300
+ /**
301
+ * The error for a chat stream the server refused before it started, read the same way as apiFetch reads errors.
302
+ * A chat POST is never resent, so a 429 is thrown, not retried.
303
+ */
304
+ export function streamRefusal(path, resp, text) {
305
+ let errBody;
306
+ try {
307
+ const parsed = JSON.parse(text);
308
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
309
+ errBody = parsed;
310
+ }
311
+ catch {
312
+ // response not JSON
313
+ }
314
+ const metadata = readApiError(errBody);
315
+ const { detail, error, subcode } = describeErrorBody(errBody);
316
+ const code = metadata.code ?? undefined;
317
+ // Uncapped: nothing waits on it here, and a person is shown the server's own number.
318
+ const retryMs = retryAfterMs(resp.headers.get("retry-after"), Date.now(), Infinity);
319
+ if (resp.status === 429)
320
+ return new RateLimitError(path, retryMs, detail, errBody, code, { error, subcode }, metadata);
321
+ return new ApiError(path, resp.status, resp.statusText, detail, errBody, code, retryMs, { error, subcode }, metadata);
322
+ }
323
+ /** Open a streaming SSE connection, returning the ReadableStream body. */
324
+ export async function apiStream(config, path, options = {}) {
325
+ assertSafeOrigin(config, config.streamApiUrl);
326
+ const url = `${config.streamApiUrl}${path}`;
327
+ const auth = await freshAuthHeaders(config);
328
+ const resp = await fetch(url, {
329
+ redirect: "error",
330
+ method: "POST",
331
+ headers: {
332
+ Accept: "text/event-stream",
333
+ "Content-Type": "application/json",
334
+ ...auth,
335
+ ...options.headers,
336
+ },
337
+ body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
338
+ signal: options.signal,
339
+ }).catch((error) => {
340
+ traceRequest("POST", url, null);
341
+ throw error;
342
+ });
343
+ traceRequest("POST", url, resp.status, resp.headers.get("x-request-id"));
344
+ if (resp.status === 401) {
345
+ throw new AuthError(path);
346
+ }
347
+ if (!resp.ok) {
348
+ throw streamRefusal(path, resp, await resp.text().catch(() => ""));
349
+ }
350
+ if (!resp.body) {
351
+ throw new NetworkError(path, new Error("Response has no body"));
352
+ }
353
+ return resp.body;
354
+ }
355
+ function delay(ms, signal) {
356
+ return new Promise((resolve, reject) => {
357
+ if (signal?.aborted) {
358
+ reject(signal.reason);
359
+ return;
360
+ }
361
+ const abort = () => { clearTimeout(timer); reject(signal?.reason); };
362
+ const timer = setTimeout(() => {
363
+ signal?.removeEventListener("abort", abort);
364
+ resolve();
365
+ }, ms);
366
+ signal?.addEventListener("abort", abort, { once: true });
367
+ });
368
+ }
@@ -0,0 +1,76 @@
1
+ import { CLOUD_API_BASE, CLOUD_ENDPOINT, type ApiKeyCredential, type OAuthCredential, type OmicsCredential } from "./credentials.js";
2
+ export interface AuthVerifyResponse {
3
+ auth_mode?: "api_key" | "oauth" | string;
4
+ user_id?: string;
5
+ email?: string;
6
+ org_id?: string;
7
+ tier?: string;
8
+ valid?: boolean;
9
+ [key: string]: unknown;
10
+ }
11
+ export interface BrowserLoginOptions {
12
+ apiUrl?: string;
13
+ openBrowser: (url: string) => void | Promise<void>;
14
+ timeoutMs?: number;
15
+ onAuthUrl?: (url: string) => void;
16
+ tenant?: string;
17
+ }
18
+ export interface DeviceLoginOptions {
19
+ apiUrl?: string;
20
+ onVerification: (info: DeviceStartResponse) => void | Promise<void>;
21
+ wait?: (ms: number) => Promise<void>;
22
+ maxWaitMs?: number;
23
+ tenant?: string;
24
+ }
25
+ export interface DeviceStartResponse {
26
+ device_code: string;
27
+ user_code: string;
28
+ verification_uri: string;
29
+ verification_uri_complete?: string;
30
+ expires_at?: string;
31
+ interval?: number;
32
+ [key: string]: unknown;
33
+ }
34
+ interface CallbackResult {
35
+ code: string;
36
+ state?: string;
37
+ }
38
+ interface CallbackServer {
39
+ callbackUrl: string;
40
+ setExpectedState: (state: string) => void;
41
+ waitForCode: () => Promise<CallbackResult>;
42
+ close: () => Promise<void>;
43
+ }
44
+ export declare function loginWithApiKey(options: {
45
+ apiKey: string;
46
+ apiUrl?: string;
47
+ }): Promise<{
48
+ credential: ApiKeyCredential;
49
+ verify: AuthVerifyResponse;
50
+ }>;
51
+ export declare function runBrowserLogin(options: BrowserLoginOptions): Promise<OAuthCredential>;
52
+ export declare function exchangeCliAuthCode(options: {
53
+ apiUrl?: string;
54
+ endpoint?: string;
55
+ transactionId: string;
56
+ transactionSecret: string;
57
+ code: string;
58
+ }): Promise<OAuthCredential>;
59
+ export declare function runDeviceLogin(options: DeviceLoginOptions): Promise<OAuthCredential>;
60
+ export declare function verifyCurrentCredential(options?: {
61
+ apiUrl?: string;
62
+ profile?: string;
63
+ }): Promise<AuthVerifyResponse>;
64
+ export declare function logoutStoredCredential(options?: {
65
+ apiUrl?: string;
66
+ profile?: string;
67
+ }): Promise<{
68
+ removed: boolean;
69
+ revoked: boolean;
70
+ }>;
71
+ export declare function createCliAuthCallbackServer(options: {
72
+ state: string;
73
+ timeoutMs?: number;
74
+ }): Promise<CallbackServer>;
75
+ export { CLOUD_API_BASE, CLOUD_ENDPOINT };
76
+ export type { ApiKeyCredential, OAuthCredential, OmicsCredential };