omics-os 0.0.1 → 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.
- 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 +462 -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,119 @@
|
|
|
1
|
+
/** Projects & datasets REST API. */
|
|
2
|
+
import { apiFetch } from "./apiClient.js";
|
|
3
|
+
import { freshAuthHeaders } from "./config.js";
|
|
4
|
+
import { ApiError, AuthError, NetworkError, UnreadableResponseError } from "./types.js";
|
|
5
|
+
/** List all projects for the current user. Rejects on any request failure; an empty list means no projects. */
|
|
6
|
+
export async function listProjects(config) {
|
|
7
|
+
const data = await apiFetch(config, "/projects");
|
|
8
|
+
return data.projects ?? [];
|
|
9
|
+
}
|
|
10
|
+
/** Upload a file to a dataset. */
|
|
11
|
+
export async function pushFile(config, datasetId, filePath, fileContent) {
|
|
12
|
+
const url = `${config.apiUrl}/datasets/${datasetId}/files`;
|
|
13
|
+
const formData = new FormData();
|
|
14
|
+
formData.append("file", new Blob([fileContent]), filePath);
|
|
15
|
+
const auth = await freshAuthHeaders(config);
|
|
16
|
+
const resp = await fetch(url, {
|
|
17
|
+
redirect: "error",
|
|
18
|
+
method: "POST",
|
|
19
|
+
headers: auth,
|
|
20
|
+
body: formData,
|
|
21
|
+
});
|
|
22
|
+
if (!resp.ok) {
|
|
23
|
+
throw new Error(`Upload failed: ${resp.status} ${resp.statusText}`);
|
|
24
|
+
}
|
|
25
|
+
const data = (await resp.json());
|
|
26
|
+
return data.message ?? data.file_id ?? "Uploaded successfully";
|
|
27
|
+
}
|
|
28
|
+
/** List files in a dataset (for pull). Rejects on any request failure. */
|
|
29
|
+
export async function listDatasetFiles(config, datasetId) {
|
|
30
|
+
// Call text kept byte-identical: apiClient.test.ts pins the text of every apiFetch call.
|
|
31
|
+
const data = await apiFetch(config, `/datasets/${datasetId}/files`);
|
|
32
|
+
return data.files ?? [];
|
|
33
|
+
}
|
|
34
|
+
/** Stream one file of an org project's shared data (GET /org/projects/{id}/data/{filename}). */
|
|
35
|
+
export async function downloadProjectDataFile(config, projectId, filename) {
|
|
36
|
+
const path = `/org/projects/${encodeURIComponent(projectId)}/data/${filename.split("/").map(encodeURIComponent).join("/")}`;
|
|
37
|
+
const auth = await freshAuthHeaders(config);
|
|
38
|
+
const resp = await fetch(`${config.apiUrl}${path}`, { redirect: "error", headers: { ...auth } });
|
|
39
|
+
if (resp.status === 401)
|
|
40
|
+
throw new AuthError(path);
|
|
41
|
+
if (!resp.ok)
|
|
42
|
+
throw new ApiError(path, resp.status, resp.statusText);
|
|
43
|
+
if (!resp.body)
|
|
44
|
+
throw new NetworkError(path, new Error("No response body"));
|
|
45
|
+
return resp.body;
|
|
46
|
+
}
|
|
47
|
+
/** Project files above this size download through the link route, so a long transfer never holds an API task. */
|
|
48
|
+
export const PROJECT_DATA_LINK_BYTES = 500 * 1024 * 1024;
|
|
49
|
+
/**
|
|
50
|
+
* Stream one large project file straight from storage: the link route returns a presigned GET
|
|
51
|
+
* (`{url, expires_at, size_bytes}`), fetched with no Omics credentials and no redirects. A link
|
|
52
|
+
* that is not HTTPS is refused before anything is requested from it.
|
|
53
|
+
*/
|
|
54
|
+
export async function downloadProjectDataLink(config, projectId, filename) {
|
|
55
|
+
const path = `/org/projects/${encodeURIComponent(projectId)}/data-link/${filename.split("/").map(encodeURIComponent).join("/")}`;
|
|
56
|
+
const link = await apiFetch(config, path);
|
|
57
|
+
let url;
|
|
58
|
+
try {
|
|
59
|
+
if (typeof link.url === "string")
|
|
60
|
+
url = new URL(link.url);
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
url = undefined;
|
|
64
|
+
}
|
|
65
|
+
if (url?.protocol !== "https:") {
|
|
66
|
+
throw Object.assign(new UnreadableResponseError(path, 200), { publicMessage: "The server returned no usable HTTPS download link; nothing was downloaded." });
|
|
67
|
+
}
|
|
68
|
+
const resp = await fetch(url, { redirect: "error", credentials: "omit" });
|
|
69
|
+
if (!resp.ok)
|
|
70
|
+
throw new ApiError(path, resp.status, resp.statusText, "storage refused the download link");
|
|
71
|
+
if (!resp.body)
|
|
72
|
+
throw new NetworkError(path, new Error("No response body"));
|
|
73
|
+
return resp.body;
|
|
74
|
+
}
|
|
75
|
+
/** The server answers every refusal of a project with the same words, on purpose; these name both causes. */
|
|
76
|
+
function projectRefused(projectId) {
|
|
77
|
+
return `This login cannot open project ${projectId}. Either it is an organisation project you are not assigned to (ask an organisation admin), or it belongs to an organisation this login does not reach (log in to it: omics-os login --tenant <organisation>).`;
|
|
78
|
+
}
|
|
79
|
+
/** Read one project (owner, organisation admin or assigned member). A refusal or a missing project is said in words. */
|
|
80
|
+
export async function getProject(config, projectId) {
|
|
81
|
+
const path = `/projects/${encodeURIComponent(projectId)}`;
|
|
82
|
+
let reply;
|
|
83
|
+
try {
|
|
84
|
+
reply = await apiFetch(config, path);
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
if (error instanceof ApiError && error.status === 403)
|
|
88
|
+
throw new Error(projectRefused(projectId));
|
|
89
|
+
if (error instanceof ApiError && error.status === 404)
|
|
90
|
+
throw new Error(`Project ${projectId} was not found.`);
|
|
91
|
+
throw error;
|
|
92
|
+
}
|
|
93
|
+
if (typeof reply?.project?.project_id !== "string")
|
|
94
|
+
throw new UnreadableResponseError(path, 200);
|
|
95
|
+
return reply.project;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Create a project, as the web app does: the login's host decides where it lives. On an organisation's host
|
|
99
|
+
* (login --tenant) it belongs to that organisation and you own it; on the platform host it is personal.
|
|
100
|
+
*/
|
|
101
|
+
export async function createProject(config, project) {
|
|
102
|
+
const reply = await apiFetch(config, "/projects", { method: "POST", body: project });
|
|
103
|
+
if (typeof reply?.project?.project_id !== "string")
|
|
104
|
+
throw new UnreadableResponseError("/projects", 201);
|
|
105
|
+
return reply.project;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* An upload the project itself refused, which holds for every file of the run: 404 `project_not_found` (no such
|
|
109
|
+
* project in this login's organisation, or a personal one) or a 403 without a code (the server's one access refusal;
|
|
110
|
+
* it checks again on sign and complete). The words to show, or undefined.
|
|
111
|
+
*/
|
|
112
|
+
export function uploadProjectRefusal(error, projectId) {
|
|
113
|
+
if (!(error instanceof ApiError))
|
|
114
|
+
return undefined;
|
|
115
|
+
if (error.status === 404 && error.code === "project_not_found") {
|
|
116
|
+
return `Project ${projectId} was not found in this login's organisation, or it is a personal project. Uploads go to organisation projects: check the ID, or log in to the project's organisation (omics-os login --tenant <organisation>).`;
|
|
117
|
+
}
|
|
118
|
+
return error.status === 403 && !error.code ? projectRefused(projectId) : undefined;
|
|
119
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Resources catalog API — fetches @mention-able resources. */
|
|
2
|
+
import type { AppConfig, Resource } from "./types.js";
|
|
3
|
+
/** Fetch resources catalog. Cached for session lifetime. */
|
|
4
|
+
export declare function fetchResources(config: AppConfig): Promise<Resource[]>;
|
|
5
|
+
/** Filter resources by prefix (case-insensitive). */
|
|
6
|
+
export declare function filterResources(resources: Resource[], prefix: string): Resource[];
|
|
7
|
+
/** Reset cached resources (useful for testing). */
|
|
8
|
+
export declare function resetResourcesCache(): void;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Resources catalog API — fetches @mention-able resources. */
|
|
2
|
+
import { apiFetch } from "./apiClient.js";
|
|
3
|
+
let cachedResources = null;
|
|
4
|
+
/** Fetch resources catalog. Cached for session lifetime. */
|
|
5
|
+
export async function fetchResources(config) {
|
|
6
|
+
if (cachedResources)
|
|
7
|
+
return cachedResources;
|
|
8
|
+
try {
|
|
9
|
+
const data = await apiFetch(config, "/resources");
|
|
10
|
+
cachedResources = data.resources ?? [];
|
|
11
|
+
return cachedResources;
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return [];
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/** Filter resources by prefix (case-insensitive). */
|
|
18
|
+
export function filterResources(resources, prefix) {
|
|
19
|
+
const lower = prefix.toLowerCase();
|
|
20
|
+
return resources.filter((r) => r.id.toLowerCase().includes(lower) ||
|
|
21
|
+
r.label.toLowerCase().includes(lower));
|
|
22
|
+
}
|
|
23
|
+
/** Reset cached resources (useful for testing). */
|
|
24
|
+
export function resetResourcesCache() {
|
|
25
|
+
cachedResources = null;
|
|
26
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/** Session CRUD — create, list, resolve, archive, delete, share. */
|
|
2
|
+
import type { AppConfig, Project, SeedWarning, Session } from "./types.js";
|
|
3
|
+
export declare function isUuidSessionId(value: string): boolean;
|
|
4
|
+
/** How long opening a session (create POST, or the `latest` lookup) may wait for the server. */
|
|
5
|
+
export declare const SESSION_OPEN_TIMEOUT_MS = 60000;
|
|
6
|
+
export declare class SessionOpenTimeoutError extends Error {
|
|
7
|
+
constructor();
|
|
8
|
+
}
|
|
9
|
+
/** One line for a new project session whose files were not all copied into it. */
|
|
10
|
+
export declare function seedWarningMessage(warnings: SeedWarning[]): string;
|
|
11
|
+
/**
|
|
12
|
+
* Create a new session on the backend. Returns session_id. Project files the server did not copy
|
|
13
|
+
* into the session (seed_warnings) go to `onSeedWarnings`, called only when there are some.
|
|
14
|
+
* The project is `options.project` (already read by the caller) or `config.projectId` (read here).
|
|
15
|
+
*/
|
|
16
|
+
export declare function createSession(config: AppConfig, onSeedWarnings?: (warnings: SeedWarning[]) => void, options?: {
|
|
17
|
+
name?: string;
|
|
18
|
+
project?: Project;
|
|
19
|
+
}): Promise<string>;
|
|
20
|
+
/** List sessions for the current user. */
|
|
21
|
+
export declare function listSessions(config: AppConfig): Promise<Session[]>;
|
|
22
|
+
/** Resolve session: use provided ID (or "latest"), or create a new one (see createSession for `onSeedWarnings`). */
|
|
23
|
+
export declare function resolveSessionId(config: AppConfig, onSeedWarnings?: (warnings: SeedWarning[]) => void): Promise<string>;
|
|
24
|
+
/** Archive (soft-delete) a session. */
|
|
25
|
+
export declare function archiveSession(config: AppConfig, sessionId: string): Promise<void>;
|
|
26
|
+
/** Permanently delete a session. */
|
|
27
|
+
export declare function deleteSession(config: AppConfig, sessionId: string): Promise<void>;
|
|
28
|
+
/** Share a session (returns share URL or token). */
|
|
29
|
+
export declare function shareSession(config: AppConfig, sessionId: string): Promise<{
|
|
30
|
+
share_url: string;
|
|
31
|
+
}>;
|
|
32
|
+
/** Get a single session by ID. */
|
|
33
|
+
export declare function getSession(config: AppConfig, sessionId: string): Promise<Session>;
|
|
34
|
+
/**
|
|
35
|
+
* One message in the GET /sessions/{id}/messages reply. Not the `Message` type: `content` is a list of
|
|
36
|
+
* blocks, and the durable-store fields below appear only when the server reads DynamoDB first.
|
|
37
|
+
*/
|
|
38
|
+
export interface SessionMessageItem {
|
|
39
|
+
role: string;
|
|
40
|
+
content: unknown;
|
|
41
|
+
content_blocks?: unknown[];
|
|
42
|
+
id?: string;
|
|
43
|
+
message_id?: string;
|
|
44
|
+
message_index?: number;
|
|
45
|
+
created_at?: string;
|
|
46
|
+
session_id?: string;
|
|
47
|
+
[key: string]: unknown;
|
|
48
|
+
}
|
|
49
|
+
/** Reply of GET /sessions/{id}/messages (api/routes/sessions.py get_session_messages). */
|
|
50
|
+
export interface SessionMessagesResponse {
|
|
51
|
+
messages: SessionMessageItem[];
|
|
52
|
+
count: number;
|
|
53
|
+
/** "memory", "dynamodb" or "none". */
|
|
54
|
+
source: string;
|
|
55
|
+
}
|
|
56
|
+
/** Fetch a session's conversation history. */
|
|
57
|
+
export declare function getSessionMessages(config: AppConfig, sessionId: string): Promise<SessionMessagesResponse>;
|
|
58
|
+
/** Cancel an in-progress chat stream. */
|
|
59
|
+
export interface CancelSessionResult {
|
|
60
|
+
/** True only when the server accepted the cancel; a 200 reply can still say false. */
|
|
61
|
+
success?: unknown;
|
|
62
|
+
message?: unknown;
|
|
63
|
+
status?: unknown;
|
|
64
|
+
[key: string]: unknown;
|
|
65
|
+
}
|
|
66
|
+
/** Ask the server to cancel the running chat. Returns the server's reply unchanged. */
|
|
67
|
+
export declare function cancelSession(config: AppConfig, sessionId: string): Promise<CancelSessionResult>;
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/** Session CRUD — create, list, resolve, archive, delete, share. */
|
|
2
|
+
import { getProject } from "./projects.js";
|
|
3
|
+
import { freshAuthHeaders } from "./config.js";
|
|
4
|
+
import { apiFetch } from "./apiClient.js";
|
|
5
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
6
|
+
export function isUuidSessionId(value) {
|
|
7
|
+
return UUID_RE.test(value);
|
|
8
|
+
}
|
|
9
|
+
/** How long opening a session (create POST, or the `latest` lookup) may wait for the server. */
|
|
10
|
+
export const SESSION_OPEN_TIMEOUT_MS = 60_000;
|
|
11
|
+
export class SessionOpenTimeoutError extends Error {
|
|
12
|
+
constructor() {
|
|
13
|
+
super(`Omics-OS Cloud did not answer within ${SESSION_OPEN_TIMEOUT_MS / 1000} s`);
|
|
14
|
+
this.name = "SessionOpenTimeoutError";
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
// AbortSignal.timeout runs on Node's own clock; a plain timer keeps the ceiling testable with fake timers.
|
|
18
|
+
async function withOpenCeiling(run) {
|
|
19
|
+
const controller = new AbortController();
|
|
20
|
+
const timer = setTimeout(() => controller.abort(), SESSION_OPEN_TIMEOUT_MS);
|
|
21
|
+
try {
|
|
22
|
+
return await run(controller.signal);
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
if (controller.signal.aborted)
|
|
26
|
+
throw new SessionOpenTimeoutError();
|
|
27
|
+
throw error;
|
|
28
|
+
}
|
|
29
|
+
finally {
|
|
30
|
+
clearTimeout(timer);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** One line for a new project session whose files were not all copied into it. */
|
|
34
|
+
export function seedWarningMessage(warnings) {
|
|
35
|
+
// listing_failed names no file (empty path): the listing broke, possibly after some files were copied.
|
|
36
|
+
const count = warnings.filter((w) => w.reason !== "listing_failed").length;
|
|
37
|
+
const files = count === 0 ? ""
|
|
38
|
+
: count === 1 ? "1 project file was not copied into this session; the agent cannot read it here"
|
|
39
|
+
: `${count.toLocaleString("en-US")} project files were not copied into this session; the agent cannot read them here`;
|
|
40
|
+
if (count === warnings.length)
|
|
41
|
+
return files;
|
|
42
|
+
const listing = "The project's file list could not be read, so this session may lack some or all of the project's files; start a new session to try again";
|
|
43
|
+
return files ? `${files}. ${listing}` : listing;
|
|
44
|
+
}
|
|
45
|
+
/** The create response's seed_warnings, well-formed entries only; missing or null means none. */
|
|
46
|
+
function seedWarnings(value) {
|
|
47
|
+
if (!Array.isArray(value))
|
|
48
|
+
return [];
|
|
49
|
+
return value.flatMap((entry) => {
|
|
50
|
+
if (!entry || typeof entry !== "object")
|
|
51
|
+
return [];
|
|
52
|
+
const { relative_path, size_bytes, reason } = entry;
|
|
53
|
+
if (typeof relative_path !== "string" || typeof reason !== "string")
|
|
54
|
+
return [];
|
|
55
|
+
return [{ relative_path, size_bytes: typeof size_bytes === "number" ? size_bytes : null, reason }];
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Create a new session on the backend. Returns session_id. Project files the server did not copy
|
|
60
|
+
* into the session (seed_warnings) go to `onSeedWarnings`, called only when there are some.
|
|
61
|
+
* The project is `options.project` (already read by the caller) or `config.projectId` (read here).
|
|
62
|
+
*/
|
|
63
|
+
export async function createSession(config, onSeedWarnings, options = {}) {
|
|
64
|
+
const url = `${config.apiUrl}/sessions`;
|
|
65
|
+
const body = { name: options.name ?? "CLI Session", client_source: "cli", ...(await sessionProject(config, options.project)) };
|
|
66
|
+
const auth = await freshAuthHeaders(config);
|
|
67
|
+
return withOpenCeiling((signal) => postSession(config, url, auth, signal, body, onSeedWarnings));
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Open an organisation project's session as the web app does, with org_project_id: that is what copies the
|
|
71
|
+
* project's files in, and the server refuses project_id to anyone but the project's creator. The local bridge
|
|
72
|
+
* has no projects to read and keeps project_id.
|
|
73
|
+
*/
|
|
74
|
+
async function sessionProject(config, project) {
|
|
75
|
+
if (project)
|
|
76
|
+
return project.org_id ? { org_project_id: project.project_id } : { project_id: project.project_id };
|
|
77
|
+
if (!config.projectId)
|
|
78
|
+
return {};
|
|
79
|
+
if (!config.isCloud)
|
|
80
|
+
return { project_id: config.projectId };
|
|
81
|
+
return sessionProject(config, await getProject(config, config.projectId));
|
|
82
|
+
}
|
|
83
|
+
async function postSession(config, url, auth, signal, body, onSeedWarnings) {
|
|
84
|
+
const resp = await fetch(url, {
|
|
85
|
+
signal,
|
|
86
|
+
redirect: "error",
|
|
87
|
+
method: "POST",
|
|
88
|
+
headers: {
|
|
89
|
+
"Content-Type": "application/json",
|
|
90
|
+
...auth,
|
|
91
|
+
},
|
|
92
|
+
body: JSON.stringify(body),
|
|
93
|
+
});
|
|
94
|
+
if (!resp.ok) {
|
|
95
|
+
let detail = "";
|
|
96
|
+
try {
|
|
97
|
+
const errBody = (await resp.json());
|
|
98
|
+
detail = String(errBody.detail ?? errBody.message ?? errBody.error ?? "").slice(0, 200);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
// response not JSON
|
|
102
|
+
}
|
|
103
|
+
const msg = `Failed to create session: ${resp.status} ${resp.statusText}`;
|
|
104
|
+
throw new Error(detail ? `${msg} — ${detail}` : msg);
|
|
105
|
+
}
|
|
106
|
+
const data = (await resp.json());
|
|
107
|
+
const id = data.session?.session_id ?? data.session_id ?? data.id;
|
|
108
|
+
if (!id) {
|
|
109
|
+
throw new Error("Backend returned no session_id");
|
|
110
|
+
}
|
|
111
|
+
if (config.isCloud && !isUuidSessionId(id)) {
|
|
112
|
+
throw new Error(`Backend returned invalid session ID: ${id.slice(0, 40)}`);
|
|
113
|
+
}
|
|
114
|
+
const warnings = seedWarnings(data.seed_warnings);
|
|
115
|
+
if (warnings.length)
|
|
116
|
+
onSeedWarnings?.(warnings);
|
|
117
|
+
return id;
|
|
118
|
+
}
|
|
119
|
+
/** List sessions for the current user. */
|
|
120
|
+
export async function listSessions(config) {
|
|
121
|
+
const data = await apiFetch(config, "/sessions");
|
|
122
|
+
return Array.isArray(data) ? data : (data.sessions ?? []);
|
|
123
|
+
}
|
|
124
|
+
/** Resolve session: use provided ID (or "latest"), or create a new one (see createSession for `onSeedWarnings`). */
|
|
125
|
+
export async function resolveSessionId(config, onSeedWarnings) {
|
|
126
|
+
if (config.sessionId) {
|
|
127
|
+
if (config.sessionId.toLowerCase() === "latest") {
|
|
128
|
+
// shortcut: the ceiling abandons the GET rather than cancelling it (listSessions takes no signal; its request text is pinned by apiClient.test.ts).
|
|
129
|
+
const sessions = await withOpenCeiling((signal) => Promise.race([
|
|
130
|
+
listSessions(config),
|
|
131
|
+
new Promise((_, reject) => signal.addEventListener("abort", () => reject(signal.reason))),
|
|
132
|
+
]));
|
|
133
|
+
if (sessions.length === 0) {
|
|
134
|
+
throw new Error("No existing sessions found. Start a new one first.");
|
|
135
|
+
}
|
|
136
|
+
const sorted = sessions.sort((a, b) => new Date(b.last_activity ?? b.created_at).getTime() -
|
|
137
|
+
new Date(a.last_activity ?? a.created_at).getTime());
|
|
138
|
+
return sorted[0].session_id;
|
|
139
|
+
}
|
|
140
|
+
if (config.isCloud && !isUuidSessionId(config.sessionId)) {
|
|
141
|
+
throw new Error(`Invalid session ID format: "${config.sessionId}". Expected a UUID.`);
|
|
142
|
+
}
|
|
143
|
+
return config.sessionId;
|
|
144
|
+
}
|
|
145
|
+
try {
|
|
146
|
+
return await createSession(config, onSeedWarnings);
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
if (config.isCloud) {
|
|
150
|
+
throw error;
|
|
151
|
+
}
|
|
152
|
+
return `local_${crypto.randomUUID().slice(0, 12)}`;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/** Archive (soft-delete) a session. */
|
|
156
|
+
export async function archiveSession(config, sessionId) {
|
|
157
|
+
await apiFetch(config, `/sessions/${sessionId}/archive`, {
|
|
158
|
+
method: "POST",
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
/** Permanently delete a session. */
|
|
162
|
+
export async function deleteSession(config, sessionId) {
|
|
163
|
+
await apiFetch(config, `/sessions/${sessionId}`, {
|
|
164
|
+
method: "DELETE",
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
/** Share a session (returns share URL or token). */
|
|
168
|
+
export async function shareSession(config, sessionId) {
|
|
169
|
+
return apiFetch(config, `/sessions/${sessionId}/share`, {
|
|
170
|
+
method: "POST",
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
/** Get a single session by ID. */
|
|
174
|
+
export async function getSession(config, sessionId) {
|
|
175
|
+
return apiFetch(config, `/sessions/${sessionId}`);
|
|
176
|
+
}
|
|
177
|
+
/** Fetch a session's conversation history. */
|
|
178
|
+
export async function getSessionMessages(config, sessionId) {
|
|
179
|
+
return apiFetch(config, `/sessions/${sessionId}/messages`);
|
|
180
|
+
}
|
|
181
|
+
/** Ask the server to cancel the running chat. Returns the server's reply unchanged. */
|
|
182
|
+
export async function cancelSession(config, sessionId) {
|
|
183
|
+
const reply = await apiFetch(config, `/sessions/${sessionId}/chat/cancel`, {
|
|
184
|
+
method: "POST",
|
|
185
|
+
});
|
|
186
|
+
return reply;
|
|
187
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** Prompt templates — fetched on new session, displayed as suggestions. */
|
|
2
|
+
import type { AppConfig, PromptTemplate } from "./types.js";
|
|
3
|
+
/** Fetch prompt templates from backend. Returns empty array on error. */
|
|
4
|
+
export declare function fetchTemplates(config: AppConfig): Promise<PromptTemplate[]>;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Prompt templates — fetched on new session, displayed as suggestions. */
|
|
2
|
+
import { apiFetch } from "./apiClient.js";
|
|
3
|
+
/** Fetch prompt templates from backend. Returns empty array on error. */
|
|
4
|
+
export async function fetchTemplates(config) {
|
|
5
|
+
try {
|
|
6
|
+
const data = await apiFetch(config, "/config/templates");
|
|
7
|
+
return data.templates ?? [];
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
return [];
|
|
11
|
+
}
|
|
12
|
+
}
|