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,462 @@
1
+ import { createServer } from "http";
2
+ import { randomBytes, timingSafeEqual } from "crypto";
3
+ import { apiFetch } from "./apiClient.js";
4
+ import { resolveConfig } from "./config.js";
5
+ import { AuthError, NOT_LOGGED_IN_MESSAGE } from "./types.js";
6
+ import { apiUrlToEndpoint, CLOUD_API_BASE, CLOUD_ENDPOINT, clearActiveProfile, endpointToApiUrl, parseOAuthCredentialResponse, readProfileCredential, resolveAuthBrokerApiUrl, saveStoredCredentials, validateApiOrigin, } from "./credentials.js";
7
+ const LOGIN_TIMEOUT_MS = 120_000;
8
+ const CALLBACK_REQUEST_TIMEOUT_MS = 10_000;
9
+ const MAX_CALLBACK_BODY_BYTES = 16 * 1024;
10
+ const DEVICE_MAX_WAIT_MS = 10 * 60_000;
11
+ export async function loginWithApiKey(options) {
12
+ const apiKey = options.apiKey.trim();
13
+ if (!apiKey.startsWith("omk_")) {
14
+ throw new Error("API key must start with omk_.");
15
+ }
16
+ const apiUrl = normalizeApiUrl(options.apiUrl);
17
+ // The key is stored after this check, and a stored credential goes only to an allowed origin.
18
+ const { safe, origin } = validateApiOrigin(apiUrl);
19
+ if (!safe) {
20
+ throw new AuthError(apiUrl, `Refusing to send credentials to untrusted origin: ${origin}. ` +
21
+ `A key for this endpoint works without login: set OMICS_OS_API_KEY and pass --endpoint.`);
22
+ }
23
+ const config = resolveConfig({ cloud: true, apiUrl, token: apiKey });
24
+ const verify = await apiFetch(config, "/gateway/auth/verify", { timeoutMs: 15_000 });
25
+ const credential = {
26
+ auth_mode: "api_key",
27
+ api_key: apiKey,
28
+ endpoint: apiUrlToEndpoint(config.apiUrl),
29
+ user_id: stringOrUndefined(verify.user_id),
30
+ email: stringOrUndefined(verify.email),
31
+ org_id: stringOrUndefined(verify.org_id),
32
+ tier: stringOrUndefined(verify.tier),
33
+ };
34
+ saveStoredCredentials(credential);
35
+ return { credential, verify };
36
+ }
37
+ export async function runBrowserLogin(options) {
38
+ const apiUrl = normalizeApiUrl(options.apiUrl);
39
+ // Saved credential keeps the requested endpoint (tenant or platform), but the
40
+ // OAuth broker calls always go to the platform — tenant hosts gate them.
41
+ const endpoint = apiUrlToEndpoint(apiUrl);
42
+ const brokerApiUrl = resolveAuthBrokerApiUrl(apiUrl);
43
+ const state = randomBytes(32).toString("hex");
44
+ const receiver = await createCliAuthCallbackServer({ state, timeoutMs: options.timeoutMs });
45
+ try {
46
+ const start = await requestJson(brokerApiUrl, "/gateway/oauth/cli/start", {
47
+ method: "POST",
48
+ body: {
49
+ mode: "local_callback",
50
+ callback_url: receiver.callbackUrl,
51
+ client_name: "omics-os",
52
+ ...(options.tenant ? { tenant: options.tenant } : {}),
53
+ },
54
+ timeoutMs: 15_000,
55
+ });
56
+ const transactionId = stringOrUndefined(start.transaction_id);
57
+ const transactionSecret = stringOrUndefined(start.transaction_secret);
58
+ const callbackState = stringOrUndefined(start.state) ?? state;
59
+ const authUrl = stringOrUndefined(start.authorization_url)
60
+ ?? stringOrUndefined(start.auth_url)
61
+ ?? stringOrUndefined(start.browser_url);
62
+ if (!transactionId || !transactionSecret || !authUrl) {
63
+ throw new Error("CLI auth start response missing transaction metadata.");
64
+ }
65
+ receiver.setExpectedState(callbackState);
66
+ options.onAuthUrl?.(authUrl);
67
+ await options.openBrowser(authUrl);
68
+ const callback = await receiver.waitForCode();
69
+ if (!safeCompare(callbackState, callback.state ?? "")) {
70
+ throw new Error("Invalid CLI auth callback state.");
71
+ }
72
+ const credential = await exchangeCliAuthCode({
73
+ apiUrl: brokerApiUrl,
74
+ endpoint,
75
+ transactionId,
76
+ transactionSecret,
77
+ code: callback.code,
78
+ });
79
+ saveStoredCredentials(credential);
80
+ return credential;
81
+ }
82
+ finally {
83
+ await receiver.close();
84
+ }
85
+ }
86
+ export async function exchangeCliAuthCode(options) {
87
+ const apiUrl = normalizeApiUrl(options.apiUrl);
88
+ const endpoint = options.endpoint ?? apiUrlToEndpoint(apiUrl);
89
+ // Token exchange is a platform broker call; saved credential keeps `endpoint`.
90
+ const brokerApiUrl = resolveAuthBrokerApiUrl(apiUrl);
91
+ const data = await requestJson(brokerApiUrl, "/gateway/oauth/cli/token", {
92
+ method: "POST",
93
+ body: {
94
+ grant_type: "authorization_code",
95
+ transaction_id: options.transactionId,
96
+ transaction_secret: options.transactionSecret,
97
+ handoff_code: options.code,
98
+ },
99
+ timeoutMs: 15_000,
100
+ });
101
+ const credential = parseOAuthCredentialResponse(data, endpoint);
102
+ if (!credential) {
103
+ throw new Error("CLI token response did not contain a valid Omics CLI credential.");
104
+ }
105
+ return credential;
106
+ }
107
+ export async function runDeviceLogin(options) {
108
+ const apiUrl = normalizeApiUrl(options.apiUrl);
109
+ const endpoint = apiUrlToEndpoint(apiUrl);
110
+ // Device broker calls (start + poll) go to platform; saved credential keeps endpoint.
111
+ const brokerApiUrl = resolveAuthBrokerApiUrl(apiUrl);
112
+ const wait = options.wait ?? delay;
113
+ const maxWaitMs = options.maxWaitMs ?? DEVICE_MAX_WAIT_MS;
114
+ const start = await requestJson(brokerApiUrl, "/gateway/oauth/cli/device/start", {
115
+ method: "POST",
116
+ body: {
117
+ client_name: "omics-os",
118
+ ...(options.tenant ? { tenant: options.tenant } : {}),
119
+ },
120
+ timeoutMs: 15_000,
121
+ });
122
+ if (!start.device_code || !start.user_code || !start.verification_uri) {
123
+ throw new Error("Device auth start response missing required fields.");
124
+ }
125
+ await options.onVerification(start);
126
+ let intervalSeconds = Math.max(Number(start.interval ?? 5), 1);
127
+ const startedAt = Date.now();
128
+ while (Date.now() - startedAt < maxWaitMs) {
129
+ const response = await requestJsonWithStatus(brokerApiUrl, "/gateway/oauth/cli/device/token", {
130
+ method: "POST",
131
+ body: {
132
+ device_code: start.device_code,
133
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
134
+ },
135
+ timeoutMs: 15_000,
136
+ });
137
+ if (response.ok) {
138
+ const credential = parseOAuthCredentialResponse(response.body, endpoint);
139
+ if (!credential) {
140
+ throw new Error("Device token response did not contain a valid Omics CLI credential.");
141
+ }
142
+ saveStoredCredentials(credential);
143
+ return credential;
144
+ }
145
+ const errorCode = extractErrorCode(response.body);
146
+ if (errorCode === "authorization_pending") {
147
+ await wait(intervalSeconds * 1000);
148
+ continue;
149
+ }
150
+ if (errorCode === "slow_down") {
151
+ intervalSeconds += 5;
152
+ await wait(intervalSeconds * 1000);
153
+ continue;
154
+ }
155
+ if (errorCode === "expired_token") {
156
+ throw new Error("Device login expired. Run omics-os login --device again.");
157
+ }
158
+ if (errorCode === "access_denied") {
159
+ throw new Error("Device login was denied.");
160
+ }
161
+ throw new Error(`Device login failed${errorCode ? `: ${errorCode}` : ""}.`);
162
+ }
163
+ throw new Error("Device login timed out.");
164
+ }
165
+ export async function verifyCurrentCredential(options = {}) {
166
+ const credential = readProfileCredential(options.profile);
167
+ if (!credential)
168
+ throw new Error(NOT_LOGGED_IN_MESSAGE);
169
+ const apiUrl = normalizeApiUrl(options.apiUrl ?? endpointToApiUrl(credential.endpoint));
170
+ const config = resolveConfig({
171
+ cloud: true,
172
+ apiUrl,
173
+ profile: options.profile,
174
+ });
175
+ return apiFetch(config, "/gateway/auth/verify", { timeoutMs: 15_000 });
176
+ }
177
+ export async function logoutStoredCredential(options = {}) {
178
+ const credential = readProfileCredential(options.profile);
179
+ let revoked = false;
180
+ if (credential?.auth_mode === "oauth") {
181
+ // Revoke is a platform broker call — logout must succeed even if the user has
182
+ // lost access to the tenant whose profile this is. Route to the platform.
183
+ const requestedApiUrl = normalizeApiUrl(options.apiUrl ?? endpointToApiUrl(credential.endpoint));
184
+ const apiUrl = resolveAuthBrokerApiUrl(requestedApiUrl);
185
+ try {
186
+ const config = resolveConfig({ cloud: true, apiUrl, profile: options.profile });
187
+ await apiFetch(config, "/gateway/oauth/cli/revoke", {
188
+ method: "POST",
189
+ body: { credential_id: credential.credential_id },
190
+ timeoutMs: 10_000,
191
+ });
192
+ revoked = true;
193
+ }
194
+ catch {
195
+ revoked = false;
196
+ }
197
+ }
198
+ // Sibling-safe: remove only this profile (defaults to active), preserving
199
+ // other tenant profiles. Whole-file removal only when it was the last one.
200
+ const removed = clearActiveProfile(options.profile);
201
+ return { removed, revoked };
202
+ }
203
+ export async function createCliAuthCallbackServer(options) {
204
+ let expectedState = options.state;
205
+ let settled = false;
206
+ let resolveCode;
207
+ let rejectCode;
208
+ let timeoutId;
209
+ const waitPromise = new Promise((resolve, reject) => {
210
+ resolveCode = (value) => {
211
+ if (settled)
212
+ return;
213
+ settled = true;
214
+ if (timeoutId)
215
+ clearTimeout(timeoutId);
216
+ resolve(value);
217
+ };
218
+ rejectCode = (error) => {
219
+ if (settled)
220
+ return;
221
+ settled = true;
222
+ if (timeoutId)
223
+ clearTimeout(timeoutId);
224
+ reject(error);
225
+ };
226
+ });
227
+ const server = createServer((req, res) => {
228
+ void handleCallbackRequest(req, res, expectedState, resolveCode);
229
+ });
230
+ server.requestTimeout = CALLBACK_REQUEST_TIMEOUT_MS;
231
+ server.headersTimeout = CALLBACK_REQUEST_TIMEOUT_MS;
232
+ await new Promise((resolve, reject) => {
233
+ server.once("error", reject);
234
+ server.listen(0, "127.0.0.1", () => {
235
+ server.off("error", reject);
236
+ resolve();
237
+ });
238
+ });
239
+ timeoutId = setTimeout(() => {
240
+ rejectCode(new Error("Login timed out waiting for browser callback."));
241
+ void closeServer(server);
242
+ }, options.timeoutMs ?? LOGIN_TIMEOUT_MS);
243
+ const address = server.address();
244
+ if (!address?.port) {
245
+ await closeServer(server);
246
+ throw new Error("Failed to bind local CLI auth callback server.");
247
+ }
248
+ return {
249
+ callbackUrl: `http://127.0.0.1:${address.port}/callback`,
250
+ setExpectedState: (state) => {
251
+ expectedState = state;
252
+ },
253
+ waitForCode: () => waitPromise,
254
+ close: async () => {
255
+ if (timeoutId)
256
+ clearTimeout(timeoutId);
257
+ await closeServer(server);
258
+ },
259
+ };
260
+ }
261
+ async function handleCallbackRequest(req, res, expectedState, resolveCode) {
262
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
263
+ if (url.pathname !== "/callback") {
264
+ res.writeHead(404);
265
+ res.end("Not found");
266
+ return;
267
+ }
268
+ if (req.method === "GET") {
269
+ const state = url.searchParams.get("state") ?? "";
270
+ const code = url.searchParams.get("code") ?? url.searchParams.get("handoff_code") ?? "";
271
+ if (!validateCallbackState(expectedState, state, res))
272
+ return;
273
+ if (!validateCallbackCode(code, res))
274
+ return;
275
+ resolveCode({ code, state });
276
+ res.writeHead(200, { "Content-Type": "text/html" });
277
+ res.end("<html><body><h2>Omics-OS CLI login complete.</h2><p>You can close this tab.</p></body></html>");
278
+ return;
279
+ }
280
+ if (req.method === "POST") {
281
+ const body = await readJsonBody(req, res);
282
+ if (!body)
283
+ return;
284
+ if (hasDurableCredentialFields(body)) {
285
+ res.writeHead(400, { "Content-Type": "text/plain" });
286
+ res.end("Durable credentials are not accepted on the local callback.");
287
+ return;
288
+ }
289
+ const state = typeof body.state === "string" ? body.state : "";
290
+ const code = typeof body.code === "string"
291
+ ? body.code
292
+ : typeof body.handoff_code === "string"
293
+ ? body.handoff_code
294
+ : "";
295
+ if (!validateCallbackState(expectedState, state, res))
296
+ return;
297
+ if (!validateCallbackCode(code, res))
298
+ return;
299
+ resolveCode({ code, state });
300
+ res.writeHead(200, { "Content-Type": "application/json" });
301
+ res.end(JSON.stringify({ success: true }));
302
+ return;
303
+ }
304
+ res.writeHead(405, { Allow: "GET, POST" });
305
+ res.end("Method not allowed");
306
+ }
307
+ async function requestJson(apiUrl, path, options) {
308
+ const response = await requestJsonWithStatus(apiUrl, path, options);
309
+ if (!response.ok) {
310
+ const detail = extractErrorCode(response.body) ?? `HTTP ${response.status}`;
311
+ // The broker answers `{detail: {error, message}}`; the code alone drops the only
312
+ // part a caller can act on (e.g. which tenant was not found).
313
+ const message = extractErrorMessage(response.body);
314
+ throw new Error(`Auth request failed: ${detail}${message && message !== detail ? ` — ${message}` : ""}`);
315
+ }
316
+ return response.body;
317
+ }
318
+ async function requestJsonWithStatus(apiUrl, path, options) {
319
+ const { safe, origin } = validateApiOrigin(apiUrl);
320
+ if (!safe) {
321
+ throw new Error(`Refusing to send auth request to untrusted origin: ${origin}.`);
322
+ }
323
+ const controller = typeof options.timeoutMs === "number" ? new AbortController() : undefined;
324
+ const timeoutId = controller
325
+ ? setTimeout(() => controller.abort(), options.timeoutMs)
326
+ : undefined;
327
+ try {
328
+ const resp = await fetch(`${apiUrl}${path}`, {
329
+ redirect: "error",
330
+ method: options.method,
331
+ headers: {
332
+ Accept: "application/json",
333
+ ...(options.body !== undefined ? { "Content-Type": "application/json" } : {}),
334
+ },
335
+ ...(options.body !== undefined ? { body: JSON.stringify(options.body) } : {}),
336
+ ...(controller ? { signal: controller.signal } : {}),
337
+ });
338
+ let body = undefined;
339
+ try {
340
+ body = await resp.json();
341
+ }
342
+ catch {
343
+ body = undefined;
344
+ }
345
+ return { ok: resp.ok, status: resp.status, body };
346
+ }
347
+ finally {
348
+ if (timeoutId)
349
+ clearTimeout(timeoutId);
350
+ }
351
+ }
352
+ async function readJsonBody(req, res) {
353
+ let body = "";
354
+ let bytes = 0;
355
+ for await (const chunk of req) {
356
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
357
+ bytes += buffer.length;
358
+ if (bytes > MAX_CALLBACK_BODY_BYTES) {
359
+ res.writeHead(413, { "Content-Type": "text/plain" });
360
+ res.end("Payload too large");
361
+ return undefined;
362
+ }
363
+ body += buffer.toString("utf-8");
364
+ }
365
+ try {
366
+ const parsed = JSON.parse(body);
367
+ if (!parsed || typeof parsed !== "object")
368
+ throw new Error("not object");
369
+ return parsed;
370
+ }
371
+ catch {
372
+ res.writeHead(400, { "Content-Type": "text/plain" });
373
+ res.end("Invalid JSON");
374
+ return undefined;
375
+ }
376
+ }
377
+ function validateCallbackState(expected, actual, res) {
378
+ if (!safeCompare(expected, actual)) {
379
+ res.writeHead(403, { "Content-Type": "text/plain" });
380
+ res.end("Invalid state parameter");
381
+ return false;
382
+ }
383
+ return true;
384
+ }
385
+ function validateCallbackCode(code, res) {
386
+ if (!code) {
387
+ res.writeHead(400, { "Content-Type": "text/plain" });
388
+ res.end("Missing one-time code");
389
+ return false;
390
+ }
391
+ return true;
392
+ }
393
+ function hasDurableCredentialFields(body) {
394
+ return typeof body.access_token === "string"
395
+ || typeof body.refresh_token === "string"
396
+ || typeof body.id_token === "string"
397
+ || typeof body.cli_token === "string"
398
+ || typeof body.api_key === "string";
399
+ }
400
+ function normalizeApiUrl(apiUrl) {
401
+ if (!apiUrl)
402
+ return CLOUD_API_BASE;
403
+ if (apiUrl.endsWith("/api/v1"))
404
+ return apiUrl.replace(/\/+$/, "");
405
+ const parsed = new URL(apiUrl);
406
+ if (parsed.pathname === "/" || parsed.pathname === "") {
407
+ return endpointToApiUrl(parsed.origin);
408
+ }
409
+ return apiUrl.replace(/\/+$/, "");
410
+ }
411
+ function safeCompare(expected, actual) {
412
+ if (expected.length !== actual.length)
413
+ return false;
414
+ try {
415
+ return timingSafeEqual(Buffer.from(expected), Buffer.from(actual));
416
+ }
417
+ catch {
418
+ return false;
419
+ }
420
+ }
421
+ function closeServer(server) {
422
+ return new Promise((resolve) => {
423
+ if (!server.listening) {
424
+ resolve();
425
+ return;
426
+ }
427
+ server.close(() => resolve());
428
+ });
429
+ }
430
+ function extractErrorCode(body) {
431
+ if (!body || typeof body !== "object")
432
+ return undefined;
433
+ const d = body;
434
+ const raw = d.error ?? d.code ?? d.detail ?? d.message;
435
+ if (typeof raw === "string")
436
+ return raw;
437
+ if (raw && typeof raw === "object")
438
+ return extractErrorCode(raw);
439
+ return undefined;
440
+ }
441
+ /** Human-readable half of an error body, when the server sent one alongside the
442
+ * machine code. Kept separate from `extractErrorCode` so device-flow code
443
+ * matching (`authorization_pending`, `slow_down`, …) stays exact. */
444
+ function extractErrorMessage(body) {
445
+ if (!body || typeof body !== "object")
446
+ return undefined;
447
+ const d = body;
448
+ const nested = d.detail;
449
+ if (nested && typeof nested === "object") {
450
+ const inner = nested.message;
451
+ if (typeof inner === "string" && inner.length > 0)
452
+ return inner;
453
+ }
454
+ return typeof d.message === "string" && d.message.length > 0 ? d.message : undefined;
455
+ }
456
+ function stringOrUndefined(value) {
457
+ return typeof value === "string" && value.length > 0 ? value : undefined;
458
+ }
459
+ function delay(ms) {
460
+ return new Promise((resolve) => setTimeout(resolve, ms));
461
+ }
462
+ export { CLOUD_API_BASE, CLOUD_ENDPOINT };
@@ -0,0 +1,40 @@
1
+ import type { EntryResponse } from './entries.js';
2
+ import type { ExecuteCommand } from './vendor/runV1.generated.js';
3
+ export declare const APPROVAL_GENERATION: "biovault.approval.v1.1";
4
+ export interface PendingExecute {
5
+ entry_id: string;
6
+ tuple: ExecuteCommand;
7
+ }
8
+ export declare const sameTuple: (a: ExecuteCommand, b: ExecuteCommand) => boolean;
9
+ /**
10
+ * Whether `now` (a plan as the server shows it: revision, turn generation, state) proves `t` can never land. Execute names the revision AND the
11
+ * generation of the plan it was clicked on and is refused unless both are still current; both only ever grow, so a LARGER observed value on a
12
+ * plan that is still "planning" is final. Equal or smaller proves nothing.
13
+ */
14
+ export declare const supersededBy: (t: ExecuteCommand, now: {
15
+ revision: number;
16
+ generation: number;
17
+ }) => boolean;
18
+ /** Is the click `later` strictly newer than `earlier` on the same plan (so `earlier` can no longer land)? */
19
+ export declare const newerThan: (later: ExecuteCommand, earlier: ExecuteCommand) => boolean;
20
+ export type Verdict =
21
+ /** The saved approval is this click's: the run it made. */
22
+ {
23
+ kind: 'same';
24
+ jobId: string;
25
+ }
26
+ /** The entry was executed under a different approval: not what was reviewed here. `jobId` is that run. */
27
+ | {
28
+ kind: 'different';
29
+ jobId: string;
30
+ } | {
31
+ kind: 'not-started';
32
+ }
33
+ /** PROVEN final: the entry was cancelled before any approval, with no job. The pending request can never land against a terminal entry. */
34
+ | {
35
+ kind: 'cancelled';
36
+ } | {
37
+ kind: 'unknown';
38
+ };
39
+ /** What an entry as the server holds it says about a click. Anything it cannot prove is `unknown`. */
40
+ export declare function judge(res: EntryResponse, clicked: PendingExecute): Verdict;
@@ -0,0 +1,38 @@
1
+ export const APPROVAL_GENERATION = 'biovault.approval.v1.1';
2
+ const KEYS = ['config_sha256', 'prompt_sha256', 'execution_manifest_sha256', 'instruction_bundle_sha256', 'expected_revision', 'expected_turn_generation', 'prompt_version'];
3
+ export const sameTuple = (a, b) => KEYS.every((k) => a[k] === b[k]);
4
+ /**
5
+ * Whether `now` (a plan as the server shows it: revision, turn generation, state) proves `t` can never land. Execute names the revision AND the
6
+ * generation of the plan it was clicked on and is refused unless both are still current; both only ever grow, so a LARGER observed value on a
7
+ * plan that is still "planning" is final. Equal or smaller proves nothing.
8
+ */
9
+ export const supersededBy = (t, now) => now.revision > t.expected_revision || (now.revision === t.expected_revision && now.generation > t.expected_turn_generation);
10
+ /** Is the click `later` strictly newer than `earlier` on the same plan (so `earlier` can no longer land)? */
11
+ export const newerThan = (later, earlier) => supersededBy(earlier, { revision: later.expected_revision, generation: later.expected_turn_generation });
12
+ /** What an entry as the server holds it says about a click. Anything it cannot prove is `unknown`. */
13
+ export function judge(res, clicked) {
14
+ const entry = res.entry;
15
+ if (!entry)
16
+ return { kind: 'unknown' };
17
+ const approval = entry.work_plan?.approval;
18
+ if (approval && typeof approval === 'object') {
19
+ const a = approval;
20
+ const jobId = typeof a.job_id === 'string' && a.job_id !== '' ? a.job_id : null;
21
+ const whole = a.approval_generation === APPROVAL_GENERATION &&
22
+ KEYS.every((k) => a[k] === clicked.tuple[k]) &&
23
+ (a.entry_id === undefined || a.entry_id === clicked.entry_id) &&
24
+ entry.entry_id === clicked.entry_id;
25
+ if (!jobId)
26
+ return { kind: 'unknown' };
27
+ if (whole)
28
+ return (entry.job_ids ?? []).includes(jobId) ? { kind: 'same', jobId } : { kind: 'unknown' };
29
+ return { kind: 'different', jobId };
30
+ }
31
+ if (entry.status === 'planning')
32
+ return { kind: 'not-started' };
33
+ // Only a durable cancellation with no approval and no job is proof that no run exists (and none can start: Execute needs "planning").
34
+ // Any other state without an approval, and any bare "gone", stays unknown.
35
+ if (entry.status === 'cancelled' && (entry.job_ids ?? []).length === 0 && entry.entry_id === clicked.entry_id)
36
+ return { kind: 'cancelled' };
37
+ return { kind: 'unknown' };
38
+ }
@@ -0,0 +1,10 @@
1
+ export declare const RP1_SCOPE = "Instructions recorded; not checked by the engine; tools restricted by Omics-OS";
2
+ export declare const NATIVE_SCOPE = "local_release_assets_and_initial_request";
3
+ export declare const RP1_MANIFEST_VERSION = "biovault.instructions.rp1.v1";
4
+ export declare const NATIVE_MANIFEST_VERSION = "biovault.instructions.v1";
5
+ export declare const RP1_BUNDLE_VERSION = "biovault.initial.instructions.rp1.v1";
6
+ export declare const NATIVE_BUNDLE_VERSION = "biovault.initial.instructions.v1";
7
+ /** The manifest version a config's execution contract names, or null. */
8
+ export declare function manifestVersionOf(config: unknown): string | null;
9
+ /** A restricted-profile run: its approved config carries the restricted profile. Old native runs say nothing new. */
10
+ export declare const isRp1: (config: unknown) => boolean;
@@ -0,0 +1,14 @@
1
+ export const RP1_SCOPE = 'Instructions recorded; not checked by the engine; tools restricted by Omics-OS';
2
+ export const NATIVE_SCOPE = 'local_release_assets_and_initial_request';
3
+ export const RP1_MANIFEST_VERSION = 'biovault.instructions.rp1.v1';
4
+ export const NATIVE_MANIFEST_VERSION = 'biovault.instructions.v1';
5
+ export const RP1_BUNDLE_VERSION = 'biovault.initial.instructions.rp1.v1';
6
+ export const NATIVE_BUNDLE_VERSION = 'biovault.initial.instructions.v1';
7
+ /** The manifest version a config's execution contract names, or null. */
8
+ export function manifestVersionOf(config) {
9
+ const c = config && typeof config === 'object' ? config.execution_contract : undefined;
10
+ const v = c?.manifest?.manifest_version;
11
+ return typeof v === 'string' ? v : null;
12
+ }
13
+ /** A restricted-profile run: its approved config carries the restricted profile. Old native runs say nothing new. */
14
+ export const isRp1 = (config) => manifestVersionOf(config) === RP1_MANIFEST_VERSION;
@@ -0,0 +1,76 @@
1
+ import { type AppConfig } from '../types.js';
2
+ import type { DraftPreview } from './vendor/runV1.generated.js';
3
+ import type { RunListV1, SamplesPage, PackageResponseV1, ProblemsPageV1, DecisionsPageV1 } from './vendor/packageDeliveryV1.generated.js';
4
+ import { type Features, type EntryListResponse, type EntryResponse, type JobResponse, type LegacyJobListResponse, type JobPrompt } from './entries.js';
5
+ import { type RunCompatibility } from './compat.js';
6
+ export interface ReadOptions {
7
+ signal?: AbortSignal;
8
+ }
9
+ export interface PageOptions extends ReadOptions {
10
+ limit?: number;
11
+ cursor?: string;
12
+ }
13
+ export interface RunListOptions extends PageOptions {
14
+ view: 'v1' | 'legacy';
15
+ status?: string;
16
+ outcome?: string;
17
+ }
18
+ export interface ProblemOptions extends PageOptions {
19
+ status?: 'resolved' | 'unresolved';
20
+ severity?: 'info' | 'warning' | 'blocking';
21
+ }
22
+ export declare function features(config: AppConfig, options?: ReadOptions): Promise<Features>;
23
+ export declare function getDraft(config: AppConfig, entryId: string, options?: ReadOptions): Promise<DraftPreview>;
24
+ export declare function listEntries(config: AppConfig, options?: ReadOptions): Promise<EntryListResponse>;
25
+ export declare function getEntry(config: AppConfig, entryId: string, options?: ReadOptions): Promise<EntryResponse>;
26
+ export declare function listRuns(config: AppConfig, options: RunListOptions & {
27
+ view: 'v1';
28
+ }): Promise<RunListV1>;
29
+ export declare function listRuns(config: AppConfig, options: RunListOptions & {
30
+ view: 'legacy';
31
+ }): Promise<LegacyJobListResponse>;
32
+ export declare function getRun(config: AppConfig, jobId: string, options?: ReadOptions): Promise<JobResponse>;
33
+ /** Display-only reads for `vault runs` / `vault run show`: a run made by a newer
34
+ * server is returned with `cli_compatibility` instead of refused. Callers that
35
+ * check, execute or download use listRuns/getRun, which stay strict. */
36
+ export type DisplayRun<T> = T & {
37
+ cli_compatibility?: RunCompatibility;
38
+ };
39
+ export type DisplayRunList = Omit<RunListV1, 'jobs'> & {
40
+ jobs: DisplayRun<RunListV1['jobs'][number]>[];
41
+ };
42
+ export type DisplayJobResponse = Omit<JobResponse, 'job'> & {
43
+ job: DisplayRun<JobResponse['job']>;
44
+ };
45
+ export declare function listRunsForDisplay(config: AppConfig, options?: Omit<RunListOptions, 'view'>): Promise<DisplayRunList>;
46
+ export declare function getRunForDisplay(config: AppConfig, jobId: string, options?: ReadOptions): Promise<DisplayJobResponse>;
47
+ export declare function getPrompt(config: AppConfig, jobId: string, options?: ReadOptions): Promise<JobPrompt>;
48
+ export declare function getSamples(config: AppConfig, jobId: string, options?: PageOptions): Promise<SamplesPage>;
49
+ export declare function getPackage(config: AppConfig, jobId: string, options?: ReadOptions): Promise<PackageResponseV1>;
50
+ export declare function getProblems(config: AppConfig, jobId: string, options?: ProblemOptions): Promise<ProblemsPageV1>;
51
+ export declare function getDecisions(config: AppConfig, jobId: string, options?: PageOptions): Promise<DecisionsPageV1>;
52
+ import type { DraftCommand } from './vendor/runV1.generated.js';
53
+ export declare function createDraft(config: AppConfig, command: DraftCommand): Promise<DraftPreview>;
54
+ export declare function saveDraft(config: AppConfig, entryId: string, command: DraftCommand): Promise<DraftPreview>;
55
+ /** Qualify the local RIS before any HTTP. stat follows a symlink only when its
56
+ * resolved target is a regular file; read bytes are rechecked for file races.
57
+ */
58
+ export declare function uploadLiterature(config: AppConfig, entryId: string, expectedRevision: number, path: string): Promise<DraftPreview>;
59
+ export declare function removeLiterature(config: AppConfig, entryId: string, fileId: string, expectedRevision: number): Promise<DraftPreview>;
60
+ export declare function discardDraft(config: AppConfig, entryId: string): Promise<EntryResponse>;
61
+ import type { PackageDownloadV1 } from './vendor/packageDeliveryV1.generated.js';
62
+ export declare function getFileLink(config: AppConfig, jobId: string, path: string, options?: ReadOptions): Promise<PackageDownloadV1>;
63
+ export declare function getArchiveLink(config: AppConfig, jobId: string, options?: ReadOptions): Promise<PackageDownloadV1>;
64
+ /** Pure comparison against copied ORIGINAL R15 bindings. For R19 the path is
65
+ * package.zip; call again for every renewal. The reason contains no URLs/data.
66
+ */
67
+ export declare function packageLinkMismatch(link: PackageDownloadV1, expected: {
68
+ job_id: string;
69
+ path: string;
70
+ sha256: string;
71
+ size_bytes: number;
72
+ }): string | null;
73
+ import type { ExecuteCommand } from './vendor/runV1.generated.js';
74
+ import { type CancelAck } from './entries.js';
75
+ export declare function executeRun(config: AppConfig, entryId: string, tuple: ExecuteCommand, options?: ReadOptions): Promise<EntryResponse>;
76
+ export declare function cancelRun(config: AppConfig, jobId: string, options?: ReadOptions): Promise<CancelAck>;