omics-os 0.0.1 → 1.3.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.
- package/LICENSE +664 -0
- package/README.md +384 -4
- package/package.json +34 -12
- package/packages/cli/dist/index.js +154 -0
- package/packages/cloud-client/dist/agents.d.ts +20 -0
- package/packages/cloud-client/dist/agents.js +69 -0
- package/packages/cloud-client/dist/apiClient.d.ts +44 -0
- package/packages/cloud-client/dist/apiClient.js +368 -0
- package/packages/cloud-client/dist/auth.d.ts +76 -0
- package/packages/cloud-client/dist/auth.js +463 -0
- package/packages/cloud-client/dist/biovault/approval.d.ts +40 -0
- package/packages/cloud-client/dist/biovault/approval.js +38 -0
- package/packages/cloud-client/dist/biovault/assurance.d.ts +10 -0
- package/packages/cloud-client/dist/biovault/assurance.js +14 -0
- package/packages/cloud-client/dist/biovault/client.d.ts +76 -0
- package/packages/cloud-client/dist/biovault/client.js +212 -0
- package/packages/cloud-client/dist/biovault/compat.d.ts +29 -0
- package/packages/cloud-client/dist/biovault/compat.js +90 -0
- package/packages/cloud-client/dist/biovault/entries.d.ts +143 -0
- package/packages/cloud-client/dist/biovault/entries.js +359 -0
- package/packages/cloud-client/dist/biovault/errors.d.ts +18 -0
- package/packages/cloud-client/dist/biovault/errors.js +90 -0
- package/packages/cloud-client/dist/biovault/fields.d.ts +7 -0
- package/packages/cloud-client/dist/biovault/fields.js +42 -0
- package/packages/cloud-client/dist/biovault/identity.d.ts +10 -0
- package/packages/cloud-client/dist/biovault/identity.js +43 -0
- package/packages/cloud-client/dist/biovault/index.d.ts +15 -0
- package/packages/cloud-client/dist/biovault/index.js +16 -0
- package/packages/cloud-client/dist/biovault/instructionMatch.d.ts +32 -0
- package/packages/cloud-client/dist/biovault/instructionMatch.js +118 -0
- package/packages/cloud-client/dist/biovault/pending.d.ts +41 -0
- package/packages/cloud-client/dist/biovault/pending.js +208 -0
- package/packages/cloud-client/dist/biovault/preCommit.d.ts +10 -0
- package/packages/cloud-client/dist/biovault/preCommit.js +10 -0
- package/packages/cloud-client/dist/biovault/provenance.d.ts +45 -0
- package/packages/cloud-client/dist/biovault/provenance.js +55 -0
- package/packages/cloud-client/dist/biovault/vendor/packageDeliveryV1.generated.d.ts +3981 -0
- package/packages/cloud-client/dist/biovault/vendor/packageDeliveryV1.generated.js +3632 -0
- package/packages/cloud-client/dist/biovault/vendor/runV1.generated.d.ts +2326 -0
- package/packages/cloud-client/dist/biovault/vendor/runV1.generated.js +491 -0
- package/packages/cloud-client/dist/biovault/wireShape.d.ts +25 -0
- package/packages/cloud-client/dist/biovault/wireShape.js +88 -0
- package/packages/cloud-client/dist/bootstrap.d.ts +4 -0
- package/packages/cloud-client/dist/bootstrap.js +19 -0
- package/packages/cloud-client/dist/config.d.ts +44 -0
- package/packages/cloud-client/dist/config.js +309 -0
- package/packages/cloud-client/dist/credentials.d.ts +96 -0
- package/packages/cloud-client/dist/credentials.js +395 -0
- package/packages/cloud-client/dist/editor.d.ts +77 -0
- package/packages/cloud-client/dist/editor.js +278 -0
- package/packages/cloud-client/dist/errors.d.ts +27 -0
- package/packages/cloud-client/dist/errors.js +102 -0
- package/packages/cloud-client/dist/exports.d.ts +19 -0
- package/packages/cloud-client/dist/exports.js +85 -0
- package/packages/cloud-client/dist/featureFlags.d.ts +10 -0
- package/packages/cloud-client/dist/featureFlags.js +36 -0
- package/packages/cloud-client/dist/files.d.ts +35 -0
- package/packages/cloud-client/dist/files.js +109 -0
- package/packages/cloud-client/dist/index.d.ts +29 -0
- package/packages/cloud-client/dist/index.js +22 -0
- package/packages/cloud-client/dist/multipartUpload.d.ts +99 -0
- package/packages/cloud-client/dist/multipartUpload.js +624 -0
- package/packages/cloud-client/dist/projects.d.ts +42 -0
- package/packages/cloud-client/dist/projects.js +119 -0
- package/packages/cloud-client/dist/resources.d.ts +8 -0
- package/packages/cloud-client/dist/resources.js +26 -0
- package/packages/cloud-client/dist/sessions.d.ts +67 -0
- package/packages/cloud-client/dist/sessions.js +187 -0
- package/packages/cloud-client/dist/templates.d.ts +4 -0
- package/packages/cloud-client/dist/templates.js +12 -0
- package/packages/cloud-client/dist/types.d.ts +431 -0
- package/packages/cloud-client/dist/types.js +94 -0
- package/packages/cloud-client/dist/uploads.d.ts +93 -0
- package/packages/cloud-client/dist/uploads.js +61 -0
- package/packages/cloud-client/dist/vault.d.ts +20 -0
- package/packages/cloud-client/dist/vault.js +43 -0
- package/packages/cloud-client/dist/vectorSearch.d.ts +3 -0
- package/packages/cloud-client/dist/vectorSearch.js +12 -0
- package/packages/tui/dist/lobster.mjs +273 -0
- package/skills/omics-os-cloud/SKILL.md +24 -0
- package/skills/omics-os-lobster/SKILL.md +24 -0
- package/bin/omics-os.js +0 -5
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
/** Editor — LaTeX generation, file CRUD, compile, download. */
|
|
2
|
+
import { apiFetch } from "./apiClient.js";
|
|
3
|
+
import { freshAuthHeaders } from "./config.js";
|
|
4
|
+
import { AuthError, ApiError, UnknownOutcomeError, UnreadableResponseError } from "./types.js";
|
|
5
|
+
/** Start LaTeX generation for a session (async job, returns 202). */
|
|
6
|
+
export async function editorGenerate(config, sessionId, options) {
|
|
7
|
+
const qs = options?.force ? "?force=true" : "";
|
|
8
|
+
return apiFetch(config, `/editor/${sessionId}/generate${qs}`, { method: "POST" });
|
|
9
|
+
}
|
|
10
|
+
/** Poll LaTeX generation job status. */
|
|
11
|
+
export async function editorPollGenerate(config, sessionId, jobId) {
|
|
12
|
+
return apiFetch(config, `/editor/${sessionId}/generate/${jobId}`);
|
|
13
|
+
}
|
|
14
|
+
/** Get editor project metadata (lightweight — no S3 list). */
|
|
15
|
+
export async function editorMeta(config, sessionId) {
|
|
16
|
+
return apiFetch(config, `/editor/${sessionId}/meta`);
|
|
17
|
+
}
|
|
18
|
+
/** List all files in the editor project. */
|
|
19
|
+
export async function editorListFiles(config, sessionId) {
|
|
20
|
+
const data = await apiFetch(config, `/editor/${sessionId}/files`);
|
|
21
|
+
return data.files ?? [];
|
|
22
|
+
}
|
|
23
|
+
/** Get (pull) editor file content. Returns raw bytes. */
|
|
24
|
+
export async function editorPullFile(config, sessionId, filePath, options) {
|
|
25
|
+
const url = `${config.apiUrl}/editor/${sessionId}/files/${encodeURIComponent(filePath)}`;
|
|
26
|
+
const auth = await freshAuthHeaders(config);
|
|
27
|
+
const resp = await fetch(url, {
|
|
28
|
+
redirect: "error",
|
|
29
|
+
headers: { ...auth },
|
|
30
|
+
signal: options?.signal,
|
|
31
|
+
});
|
|
32
|
+
if (resp.status === 401)
|
|
33
|
+
throw new AuthError(`/editor/${sessionId}/files/${filePath}`);
|
|
34
|
+
if (!resp.ok) {
|
|
35
|
+
throw new ApiError(`/editor/${sessionId}/files/${filePath}`, resp.status, resp.statusText);
|
|
36
|
+
}
|
|
37
|
+
return resp.arrayBuffer();
|
|
38
|
+
}
|
|
39
|
+
/** Save (push) editor file content. */
|
|
40
|
+
export async function editorPushFile(config, sessionId, filePath, content) {
|
|
41
|
+
const url = `${config.apiUrl}/editor/${sessionId}/files/${encodeURIComponent(filePath)}`;
|
|
42
|
+
const auth = await freshAuthHeaders(config);
|
|
43
|
+
const encoded = typeof content === "string" ? new TextEncoder().encode(content) : content;
|
|
44
|
+
const resp = await fetch(url, {
|
|
45
|
+
redirect: "error",
|
|
46
|
+
method: "PUT",
|
|
47
|
+
headers: {
|
|
48
|
+
"Content-Type": "application/octet-stream",
|
|
49
|
+
...auth,
|
|
50
|
+
},
|
|
51
|
+
body: encoded,
|
|
52
|
+
});
|
|
53
|
+
if (resp.status === 401)
|
|
54
|
+
throw new AuthError(`/editor/${sessionId}/files/${filePath}`);
|
|
55
|
+
if (!resp.ok) {
|
|
56
|
+
let detail;
|
|
57
|
+
try {
|
|
58
|
+
const errBody = (await resp.json());
|
|
59
|
+
detail = String(errBody.detail ?? "").slice(0, 200) || undefined;
|
|
60
|
+
}
|
|
61
|
+
catch { /* not JSON */ }
|
|
62
|
+
throw new ApiError(`/editor/${sessionId}/files/${filePath}`, resp.status, resp.statusText, detail);
|
|
63
|
+
}
|
|
64
|
+
return (await resp.json());
|
|
65
|
+
}
|
|
66
|
+
/** Compile LaTeX via the backend proxy. Returns raw PDF bytes. */
|
|
67
|
+
export async function editorCompile(config, sessionId, options) {
|
|
68
|
+
const url = `${config.apiUrl}/editor/${sessionId}/compile`;
|
|
69
|
+
const auth = await freshAuthHeaders(config);
|
|
70
|
+
const body = options?.resources
|
|
71
|
+
? JSON.stringify({ compiler: options.compiler ?? "pdflatex", resources: options.resources })
|
|
72
|
+
: undefined;
|
|
73
|
+
const resp = await fetch(url, {
|
|
74
|
+
redirect: "error",
|
|
75
|
+
method: "POST",
|
|
76
|
+
headers: {
|
|
77
|
+
"Content-Type": "application/json",
|
|
78
|
+
...auth,
|
|
79
|
+
},
|
|
80
|
+
body,
|
|
81
|
+
signal: options?.signal,
|
|
82
|
+
});
|
|
83
|
+
if (resp.status === 401)
|
|
84
|
+
throw new AuthError(`/editor/${sessionId}/compile`);
|
|
85
|
+
if (!resp.ok) {
|
|
86
|
+
let detail;
|
|
87
|
+
try {
|
|
88
|
+
const errBody = (await resp.json());
|
|
89
|
+
detail = String(errBody.detail ?? errBody.error ?? "").slice(0, 200) || undefined;
|
|
90
|
+
}
|
|
91
|
+
catch { /* not JSON */ }
|
|
92
|
+
throw new ApiError(`/editor/${sessionId}/compile`, resp.status, resp.statusText, detail);
|
|
93
|
+
}
|
|
94
|
+
// Only a 200 PDF is a finished compile. The server can answer 202 with a
|
|
95
|
+
// JSON job description while it compiles; that must never be saved as a PDF.
|
|
96
|
+
const contentType = (resp.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
|
|
97
|
+
const bytes = await resp.arrayBuffer();
|
|
98
|
+
const magic = new TextDecoder().decode(new Uint8Array(bytes, 0, Math.min(5, bytes.byteLength)));
|
|
99
|
+
if (resp.status !== 200 || contentType !== "application/pdf" || magic !== "%PDF-") {
|
|
100
|
+
const error = new UnreadableResponseError(`/editor/${sessionId}/compile`, resp.status, resp.statusText);
|
|
101
|
+
error.publicMessage =
|
|
102
|
+
`The server did not return a PDF (HTTP ${resp.status}, ${contentType || "no content type"}); nothing was written.` +
|
|
103
|
+
(resp.status === 202 ? " The compile may still be running." : "");
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
return bytes;
|
|
107
|
+
}
|
|
108
|
+
/** Download entire editor project as a zip. Returns raw zip bytes. */
|
|
109
|
+
export async function editorDownload(config, sessionId, options) {
|
|
110
|
+
const url = `${config.apiUrl}/editor/${sessionId}/download-zip`;
|
|
111
|
+
const auth = await freshAuthHeaders(config);
|
|
112
|
+
const resp = await fetch(url, {
|
|
113
|
+
redirect: "error",
|
|
114
|
+
method: "POST",
|
|
115
|
+
headers: { ...auth },
|
|
116
|
+
signal: options?.signal,
|
|
117
|
+
});
|
|
118
|
+
if (resp.status === 401)
|
|
119
|
+
throw new AuthError(`/editor/${sessionId}/download-zip`);
|
|
120
|
+
if (!resp.ok) {
|
|
121
|
+
let detail;
|
|
122
|
+
try {
|
|
123
|
+
const errBody = (await resp.json());
|
|
124
|
+
detail = String(errBody.detail ?? "").slice(0, 200) || undefined;
|
|
125
|
+
}
|
|
126
|
+
catch { /* not JSON */ }
|
|
127
|
+
throw new ApiError(`/editor/${sessionId}/download-zip`, resp.status, resp.statusText, detail);
|
|
128
|
+
}
|
|
129
|
+
return resp.arrayBuffer();
|
|
130
|
+
}
|
|
131
|
+
/** Start compiling the stored editor project (202 + job id). */
|
|
132
|
+
export async function editorStartCompile(config, sessionId, options) {
|
|
133
|
+
return apiFetch(config, `/editor/${sessionId}/compile`, {
|
|
134
|
+
method: "POST",
|
|
135
|
+
signal: options?.signal,
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
/** Poll a compile job. */
|
|
139
|
+
export async function editorCompileStatus(config, sessionId, jobId, options) {
|
|
140
|
+
return apiFetch(config, `/editor/${sessionId}/compile/${encodeURIComponent(jobId)}`, { signal: options?.signal });
|
|
141
|
+
}
|
|
142
|
+
function compileProblem(path, kind, message, code) {
|
|
143
|
+
const error = new ApiError(path, 0, "", undefined, undefined, code);
|
|
144
|
+
error.kind = kind;
|
|
145
|
+
error.publicMessage = message;
|
|
146
|
+
return error;
|
|
147
|
+
}
|
|
148
|
+
/** Settle with `promise`, or reject with the signal's reason once it aborts. */
|
|
149
|
+
function untilAborted(promise, signal) {
|
|
150
|
+
if (!signal)
|
|
151
|
+
return promise;
|
|
152
|
+
return new Promise((resolve, reject) => {
|
|
153
|
+
const onAbort = () => reject(signal.reason);
|
|
154
|
+
// Observe the promise first: once abandoned, its later rejection must not
|
|
155
|
+
// go unhandled.
|
|
156
|
+
promise.then((value) => { signal.removeEventListener("abort", onAbort); resolve(value); }, (error) => { signal.removeEventListener("abort", onAbort); reject(error); });
|
|
157
|
+
if (signal.aborted) {
|
|
158
|
+
onAbort();
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
/** Download the finished PDF from its signed link. The link carries its own
|
|
165
|
+
* authorization, so no CLI credential is sent; only an https link on S3 is
|
|
166
|
+
* followed, without redirects, and only PDF bytes are returned. Failure
|
|
167
|
+
* messages never include the link (it is a credential while it lasts). */
|
|
168
|
+
export async function fetchCompiledPdf(pdfUrl, options) {
|
|
169
|
+
const where = "compiled PDF";
|
|
170
|
+
let url = null;
|
|
171
|
+
try {
|
|
172
|
+
url = new URL(pdfUrl);
|
|
173
|
+
}
|
|
174
|
+
catch { /* refused below */ }
|
|
175
|
+
if (!url || url.protocol !== "https:" || url.username !== "" || url.password !== "" ||
|
|
176
|
+
!url.hostname.toLowerCase().endsWith(".amazonaws.com")) {
|
|
177
|
+
throw compileProblem(where, "unreadable", "The server's PDF link is not an https S3 link; nothing was written.");
|
|
178
|
+
}
|
|
179
|
+
const signal = options?.signal;
|
|
180
|
+
let resp;
|
|
181
|
+
let bytes;
|
|
182
|
+
try {
|
|
183
|
+
resp = await untilAborted(fetch(url, {
|
|
184
|
+
redirect: "error",
|
|
185
|
+
method: "GET",
|
|
186
|
+
headers: { Accept: "application/pdf" },
|
|
187
|
+
signal,
|
|
188
|
+
}), signal);
|
|
189
|
+
const body = resp;
|
|
190
|
+
bytes = await untilAborted(body.arrayBuffer(), signal).catch((error) => {
|
|
191
|
+
void body.body?.cancel().catch(() => { });
|
|
192
|
+
throw error;
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
if (signal?.aborted)
|
|
197
|
+
throw signal.reason;
|
|
198
|
+
throw compileProblem(where, "network", "The compiled PDF could not be downloaded; nothing was written.");
|
|
199
|
+
}
|
|
200
|
+
const contentType = (resp.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
|
|
201
|
+
const magic = new TextDecoder().decode(new Uint8Array(bytes, 0, Math.min(5, bytes.byteLength)));
|
|
202
|
+
if (resp.status !== 200 || contentType !== "application/pdf" || magic !== "%PDF-") {
|
|
203
|
+
throw compileProblem(where, "unreadable", `The PDF link did not return a PDF (HTTP ${resp.status}, ${contentType || "no content type"}); nothing was written.`);
|
|
204
|
+
}
|
|
205
|
+
return bytes;
|
|
206
|
+
}
|
|
207
|
+
const sleepFor = (ms, signal) => new Promise((resolve, reject) => {
|
|
208
|
+
if (signal?.aborted) {
|
|
209
|
+
reject(signal.reason);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
const timer = setTimeout(() => { signal?.removeEventListener("abort", onAbort); resolve(); }, ms);
|
|
213
|
+
const onAbort = () => { clearTimeout(timer); reject(signal?.reason); };
|
|
214
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
215
|
+
});
|
|
216
|
+
/** Compile the stored editor project and return the PDF: start a job, poll
|
|
217
|
+
* until it finishes, then download the PDF from its signed link. */
|
|
218
|
+
export async function editorCompileToPdf(config, sessionId, options) {
|
|
219
|
+
const path = `/editor/${sessionId}/compile`;
|
|
220
|
+
const intervalMs = options?.intervalMs ?? 2_000;
|
|
221
|
+
const timeoutMs = options?.timeoutMs ?? 330_000;
|
|
222
|
+
const sleep = options?.sleep ?? sleepFor;
|
|
223
|
+
// One budget for the whole wait: the start, every poll, the pauses and the
|
|
224
|
+
// PDF download all stop when it runs out, even if a request stalls.
|
|
225
|
+
const budget = new AbortController();
|
|
226
|
+
const timer = setTimeout(() => budget.abort(new Error("compile wait budget used up")), timeoutMs);
|
|
227
|
+
const signal = options?.signal ? AbortSignal.any([options.signal, budget.signal]) : budget.signal;
|
|
228
|
+
const outOfTime = (started) => compileProblem(path, "timeout", `The compile ${started ? "is still running" : "request got no answer"} after ${Math.round(timeoutMs / 1000)} s` +
|
|
229
|
+
`${started ? "" : " (it may have started)"}; nothing was written. ` +
|
|
230
|
+
"Open it in the Omics-OS Editor: https://editor.omics-os.com");
|
|
231
|
+
let started = false;
|
|
232
|
+
try {
|
|
233
|
+
return await waitForCompile();
|
|
234
|
+
}
|
|
235
|
+
catch (error) {
|
|
236
|
+
if (budget.signal.aborted && !options?.signal?.aborted)
|
|
237
|
+
throw outOfTime(started);
|
|
238
|
+
throw error;
|
|
239
|
+
}
|
|
240
|
+
finally {
|
|
241
|
+
clearTimeout(timer);
|
|
242
|
+
}
|
|
243
|
+
async function waitForCompile() {
|
|
244
|
+
const deadline = Date.now() + timeoutMs;
|
|
245
|
+
let job;
|
|
246
|
+
try {
|
|
247
|
+
job = await editorStartCompile(config, sessionId, { signal });
|
|
248
|
+
}
|
|
249
|
+
catch (error) {
|
|
250
|
+
// An unanswered start is never sent again: a second POST would start a second job.
|
|
251
|
+
if (error instanceof UnknownOutcomeError && budget.signal.aborted)
|
|
252
|
+
throw outOfTime(false);
|
|
253
|
+
throw error;
|
|
254
|
+
}
|
|
255
|
+
started = true;
|
|
256
|
+
if (typeof job?.job_id !== "string" || !job.job_id) {
|
|
257
|
+
throw new UnreadableResponseError(path, 202, "Accepted");
|
|
258
|
+
}
|
|
259
|
+
for (;;) {
|
|
260
|
+
const status = await editorCompileStatus(config, sessionId, job.job_id, { signal });
|
|
261
|
+
if (status?.status === "complete") {
|
|
262
|
+
if (typeof status.pdf_url !== "string") {
|
|
263
|
+
throw compileProblem(path, "unreadable", "The compile finished without a PDF link; nothing was written.");
|
|
264
|
+
}
|
|
265
|
+
return { pdf: await fetchCompiledPdf(status.pdf_url, { signal }), jobId: job.job_id };
|
|
266
|
+
}
|
|
267
|
+
if (status?.status === "failed") {
|
|
268
|
+
const reason = typeof status.error === "string" && status.error.trim()
|
|
269
|
+
? status.error.trim().slice(0, 300) : "Compilation failed";
|
|
270
|
+
throw compileProblem(path, "compile_failed", `The compile failed: ${reason}. Nothing was written.`, typeof status.error_code === "string" ? status.error_code : undefined);
|
|
271
|
+
}
|
|
272
|
+
if (Date.now() >= deadline)
|
|
273
|
+
throw outOfTime(true);
|
|
274
|
+
options?.onStatus?.(String(status?.status ?? "pending"));
|
|
275
|
+
await sleep(intervalMs, signal);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { ApiError } from "./types.js";
|
|
2
|
+
export declare function readApiError(body: unknown): {
|
|
3
|
+
code: string | null;
|
|
4
|
+
retryable: boolean | null;
|
|
5
|
+
requestId: string | null;
|
|
6
|
+
};
|
|
7
|
+
export interface FormattedError {
|
|
8
|
+
payload: {
|
|
9
|
+
error: string;
|
|
10
|
+
kind: string;
|
|
11
|
+
status: number | null;
|
|
12
|
+
code: string | null;
|
|
13
|
+
retryable: boolean | null;
|
|
14
|
+
request_id: string | null;
|
|
15
|
+
};
|
|
16
|
+
exitCode: number;
|
|
17
|
+
}
|
|
18
|
+
/** Pure: output and process termination remain the caller's responsibility. */
|
|
19
|
+
export declare function formatError(error: unknown): FormattedError;
|
|
20
|
+
/** Seconds the server asked a refused request to wait: the body's retry_after, else Retry-After; null when it sent none. */
|
|
21
|
+
export declare function refusalWaitSeconds(error: ApiError): number | null;
|
|
22
|
+
/**
|
|
23
|
+
* Plain text for the chat route's pre-run refusals (session_busy, rate_limited, prompt_too_large),
|
|
24
|
+
* or undefined for any other error, so callers keep their own text for older servers.
|
|
25
|
+
* Seconds are shown only when the server sent them.
|
|
26
|
+
*/
|
|
27
|
+
export declare function chatRefusalMessage(error: ApiError): string | undefined;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/** Shared error metadata and presentation; response bodies never classify errors. */
|
|
2
|
+
import { describeErrorBody } from "./apiClient.js";
|
|
3
|
+
import { ApiError, AuthError, TenantAccessDeniedError, RateLimitError, NetworkError, UnknownOutcomeError, UnreadableResponseError, } from "./types.js";
|
|
4
|
+
function plainObject(value) {
|
|
5
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
6
|
+
return false;
|
|
7
|
+
const prototype = Object.getPrototypeOf(value);
|
|
8
|
+
return prototype === Object.prototype || prototype === null;
|
|
9
|
+
}
|
|
10
|
+
export function readApiError(body) {
|
|
11
|
+
const outer = plainObject(body) ? body : undefined;
|
|
12
|
+
const fields = outer && plainObject(outer.detail) ? outer.detail : outer;
|
|
13
|
+
return {
|
|
14
|
+
code: describeErrorBody(outer).code ?? null,
|
|
15
|
+
retryable: typeof fields?.retryable === "boolean" ? fields.retryable : null,
|
|
16
|
+
requestId: typeof fields?.request_id === "string" ? fields.request_id : null,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
/** Pure: output and process termination remain the caller's responsibility. */
|
|
20
|
+
export function formatError(error) {
|
|
21
|
+
let kind;
|
|
22
|
+
let message;
|
|
23
|
+
if (error instanceof AuthError) {
|
|
24
|
+
kind = "session";
|
|
25
|
+
message = error.message;
|
|
26
|
+
}
|
|
27
|
+
else if (error instanceof TenantAccessDeniedError) {
|
|
28
|
+
kind = "forbidden";
|
|
29
|
+
message = error.message;
|
|
30
|
+
}
|
|
31
|
+
else if (error instanceof RateLimitError) {
|
|
32
|
+
kind = "rate_limited";
|
|
33
|
+
const wait = error.retryAfterMs ? `${Math.ceil(error.retryAfterMs / 1000)}s` : "a few seconds";
|
|
34
|
+
message = error.detail ? `${error.detail} Retry after ${wait}.` : `Rate limited. Retry after ${wait}.`;
|
|
35
|
+
}
|
|
36
|
+
else if (error instanceof UnknownOutcomeError) {
|
|
37
|
+
kind = "unknown_outcome";
|
|
38
|
+
message = error.message;
|
|
39
|
+
}
|
|
40
|
+
else if (error instanceof UnreadableResponseError) {
|
|
41
|
+
kind = "unreadable";
|
|
42
|
+
message = error.message;
|
|
43
|
+
}
|
|
44
|
+
else if (error instanceof NetworkError) {
|
|
45
|
+
kind = "network";
|
|
46
|
+
message = `Network error: ${error.message}`;
|
|
47
|
+
}
|
|
48
|
+
else if (error instanceof ApiError) {
|
|
49
|
+
kind = error.status === 403 ? "forbidden" : error.status === 404 ? "not_found" : "server";
|
|
50
|
+
const hintless = ["worker_not_started", "session_busy"].includes(error.types.error ?? error.code ?? "");
|
|
51
|
+
const hint = error.retryAfterMs && !hintless ? ` Retry after ${Math.ceil(error.retryAfterMs / 1000)}s.` : "";
|
|
52
|
+
message = `API error (${error.status}${error.code ? `, ${error.code}` : ""}): ${error.message}${hint}`;
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
kind = "internal";
|
|
56
|
+
message = String(error);
|
|
57
|
+
}
|
|
58
|
+
const api = error instanceof ApiError ? error : undefined;
|
|
59
|
+
return {
|
|
60
|
+
payload: {
|
|
61
|
+
error: api?.publicMessage ?? message,
|
|
62
|
+
kind: api?.kind ?? kind,
|
|
63
|
+
status: api?.status ? api.status : null,
|
|
64
|
+
code: api?.code ?? null,
|
|
65
|
+
retryable: api?.retryable ?? null,
|
|
66
|
+
request_id: api?.requestId ?? null,
|
|
67
|
+
},
|
|
68
|
+
exitCode: api?.exitCode ?? 1,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
const LIMITS = ["turns_per_minute", "turns_per_hour", "running_turns_user", "running_turns_tenant", "ip"];
|
|
72
|
+
const positiveInteger = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
|
|
73
|
+
/** Seconds the server asked a refused request to wait: the body's retry_after, else Retry-After; null when it sent none. */
|
|
74
|
+
export function refusalWaitSeconds(error) {
|
|
75
|
+
return positiveInteger(error.body?.retry_after) ??
|
|
76
|
+
(error.retryAfterMs ? positiveInteger(Math.ceil(error.retryAfterMs / 1000)) : undefined) ?? null;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Plain text for the chat route's pre-run refusals (session_busy, rate_limited, prompt_too_large),
|
|
80
|
+
* or undefined for any other error, so callers keep their own text for older servers.
|
|
81
|
+
* Seconds are shown only when the server sent them.
|
|
82
|
+
*/
|
|
83
|
+
export function chatRefusalMessage(error) {
|
|
84
|
+
const body = error.body ?? {};
|
|
85
|
+
// The type in `error`; a body may add its own `code` key.
|
|
86
|
+
const code = error.types.error ?? error.code;
|
|
87
|
+
if (error.status === 429 && code === "session_busy") {
|
|
88
|
+
return "This session is still running a turn. Wait for it to finish, or cancel it, then try again.";
|
|
89
|
+
}
|
|
90
|
+
if (error.status === 429 && code === "rate_limited") {
|
|
91
|
+
const limit = typeof body.limit === "string" && LIMITS.includes(body.limit) ? ` (${body.limit})` : "";
|
|
92
|
+
const seconds = refusalWaitSeconds(error);
|
|
93
|
+
return `Too many requests${limit}. ${seconds ? `Try again in ${seconds} s.` : "Try again later."}`;
|
|
94
|
+
}
|
|
95
|
+
if (error.status === 413 && code === "prompt_too_large") {
|
|
96
|
+
const actual = positiveInteger(body.actual_bytes);
|
|
97
|
+
const max = positiveInteger(body.max_bytes);
|
|
98
|
+
const sizes = actual && max ? ` (${actual} bytes; the limit is ${max})` : "";
|
|
99
|
+
return `The message is too large${sizes}. Shorten it and send again.`;
|
|
100
|
+
}
|
|
101
|
+
return undefined;
|
|
102
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Session exports — report, pipeline notebook, slide deck (async job pattern). */
|
|
2
|
+
import type { AppConfig, ExportType, ExportJobResponse } from "./types.js";
|
|
3
|
+
/** Start an export job. Returns 202 with job_id. */
|
|
4
|
+
export declare function startExport(config: AppConfig, sessionId: string, options?: {
|
|
5
|
+
exportType?: ExportType;
|
|
6
|
+
format?: "pdf" | "pptx";
|
|
7
|
+
}): Promise<ExportJobResponse>;
|
|
8
|
+
/** Poll export job status. */
|
|
9
|
+
export declare function pollExportStatus(config: AppConfig, sessionId: string, jobId: string): Promise<ExportJobResponse>;
|
|
10
|
+
/** Download an exported file by its relative path. Returns the raw stream. */
|
|
11
|
+
export declare function downloadExport(config: AppConfig, sessionId: string, filePath: string, options?: {
|
|
12
|
+
signal?: AbortSignal;
|
|
13
|
+
}): Promise<ReadableStream<Uint8Array>>;
|
|
14
|
+
/** Poll until export completes or fails (convenience wrapper with timeout). */
|
|
15
|
+
export declare function waitForExport(config: AppConfig, sessionId: string, jobId: string, options?: {
|
|
16
|
+
pollIntervalMs?: number;
|
|
17
|
+
timeoutMs?: number;
|
|
18
|
+
maxConsecutiveFailures?: number;
|
|
19
|
+
}): Promise<ExportJobResponse>;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/** Session exports — report, pipeline notebook, slide deck (async job pattern). */
|
|
2
|
+
import { apiFetch } from "./apiClient.js";
|
|
3
|
+
import { freshAuthHeaders } from "./config.js";
|
|
4
|
+
import { AuthError, ApiError, NetworkError } from "./types.js";
|
|
5
|
+
/** Start an export job. Returns 202 with job_id. */
|
|
6
|
+
export async function startExport(config, sessionId, options) {
|
|
7
|
+
const body = {};
|
|
8
|
+
if (options?.exportType)
|
|
9
|
+
body.export_type = options.exportType;
|
|
10
|
+
if (options?.format)
|
|
11
|
+
body.format = options.format;
|
|
12
|
+
return apiFetch(config, `/sessions/${sessionId}/export`, { method: "POST", body });
|
|
13
|
+
}
|
|
14
|
+
/** Poll export job status. */
|
|
15
|
+
export async function pollExportStatus(config, sessionId, jobId) {
|
|
16
|
+
return apiFetch(config, `/sessions/${sessionId}/export/${jobId}`);
|
|
17
|
+
}
|
|
18
|
+
/** Download an exported file by its relative path. Returns the raw stream. */
|
|
19
|
+
export async function downloadExport(config, sessionId, filePath, options) {
|
|
20
|
+
const url = `${config.apiUrl}/sessions/${sessionId}/files/${encodeURIComponent(filePath)}/download`;
|
|
21
|
+
const auth = await freshAuthHeaders(config);
|
|
22
|
+
const resp = await fetch(url, {
|
|
23
|
+
redirect: "error",
|
|
24
|
+
headers: { ...auth },
|
|
25
|
+
signal: options?.signal,
|
|
26
|
+
});
|
|
27
|
+
if (resp.status === 401) {
|
|
28
|
+
throw new AuthError(`/sessions/${sessionId}/files/${filePath}/download`);
|
|
29
|
+
}
|
|
30
|
+
if (!resp.ok) {
|
|
31
|
+
throw new ApiError(`/sessions/${sessionId}/files/${filePath}/download`, resp.status, resp.statusText);
|
|
32
|
+
}
|
|
33
|
+
if (!resp.body) {
|
|
34
|
+
throw new NetworkError(`/sessions/${sessionId}/files/${filePath}/download`, new Error("No response body"));
|
|
35
|
+
}
|
|
36
|
+
return resp.body;
|
|
37
|
+
}
|
|
38
|
+
/** A poll failure that says nothing about the job itself (it may still finish). */
|
|
39
|
+
function isTransientPollError(error) {
|
|
40
|
+
if (error instanceof AuthError)
|
|
41
|
+
return false;
|
|
42
|
+
if (error instanceof NetworkError)
|
|
43
|
+
return true;
|
|
44
|
+
if (!(error instanceof ApiError))
|
|
45
|
+
return false;
|
|
46
|
+
// A 409 that only means "the worker is still starting" clears by itself.
|
|
47
|
+
if (error.status === 409)
|
|
48
|
+
return (error.types.error ?? error.code) === "worker_hydrating";
|
|
49
|
+
return error.status === 429 || error.status >= 500;
|
|
50
|
+
}
|
|
51
|
+
/** Poll until export completes or fails (convenience wrapper with timeout). */
|
|
52
|
+
export async function waitForExport(config, sessionId, jobId, options) {
|
|
53
|
+
const interval = options?.pollIntervalMs ?? 2000;
|
|
54
|
+
const timeout = options?.timeoutMs ?? 300_000;
|
|
55
|
+
const deadline = Date.now() + timeout;
|
|
56
|
+
// The job keeps running on the server when one poll fails, so a brief outage
|
|
57
|
+
// (network drop, 5xx, 429) must not end the wait. Each failed poll has
|
|
58
|
+
// already been retried by apiFetch; give up after a few in a row.
|
|
59
|
+
const maxConsecutiveFailures = options?.maxConsecutiveFailures ?? 3;
|
|
60
|
+
let failures = 0;
|
|
61
|
+
while (Date.now() < deadline) {
|
|
62
|
+
let status;
|
|
63
|
+
try {
|
|
64
|
+
status = await pollExportStatus(config, sessionId, jobId);
|
|
65
|
+
failures = 0;
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
if (error instanceof ApiError && error.retryable === false)
|
|
69
|
+
throw error;
|
|
70
|
+
if (!isTransientPollError(error) || ++failures >= maxConsecutiveFailures) {
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
// Honour the server's Retry-After, but never wait past the deadline.
|
|
74
|
+
const asked = error instanceof ApiError ? error.retryAfterMs : undefined;
|
|
75
|
+
const wait = Math.min(Math.max(interval, asked ?? 0), Math.max(0, deadline - Date.now()));
|
|
76
|
+
await new Promise((resolve) => setTimeout(resolve, wait));
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if (status.status === "complete" || status.status === "failed") {
|
|
80
|
+
return status;
|
|
81
|
+
}
|
|
82
|
+
await new Promise((resolve) => setTimeout(resolve, interval));
|
|
83
|
+
}
|
|
84
|
+
return { job_id: jobId, status: "failed", error: "Export timed out" };
|
|
85
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Feature flags — fetched once on startup, cached for session lifetime. */
|
|
2
|
+
import type { AppConfig, FeatureFlags } from "./types.js";
|
|
3
|
+
/** Fetch feature flags from backend. Returns defaults on error. */
|
|
4
|
+
export declare function fetchFeatureFlags(config: AppConfig): Promise<FeatureFlags>;
|
|
5
|
+
/** Get cached flags (undefined if not yet fetched). */
|
|
6
|
+
export declare function getCachedFlags(): FeatureFlags | undefined;
|
|
7
|
+
/** Check if a specific flag is enabled. */
|
|
8
|
+
export declare function isFeatureEnabled(flag: keyof FeatureFlags): boolean;
|
|
9
|
+
/** Reset cached flags (useful for testing). */
|
|
10
|
+
export declare function resetFlagsCache(): void;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** Feature flags — fetched once on startup, cached for session lifetime. */
|
|
2
|
+
import { apiFetch } from "./apiClient.js";
|
|
3
|
+
const DEFAULT_FLAGS = {
|
|
4
|
+
projects_datasets: false,
|
|
5
|
+
session_state_read: false,
|
|
6
|
+
session_state_write: false,
|
|
7
|
+
message_ddb_primary: false,
|
|
8
|
+
curated_agent_store: false,
|
|
9
|
+
playground: false,
|
|
10
|
+
};
|
|
11
|
+
let cachedFlags;
|
|
12
|
+
/** Fetch feature flags from backend. Returns defaults on error. */
|
|
13
|
+
export async function fetchFeatureFlags(config) {
|
|
14
|
+
if (cachedFlags)
|
|
15
|
+
return cachedFlags;
|
|
16
|
+
try {
|
|
17
|
+
const data = await apiFetch(config, "/config/flags");
|
|
18
|
+
cachedFlags = { ...DEFAULT_FLAGS, ...data };
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
cachedFlags = DEFAULT_FLAGS;
|
|
22
|
+
}
|
|
23
|
+
return cachedFlags;
|
|
24
|
+
}
|
|
25
|
+
/** Get cached flags (undefined if not yet fetched). */
|
|
26
|
+
export function getCachedFlags() {
|
|
27
|
+
return cachedFlags;
|
|
28
|
+
}
|
|
29
|
+
/** Check if a specific flag is enabled. */
|
|
30
|
+
export function isFeatureEnabled(flag) {
|
|
31
|
+
return cachedFlags?.[flag] ?? false;
|
|
32
|
+
}
|
|
33
|
+
/** Reset cached flags (useful for testing). */
|
|
34
|
+
export function resetFlagsCache() {
|
|
35
|
+
cachedFlags = undefined;
|
|
36
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** File management — upload, download, list, delete, load into session. */
|
|
2
|
+
import type { AppConfig, FileInfo, FileUploadResponse, WorkspaceFileMetadata } from "./types.js";
|
|
3
|
+
/** List files in a session workspace. */
|
|
4
|
+
export declare function listFiles(config: AppConfig, sessionId: string, directory?: string): Promise<FileInfo[]>;
|
|
5
|
+
/** Upload a file to the session workspace (multipart/form-data with streaming). */
|
|
6
|
+
export declare function uploadFile(config: AppConfig, sessionId: string, file: Blob | ArrayBuffer | Uint8Array, filename: string, options?: {
|
|
7
|
+
description?: string;
|
|
8
|
+
signal?: AbortSignal;
|
|
9
|
+
}): Promise<FileUploadResponse>;
|
|
10
|
+
/** Download a file from the session workspace. Returns the raw response body. */
|
|
11
|
+
export declare function downloadFile(config: AppConfig, sessionId: string, filePath: string, options?: {
|
|
12
|
+
inline?: boolean;
|
|
13
|
+
signal?: AbortSignal;
|
|
14
|
+
}): Promise<ReadableStream<Uint8Array>>;
|
|
15
|
+
/** Delete a file from the session workspace. */
|
|
16
|
+
export declare function deleteFile(config: AppConfig, sessionId: string, filePath: string): Promise<void>;
|
|
17
|
+
/** Get workspace file metadata (optimized for large datasets). */
|
|
18
|
+
export declare function getWorkspaceMetadata(config: AppConfig, sessionId: string, directory?: string): Promise<WorkspaceFileMetadata[]>;
|
|
19
|
+
/** Load an uploaded file into the active session for agent processing. */
|
|
20
|
+
export declare function loadFileIntoSession(config: AppConfig, sessionId: string, filePath: string): Promise<{
|
|
21
|
+
success: boolean;
|
|
22
|
+
message: string;
|
|
23
|
+
}>;
|
|
24
|
+
/**
|
|
25
|
+
* Download a session file for saving to disk: the body as a stream and its
|
|
26
|
+
* Content-Length when sent. Asks the stream host first (no CloudFront time
|
|
27
|
+
* limit on long transfers); a 403 there, as when that host requires the
|
|
28
|
+
* CloudFront origin header, falls back to the API host.
|
|
29
|
+
*/
|
|
30
|
+
export declare function downloadFileForSave(config: AppConfig, sessionId: string, filePath: string, options?: {
|
|
31
|
+
signal?: AbortSignal;
|
|
32
|
+
}): Promise<{
|
|
33
|
+
body: ReadableStream<Uint8Array>;
|
|
34
|
+
size: number | null;
|
|
35
|
+
}>;
|