@dbx-tools/dbx-model-catalog 0.1.9 → 0.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/README.md +296 -55
- package/dist/_generated/channels.d.ts +4 -3
- package/dist/_generated/json-schema.d.ts +6527 -175
- package/dist/_generated/schemas.d.ts +154 -0
- package/dist/_generated/workspace-rules.d.ts +133 -0
- package/dist/browser.d.ts +34 -15
- package/dist/browser.js +1152 -9042
- package/dist/catalog-index.d.ts +15 -2
- package/dist/chunk-engbh7tj.js +39 -0
- package/dist/chunk-gzjer0mc.js +1797 -0
- package/dist/chunk-pp7fw379.js +51 -0
- package/dist/chunk-pwssxaq0.js +39 -0
- package/dist/cli.js +41 -9619
- package/dist/effective.d.ts +31 -0
- package/dist/index.d.ts +33 -16
- package/dist/index.js +60 -9630
- package/dist/local-client.d.ts +16 -3
- package/dist/pynect.d.ts +6 -3
- package/dist/search.d.ts +7 -1
- package/dist/serving-endpoints.d.ts +15 -0
- package/dist/sources.d.ts +30 -0
- package/dist/types.d.ts +31 -3
- package/dist/validation.d.ts +15 -1
- package/dist/workspace-cache.d.ts +68 -0
- package/dist/workspace-client.d.ts +49 -0
- package/dist/workspace-connection.d.ts +67 -0
- package/dist/workspace-file-cache.d.ts +11 -0
- package/dist/workspace-identity.d.ts +27 -0
- package/dist/workspace-overlay.d.ts +71 -0
- package/package.json +8 -12
- package/src/_generated/channels.ts +41 -0
- package/src/_generated/index.ts +6 -0
- package/src/_generated/json-schema.ts +5 -0
- package/src/_generated/published.ts +7 -0
- package/src/_generated/schemas.ts +585 -0
- package/src/_generated/workspace-rules.ts +285 -0
- package/src/browser.ts +115 -0
- package/src/catalog-index.ts +121 -0
- package/src/cli.ts +99 -0
- package/src/effective.ts +200 -0
- package/src/filter.ts +47 -0
- package/src/identity.ts +56 -0
- package/src/index.ts +187 -0
- package/src/local-client.ts +127 -0
- package/src/pynect.ts +31 -0
- package/src/search.ts +582 -0
- package/src/serving-endpoints.ts +157 -0
- package/src/sources.ts +107 -0
- package/src/types.ts +49 -0
- package/src/validation.ts +127 -0
- package/src/workspace-cache.ts +234 -0
- package/src/workspace-client.ts +134 -0
- package/src/workspace-connection.ts +160 -0
- package/src/workspace-file-cache.ts +45 -0
- package/src/workspace-identity.ts +77 -0
- package/src/workspace-overlay.ts +200 -0
- package/dist/browser.js.map +0 -38
- package/dist/catalog.json +0 -1
- package/dist/cli.js.map +0 -40
- package/dist/index.js.map +0 -39
- package/dist/pynect.js +0 -553
- package/dist/pynect.js.map +0 -15
- package/dist/search-index.json +0 -1
- package/dist/snapshot.d.ts +0 -7
- package/dist/snapshot.js +0 -9515
- package/dist/snapshot.js.map +0 -36
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
EffectiveEndpoint,
|
|
3
|
+
IdentityCandidate,
|
|
4
|
+
ServingEndpoint,
|
|
5
|
+
ServingEndpointsResponse,
|
|
6
|
+
WorkspaceModelProfile,
|
|
7
|
+
} from "./_generated/schemas.js";
|
|
8
|
+
import { WORKSPACE_OVERLAY_RULES } from "./_generated/workspace-rules.js";
|
|
9
|
+
import { parseServingEndpoint, parseServingEndpointsResponse } from "./validation.js";
|
|
10
|
+
|
|
11
|
+
/** Catalog-owned normalized Serving Endpoints record; absent values stay absent (unknown). */
|
|
12
|
+
export type WorkspaceEndpoint = Omit<EffectiveEndpoint, "match" | "fields">;
|
|
13
|
+
|
|
14
|
+
const RULES = WORKSPACE_OVERLAY_RULES;
|
|
15
|
+
const MODEL_SERVICE_KINDS: ReadonlySet<string> = new Set(["served_entity", "foundation_model"]);
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Validate a raw `GET /api/2.0/serving-endpoints` listing and normalize every named endpoint,
|
|
19
|
+
* sorted by name. Endpoints without a name are skipped; a repeated name keeps its first entry.
|
|
20
|
+
*/
|
|
21
|
+
export function normalizeServingEndpoints(response: ServingEndpointsResponse | unknown): WorkspaceEndpoint[] {
|
|
22
|
+
const endpoints = new Map<string, WorkspaceEndpoint>();
|
|
23
|
+
for (const endpoint of parseServingEndpointsResponse(response).endpoints ?? []) {
|
|
24
|
+
const name = text(endpoint.name);
|
|
25
|
+
if (name && !endpoints.has(name)) endpoints.set(name, normalizeEndpoint(endpoint));
|
|
26
|
+
}
|
|
27
|
+
return [...endpoints.keys()].sort(compareCodePoints).map(name => endpoints.get(name)!);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Normalize one raw endpoint through the shared `WORKSPACE_OVERLAY_RULES` table. */
|
|
31
|
+
export function normalizeServingEndpoint(endpoint: ServingEndpoint | unknown): WorkspaceEndpoint {
|
|
32
|
+
return normalizeEndpoint(parseServingEndpoint(endpoint));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Exact identities in rule order, deduplicated by value; `system.ai.` entities are model services. */
|
|
36
|
+
export function endpointIdentityCandidates(endpoint: ServingEndpoint | unknown): IdentityCandidate[] {
|
|
37
|
+
return identityCandidates(parseServingEndpoint(endpoint));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Lowercase slug matching published catalog family values. */
|
|
41
|
+
export function normalizeFamily(value: string): string | undefined {
|
|
42
|
+
return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || undefined;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function normalizeEndpoint(endpoint: ServingEndpoint): WorkspaceEndpoint {
|
|
46
|
+
const entities = endpoint.config?.served_entities ?? [];
|
|
47
|
+
const task = text(endpoint.task);
|
|
48
|
+
const taskType = task === undefined ? undefined : (RULES.task_types as unknown as Record<string, TaskType>)[task];
|
|
49
|
+
const family = firstText(endpoint, RULES.family_fields);
|
|
50
|
+
const capabilities: Record<string, boolean> = {};
|
|
51
|
+
for (const [name, path] of Object.entries(RULES.capability_fields)) {
|
|
52
|
+
const value = values(endpoint, path).find(item => typeof item === "boolean");
|
|
53
|
+
if (value !== undefined) capabilities[name] = value as boolean;
|
|
54
|
+
}
|
|
55
|
+
return compact({
|
|
56
|
+
name: text(endpoint.name) ?? "",
|
|
57
|
+
display_name: firstText(endpoint, RULES.display_name_fields) ?? tagDisplayName(endpoint),
|
|
58
|
+
description: firstText(endpoint, RULES.description_fields),
|
|
59
|
+
task,
|
|
60
|
+
type: taskType?.type,
|
|
61
|
+
modalities: taskType ? structuredClone(taskType.modalities) : undefined,
|
|
62
|
+
state: text(endpoint.state?.ready),
|
|
63
|
+
source: entities.some(entity => entity.foundation_model != null)
|
|
64
|
+
? "foundation"
|
|
65
|
+
: entities.some(entity => entity.external_model != null) ? "external" : "custom",
|
|
66
|
+
family: family === undefined ? undefined : normalizeFamily(family),
|
|
67
|
+
capabilities,
|
|
68
|
+
profile: profile(endpoint),
|
|
69
|
+
identities: identityCandidates(endpoint),
|
|
70
|
+
}) as WorkspaceEndpoint;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
interface TaskType {
|
|
74
|
+
readonly type: NonNullable<WorkspaceEndpoint["type"]>;
|
|
75
|
+
readonly modalities: NonNullable<WorkspaceEndpoint["modalities"]>;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function identityCandidates(endpoint: ServingEndpoint): IdentityCandidate[] {
|
|
79
|
+
const seen = new Set<string>();
|
|
80
|
+
const candidates: IdentityCandidate[] = [];
|
|
81
|
+
for (const rule of RULES.identity_fields) {
|
|
82
|
+
const join = "join" in rule ? rule.join : undefined;
|
|
83
|
+
for (const node of values(endpoint, rule.path)) {
|
|
84
|
+
let value: string | undefined;
|
|
85
|
+
if (join) {
|
|
86
|
+
const parts = isObject(node) ? join.map(key => text(node[key])) : [undefined];
|
|
87
|
+
value = parts.every(Boolean) ? parts.join("/") : undefined;
|
|
88
|
+
} else {
|
|
89
|
+
value = text(node);
|
|
90
|
+
}
|
|
91
|
+
if (!value || seen.has(value)) continue;
|
|
92
|
+
seen.add(value);
|
|
93
|
+
const service = MODEL_SERVICE_KINDS.has(rule.kind)
|
|
94
|
+
&& RULES.model_service_prefixes.some(prefix => value.startsWith(prefix));
|
|
95
|
+
candidates.push({ kind: service ? "model_service" : rule.kind, value });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return candidates;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function profile(endpoint: ServingEndpoint): WorkspaceModelProfile | undefined {
|
|
102
|
+
for (const path of RULES.profile_fields) {
|
|
103
|
+
for (const node of values(endpoint, path)) {
|
|
104
|
+
if (!isObject(node)) continue;
|
|
105
|
+
const scores: Record<string, number> = {};
|
|
106
|
+
for (const key of RULES.profile_keys) {
|
|
107
|
+
const value = node[key];
|
|
108
|
+
if (typeof value === "number" && Number.isFinite(value)) scores[key] = value;
|
|
109
|
+
}
|
|
110
|
+
if (Object.keys(scores).length) return scores;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return undefined;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function tagDisplayName(endpoint: ServingEndpoint): string | undefined {
|
|
117
|
+
const keys: readonly string[] = RULES.display_name_tag_keys;
|
|
118
|
+
for (const tag of endpoint.tags ?? []) {
|
|
119
|
+
const value = keys.includes(tag.key) ? text(tag.value) : undefined;
|
|
120
|
+
if (value) return value;
|
|
121
|
+
}
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function firstText(node: unknown, paths: readonly (readonly string[])[]): string | undefined {
|
|
126
|
+
for (const path of paths) {
|
|
127
|
+
for (const value of values(node, path)) {
|
|
128
|
+
const result = text(value);
|
|
129
|
+
if (result) return result;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Walk a rule path; `*` expands every array element in order. */
|
|
136
|
+
function values(node: unknown, path: readonly string[]): unknown[] {
|
|
137
|
+
if (!path.length) return [node];
|
|
138
|
+
const [head, ...rest] = path;
|
|
139
|
+
if (head === "*") return Array.isArray(node) ? node.flatMap(item => values(item, rest)) : [];
|
|
140
|
+
return isObject(node) && head! in node ? values(node[head!], rest) : [];
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function text(value: unknown): string | undefined {
|
|
144
|
+
return typeof value === "string" ? value.trim() || undefined : undefined;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function isObject(value: unknown): value is Record<string, unknown> {
|
|
148
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function compact<T extends Record<string, unknown>>(value: T): T {
|
|
152
|
+
return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined)) as T;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function compareCodePoints(left: string, right: string): number {
|
|
156
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
157
|
+
}
|
package/src/sources.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser-safe catalog source loading for `createModelCatalogClient`. Internal: the Node entry
|
|
3
|
+
* point adds file paths and `DBX_MODEL_CATALOG_PATH` on top of these loaders.
|
|
4
|
+
*/
|
|
5
|
+
import type { CatalogSearchIndexPayload, ModelCatalog } from "./_generated/schemas.js";
|
|
6
|
+
import {
|
|
7
|
+
PUBLISHED_CATALOG_SEARCH_INDEX_URL,
|
|
8
|
+
PUBLISHED_CATALOG_URL,
|
|
9
|
+
} from "./_generated/published.js";
|
|
10
|
+
import type { LoadedCatalog } from "./local-client.js";
|
|
11
|
+
import { parseCatalogSearchIndex, parseModelCatalog } from "./validation.js";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* A catalog source: an `http(s)` catalog URL, a `ws(s)` URL of the Python catalog server, or an
|
|
15
|
+
* already-loaded catalog. The Node entry point also accepts file paths and `file:` URLs.
|
|
16
|
+
*/
|
|
17
|
+
export type ModelCatalogSourceInput = string | URL | ModelCatalog;
|
|
18
|
+
|
|
19
|
+
/** Source-loading options shared by both entry points. */
|
|
20
|
+
export interface CatalogSourceOptions {
|
|
21
|
+
/** Transport for catalog downloads and workspace requests. */
|
|
22
|
+
fetch?: typeof globalThis.fetch;
|
|
23
|
+
/**
|
|
24
|
+
* The search index: a payload (required with an in-memory catalog) or its URL (in Node, also a
|
|
25
|
+
* file path). Defaults to `search-index.json` beside a catalog URL or file. WebSocket sources
|
|
26
|
+
* always read the server's index.
|
|
27
|
+
*/
|
|
28
|
+
searchIndex?: CatalogSearchIndexPayload | string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function isWebSocketUrl(value: string): boolean {
|
|
32
|
+
return /^wss?:/i.test(value);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function isHttpUrl(value: string): boolean {
|
|
36
|
+
return /^https?:/i.test(value);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Load a source in any runtime: published default, URL download, WebSocket, or in-memory. */
|
|
40
|
+
export async function loadBrowserSource(
|
|
41
|
+
source: ModelCatalogSourceInput | undefined,
|
|
42
|
+
options: CatalogSourceOptions,
|
|
43
|
+
): Promise<LoadedCatalog> {
|
|
44
|
+
if (source === undefined) return loadPublished(options);
|
|
45
|
+
if (typeof source === "string" || source instanceof URL) {
|
|
46
|
+
const location = source.toString();
|
|
47
|
+
if (isWebSocketUrl(location)) return loadWebSocket(location);
|
|
48
|
+
return loadUrl(new URL(location, documentUrl()).toString(), options);
|
|
49
|
+
}
|
|
50
|
+
return loadMemory(source, options);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The page URL in a browser, against which relative catalog URLs resolve. */
|
|
54
|
+
function documentUrl(): string | undefined {
|
|
55
|
+
return (globalThis as { location?: { href?: string } }).location?.href;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function loadPublished(options: CatalogSourceOptions): Promise<LoadedCatalog> {
|
|
59
|
+
return download(PUBLISHED_CATALOG_URL, options.searchIndex ?? PUBLISHED_CATALOG_SEARCH_INDEX_URL, options, "published");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function loadUrl(url: string, options: CatalogSourceOptions): Promise<LoadedCatalog> {
|
|
63
|
+
return download(url, options.searchIndex ?? new URL("search-index.json", url).toString(), options, "url");
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function loadMemory(catalog: ModelCatalog, options: CatalogSourceOptions): LoadedCatalog {
|
|
67
|
+
if (options.searchIndex === undefined || typeof options.searchIndex === "string") {
|
|
68
|
+
throw new TypeError("An in-memory catalog needs its search index payload as options.searchIndex");
|
|
69
|
+
}
|
|
70
|
+
return { catalog, searchIndex: options.searchIndex, source: { kind: "memory" } };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function loadWebSocket(url: string): Promise<LoadedCatalog> {
|
|
74
|
+
let transport: typeof import("./pynect.js");
|
|
75
|
+
try {
|
|
76
|
+
transport = await import("./pynect.js");
|
|
77
|
+
} catch (cause) {
|
|
78
|
+
throw new Error(
|
|
79
|
+
"WebSocket catalog sources need the optional peers pynect and @chanx-js/client; "
|
|
80
|
+
+ "install them with `bun add pynect @chanx-js/client`",
|
|
81
|
+
{ cause },
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
return { ...(await transport.downloadWebSocketCatalog(url)), source: { kind: "websocket", location: url } };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function download(
|
|
88
|
+
catalogUrl: string,
|
|
89
|
+
searchIndex: CatalogSearchIndexPayload | string,
|
|
90
|
+
options: CatalogSourceOptions,
|
|
91
|
+
kind: "published" | "url",
|
|
92
|
+
): Promise<LoadedCatalog> {
|
|
93
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
94
|
+
const [catalog, index] = await Promise.all([
|
|
95
|
+
fetchJson(fetcher, catalogUrl, "Catalog").then(parseModelCatalog),
|
|
96
|
+
typeof searchIndex === "string"
|
|
97
|
+
? fetchJson(fetcher, searchIndex, "Search index").then(parseCatalogSearchIndex)
|
|
98
|
+
: searchIndex,
|
|
99
|
+
]);
|
|
100
|
+
return { catalog, searchIndex: index, source: { kind, location: catalogUrl } };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function fetchJson(fetcher: typeof globalThis.fetch, url: string, label: string): Promise<unknown> {
|
|
104
|
+
const response = await fetcher(url);
|
|
105
|
+
if (!response.ok) throw new Error(`${label} request failed with ${response.status}`);
|
|
106
|
+
return response.json();
|
|
107
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
CatalogFilters,
|
|
3
|
+
CatalogModelRecord,
|
|
4
|
+
CatalogSearchIndexPayload,
|
|
5
|
+
EffectiveModelCatalog,
|
|
6
|
+
ModelCatalog,
|
|
7
|
+
WorkspaceRefresh,
|
|
8
|
+
} from "./_generated/schemas.js";
|
|
9
|
+
import type { CatalogIdentityMatch } from "./catalog-index.js";
|
|
10
|
+
import type { CatalogSearchMatch } from "./search.js";
|
|
11
|
+
|
|
12
|
+
/** Where a client's public catalog came from. */
|
|
13
|
+
export type ModelCatalogSourceKind = "published" | "url" | "websocket" | "file" | "memory";
|
|
14
|
+
|
|
15
|
+
export interface ModelCatalogSource {
|
|
16
|
+
readonly kind: ModelCatalogSourceKind;
|
|
17
|
+
/** Catalog URL, WebSocket server URL, or resolved file path; absent for an in-memory catalog. */
|
|
18
|
+
readonly location?: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Catalog client over the effective catalog: the public records plus, when a workspace connection
|
|
23
|
+
* is configured, the caller's accessible Serving Endpoints. `catalog`, `searchIndex`, `list`, `get`,
|
|
24
|
+
* `resolve`, `search`, and `stream` all read the effective records. Without a workspace connection
|
|
25
|
+
* the status is `disabled` and no workspace request is ever made.
|
|
26
|
+
*/
|
|
27
|
+
export interface ModelCatalogClient extends AsyncDisposable {
|
|
28
|
+
/** Where the public catalog was loaded from. */
|
|
29
|
+
readonly source: ModelCatalogSource;
|
|
30
|
+
catalog(): Promise<ModelCatalog>;
|
|
31
|
+
searchIndex(): Promise<CatalogSearchIndexPayload>;
|
|
32
|
+
list(filters?: CatalogFilters): Promise<CatalogModelRecord[]>;
|
|
33
|
+
get(identity: string): Promise<CatalogModelRecord | undefined>;
|
|
34
|
+
resolve(identity: string): Promise<CatalogIdentityMatch | undefined>;
|
|
35
|
+
search(query: string, limit?: number | null): Promise<CatalogSearchMatch[]>;
|
|
36
|
+
stream(filters?: CatalogFilters): AsyncGenerator<CatalogModelRecord>;
|
|
37
|
+
/** Merged records with workspace refresh state, endpoint access, and field provenance. */
|
|
38
|
+
effectiveCatalog(): Promise<EffectiveModelCatalog>;
|
|
39
|
+
/** Workspace refresh state of the served effective catalog. */
|
|
40
|
+
workspaceStatus(): Promise<WorkspaceRefresh>;
|
|
41
|
+
/** True when the connected workspace listed `id` as an invocable endpoint. */
|
|
42
|
+
isAccessible(id: string): Promise<boolean>;
|
|
43
|
+
/** Refresh this workspace and principal's overlay now; failures are reported, not thrown. */
|
|
44
|
+
refreshWorkspace(): Promise<WorkspaceRefresh>;
|
|
45
|
+
/** Drop this workspace and principal's cached overlay, or every cached overlay with `all`. */
|
|
46
|
+
evictWorkspace(options?: { all?: boolean }): Promise<void>;
|
|
47
|
+
/** Wait for in-flight and background workspace refreshes. */
|
|
48
|
+
close(): Promise<void>;
|
|
49
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import {
|
|
3
|
+
CATALOG_SEARCH_INDEX_JSON_SCHEMA,
|
|
4
|
+
MODEL_CATALOG_JSON_SCHEMA,
|
|
5
|
+
} from "./_generated/json-schema.js";
|
|
6
|
+
import type {
|
|
7
|
+
AveragePrice,
|
|
8
|
+
Capabilities,
|
|
9
|
+
CatalogModel,
|
|
10
|
+
CatalogModelRecord,
|
|
11
|
+
CatalogSearchIndexPayload,
|
|
12
|
+
EffectiveModelCatalog,
|
|
13
|
+
Latency,
|
|
14
|
+
ModelCatalog,
|
|
15
|
+
Price,
|
|
16
|
+
Rankings,
|
|
17
|
+
Rankings1,
|
|
18
|
+
RateLimits,
|
|
19
|
+
ServingEndpoint,
|
|
20
|
+
ServingEndpointsResponse,
|
|
21
|
+
Status,
|
|
22
|
+
WorkspaceRefresh,
|
|
23
|
+
} from "./_generated/schemas.js";
|
|
24
|
+
|
|
25
|
+
type JsonSchemaInput = Parameters<typeof z.fromJSONSchema>[0];
|
|
26
|
+
type ModelCatalogDefinition = keyof typeof MODEL_CATALOG_JSON_SCHEMA.$defs;
|
|
27
|
+
|
|
28
|
+
function modelCatalogDefinitionSchema<T>(definition: ModelCatalogDefinition): z.ZodType<T> {
|
|
29
|
+
return z.fromJSONSchema({
|
|
30
|
+
...MODEL_CATALOG_JSON_SCHEMA.$defs[definition],
|
|
31
|
+
$defs: MODEL_CATALOG_JSON_SCHEMA.$defs,
|
|
32
|
+
} as unknown as JsonSchemaInput) as z.ZodType<T>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Runtime schema for the complete published model catalog. */
|
|
36
|
+
export const ModelCatalogSchema = z.fromJSONSchema(
|
|
37
|
+
MODEL_CATALOG_JSON_SCHEMA as unknown as JsonSchemaInput,
|
|
38
|
+
) as z.ZodType<ModelCatalog>;
|
|
39
|
+
|
|
40
|
+
/** Runtime schema for the published catalog search index. */
|
|
41
|
+
export const CatalogSearchIndexSchema = z.fromJSONSchema(
|
|
42
|
+
CATALOG_SEARCH_INDEX_JSON_SCHEMA as unknown as JsonSchemaInput,
|
|
43
|
+
) as z.ZodType<CatalogSearchIndexPayload>;
|
|
44
|
+
|
|
45
|
+
/** Runtime schema for one catalog model without its map key. */
|
|
46
|
+
export const CatalogModelSchema = modelCatalogDefinitionSchema<CatalogModel>("CatalogModel");
|
|
47
|
+
|
|
48
|
+
/** Runtime schema for one catalog model with its stable id. */
|
|
49
|
+
export const CatalogModelRecordSchema =
|
|
50
|
+
modelCatalogDefinitionSchema<CatalogModelRecord>("CatalogModelRecord");
|
|
51
|
+
|
|
52
|
+
/** Runtime schema for catalog-owned model capabilities. */
|
|
53
|
+
export const CatalogCapabilitiesSchema =
|
|
54
|
+
modelCatalogDefinitionSchema<Capabilities>("Capabilities");
|
|
55
|
+
|
|
56
|
+
/** Runtime schema for catalog-owned pay-per-token rate limits. */
|
|
57
|
+
export const CatalogRateLimitsSchema = modelCatalogDefinitionSchema<RateLimits>("RateLimits");
|
|
58
|
+
|
|
59
|
+
/** Runtime schema for catalog-owned latency measurements and score. */
|
|
60
|
+
export const CatalogLatencySchema = modelCatalogDefinitionSchema<Latency>("Latency");
|
|
61
|
+
|
|
62
|
+
/** Runtime schema for one catalog-owned cloud and currency price. */
|
|
63
|
+
export const CatalogPriceSchema = modelCatalogDefinitionSchema<Price>("Price");
|
|
64
|
+
|
|
65
|
+
/** Runtime schema for one catalog-owned normalized currency price. */
|
|
66
|
+
export const CatalogAveragePriceSchema =
|
|
67
|
+
modelCatalogDefinitionSchema<AveragePrice>("AveragePrice");
|
|
68
|
+
|
|
69
|
+
/** Runtime schema for a preference-rating ranking. */
|
|
70
|
+
export const CatalogPreferenceRankingSchema =
|
|
71
|
+
modelCatalogDefinitionSchema<Rankings>("Rankings");
|
|
72
|
+
|
|
73
|
+
/** Runtime schema for a scored-evaluation ranking. */
|
|
74
|
+
export const CatalogScoreRankingSchema = modelCatalogDefinitionSchema<Rankings1>("Rankings1");
|
|
75
|
+
|
|
76
|
+
/** Runtime schema for either catalog ranking representation. */
|
|
77
|
+
export const CatalogRankingSchema = z.union([
|
|
78
|
+
CatalogPreferenceRankingSchema,
|
|
79
|
+
CatalogScoreRankingSchema,
|
|
80
|
+
]);
|
|
81
|
+
|
|
82
|
+
/** Runtime schema for a catalog model lifecycle status. */
|
|
83
|
+
export const CatalogStatusSchema = modelCatalogDefinitionSchema<Status>("Status");
|
|
84
|
+
|
|
85
|
+
/** Runtime schema for a workspace-effective catalog (public catalog plus accessible endpoints). */
|
|
86
|
+
export const EffectiveModelCatalogSchema =
|
|
87
|
+
modelCatalogDefinitionSchema<EffectiveModelCatalog>("EffectiveModelCatalog");
|
|
88
|
+
|
|
89
|
+
/** Runtime schema for workspace overlay refresh state. */
|
|
90
|
+
export const WorkspaceRefreshSchema = modelCatalogDefinitionSchema<WorkspaceRefresh>("WorkspaceRefresh");
|
|
91
|
+
|
|
92
|
+
/** Runtime schema for a raw `GET /api/2.0/serving-endpoints` response; unknown members are ignored. */
|
|
93
|
+
export const ServingEndpointsResponseSchema =
|
|
94
|
+
modelCatalogDefinitionSchema<ServingEndpointsResponse>("ServingEndpointsResponse");
|
|
95
|
+
|
|
96
|
+
/** Runtime schema for one raw serving endpoint. */
|
|
97
|
+
export const ServingEndpointSchema = modelCatalogDefinitionSchema<ServingEndpoint>("ServingEndpoint");
|
|
98
|
+
|
|
99
|
+
/** Validate an untrusted catalog payload against the Python-owned contract. */
|
|
100
|
+
export function parseModelCatalog(value: unknown): ModelCatalog {
|
|
101
|
+
return ModelCatalogSchema.parse(value);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Validate an untrusted search-index payload against the Python-owned contract. */
|
|
105
|
+
export function parseCatalogSearchIndex(value: unknown): CatalogSearchIndexPayload {
|
|
106
|
+
return CatalogSearchIndexSchema.parse(value);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Validate one untrusted catalog model record. */
|
|
110
|
+
export function parseCatalogModelRecord(value: unknown): CatalogModelRecord {
|
|
111
|
+
return CatalogModelRecordSchema.parse(value);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Validate an untrusted effective catalog payload. */
|
|
115
|
+
export function parseEffectiveModelCatalog(value: unknown): EffectiveModelCatalog {
|
|
116
|
+
return EffectiveModelCatalogSchema.parse(value);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Validate a raw Serving Endpoints listing. */
|
|
120
|
+
export function parseServingEndpointsResponse(value: unknown): ServingEndpointsResponse {
|
|
121
|
+
return ServingEndpointsResponseSchema.parse(value ?? {});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Validate one raw serving endpoint. */
|
|
125
|
+
export function parseServingEndpoint(value: unknown): ServingEndpoint {
|
|
126
|
+
return ServingEndpointSchema.parse(value);
|
|
127
|
+
}
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import { WORKSPACE_OVERLAY_RULES } from "./_generated/workspace-rules.js";
|
|
2
|
+
import type { WorkspaceIdentity } from "./workspace-identity.js";
|
|
3
|
+
|
|
4
|
+
/** Five minutes, from the shared `cache.refresh_interval_seconds` rule. */
|
|
5
|
+
export const DEFAULT_WORKSPACE_REFRESH_AFTER_MS: number =
|
|
6
|
+
WORKSPACE_OVERLAY_RULES.cache.refresh_interval_seconds * 1000;
|
|
7
|
+
/** Seven days, from the shared `cache.stale_ttl_seconds` rule. */
|
|
8
|
+
export const DEFAULT_WORKSPACE_STALE_ON_ERROR_MS: number =
|
|
9
|
+
WORKSPACE_OVERLAY_RULES.cache.stale_ttl_seconds * 1000;
|
|
10
|
+
|
|
11
|
+
/** Keyv-store-compatible persistence (for example `keyv-file`'s `KeyvFile`). `ttl` is milliseconds. */
|
|
12
|
+
export interface WorkspaceCacheStore {
|
|
13
|
+
get(key: string): Promise<unknown>;
|
|
14
|
+
set(key: string, value: unknown, ttl?: number): Promise<unknown>;
|
|
15
|
+
delete(key: string): Promise<boolean>;
|
|
16
|
+
clear(): Promise<unknown>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Cache key for one workspace, contract version, and principal. `shared` is false when no
|
|
21
|
+
* principal identity is available; such entries stay in the cache instance's session memory.
|
|
22
|
+
*/
|
|
23
|
+
export interface WorkspaceCacheKey {
|
|
24
|
+
readonly id: string;
|
|
25
|
+
readonly shared: boolean;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface WorkspaceCacheKeyInput {
|
|
29
|
+
/** Workspace identity; absent when the source exposes no host, which keeps the key session-only. */
|
|
30
|
+
readonly workspace?: WorkspaceIdentity | undefined;
|
|
31
|
+
readonly contractVersion: string | number;
|
|
32
|
+
/** Non-secret principal identity, such as the SCIM `Me` id. Stored only as a SHA-256 hash. */
|
|
33
|
+
readonly principal?: string | undefined;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface WorkspaceCatalogCacheOptions {
|
|
37
|
+
/** Shared store for keys with a principal. Defaults to process-wide memory. */
|
|
38
|
+
store?: WorkspaceCacheStore;
|
|
39
|
+
/** Age after which a hit is returned while one background refresh runs. Defaults to 5 minutes. */
|
|
40
|
+
refreshAfterMs?: number;
|
|
41
|
+
/** Maximum age of an entry served while refreshing or after a refresh error. Defaults to 7 days. */
|
|
42
|
+
staleOnErrorMs?: number;
|
|
43
|
+
now?: () => number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** `fresh`: within the refresh interval; `refreshing`: served while a refresh runs; `stale`: the last refresh failed. */
|
|
47
|
+
export type WorkspaceCacheStatus = "fresh" | "refreshing" | "stale";
|
|
48
|
+
|
|
49
|
+
export interface WorkspaceCacheResult<T> {
|
|
50
|
+
readonly value: T;
|
|
51
|
+
readonly status: WorkspaceCacheStatus;
|
|
52
|
+
readonly writtenAt: number;
|
|
53
|
+
readonly ageMs: number;
|
|
54
|
+
readonly shared: boolean;
|
|
55
|
+
/** The most recent refresh error when `status` is `stale`. */
|
|
56
|
+
readonly error?: unknown;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface WorkspaceCatalogCache<T> {
|
|
60
|
+
/** Return a cached value, refreshing in the background after the refresh interval, or load it. */
|
|
61
|
+
get(key: WorkspaceCacheKey, load: () => Promise<T>): Promise<WorkspaceCacheResult<T>>;
|
|
62
|
+
/** Reload now, returning a bounded stale entry with its error if the load fails. */
|
|
63
|
+
refresh(key: WorkspaceCacheKey, load: () => Promise<T>): Promise<WorkspaceCacheResult<T>>;
|
|
64
|
+
/** Remove only the matching workspace and principal entry. */
|
|
65
|
+
evict(key: WorkspaceCacheKey): Promise<boolean>;
|
|
66
|
+
/** Remove every entry in the shared store and this instance's session memory. */
|
|
67
|
+
clear(): Promise<void>;
|
|
68
|
+
/** Wait for background refreshes started by this instance. */
|
|
69
|
+
settle(): Promise<void>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
interface Entry<T> {
|
|
73
|
+
readonly value: T;
|
|
74
|
+
readonly writtenAt: number;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
interface StoreState {
|
|
78
|
+
readonly inflight: Map<string, Promise<Entry<unknown>>>;
|
|
79
|
+
readonly failures: Map<string, { readonly error: unknown; readonly at: number }>;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const sharedMemoryStore = createMemoryWorkspaceCacheStore();
|
|
83
|
+
const storeStates = new WeakMap<WorkspaceCacheStore, StoreState>();
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Build a key from workspace identity, contract version, and SHA-256 of the principal identity.
|
|
87
|
+
* The key is shared only when both the workspace and the principal are known.
|
|
88
|
+
*/
|
|
89
|
+
export async function workspaceCacheKey(input: WorkspaceCacheKeyInput): Promise<WorkspaceCacheKey> {
|
|
90
|
+
const principal = input.workspace ? input.principal?.trim() : undefined;
|
|
91
|
+
const scope = principal ? await sha256(principal) : "session";
|
|
92
|
+
const workspace = input.workspace
|
|
93
|
+
? `${input.workspace.kind}:${encodeURIComponent(input.workspace.value)}`
|
|
94
|
+
: "unknown";
|
|
95
|
+
return {
|
|
96
|
+
id: `workspace-catalog/v${input.contractVersion}/${workspace}/${scope}`,
|
|
97
|
+
shared: Boolean(principal),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** In-memory store with millisecond TTLs. */
|
|
102
|
+
export function createMemoryWorkspaceCacheStore(now: () => number = Date.now): WorkspaceCacheStore {
|
|
103
|
+
const entries = new Map<string, { value: unknown; expires?: number }>();
|
|
104
|
+
return {
|
|
105
|
+
async get(key) {
|
|
106
|
+
const entry = entries.get(key);
|
|
107
|
+
if (entry?.expires !== undefined && entry.expires <= now()) entries.delete(key);
|
|
108
|
+
return entries.get(key)?.value;
|
|
109
|
+
},
|
|
110
|
+
async set(key, value, ttl) {
|
|
111
|
+
entries.set(key, ttl ? { value, expires: now() + ttl } : { value });
|
|
112
|
+
return true;
|
|
113
|
+
},
|
|
114
|
+
async delete(key) {
|
|
115
|
+
return entries.delete(key);
|
|
116
|
+
},
|
|
117
|
+
async clear() {
|
|
118
|
+
entries.clear();
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Workspace-scoped cache with refresh-after-write, in-flight coalescing, and bounded stale-on-error. */
|
|
124
|
+
export function createWorkspaceCatalogCache<T>(
|
|
125
|
+
options: WorkspaceCatalogCacheOptions = {},
|
|
126
|
+
): WorkspaceCatalogCache<T> {
|
|
127
|
+
const now = options.now ?? Date.now;
|
|
128
|
+
const refreshAfterMs = options.refreshAfterMs ?? DEFAULT_WORKSPACE_REFRESH_AFTER_MS;
|
|
129
|
+
const staleOnErrorMs = options.staleOnErrorMs ?? DEFAULT_WORKSPACE_STALE_ON_ERROR_MS;
|
|
130
|
+
const shared = options.store ?? sharedMemoryStore;
|
|
131
|
+
const session = createMemoryWorkspaceCacheStore(now);
|
|
132
|
+
const background = new Set<Promise<unknown>>();
|
|
133
|
+
|
|
134
|
+
const storeFor = (key: WorkspaceCacheKey) => (key.shared ? shared : session);
|
|
135
|
+
|
|
136
|
+
const read = async (key: WorkspaceCacheKey): Promise<Entry<T> | undefined> => {
|
|
137
|
+
const entry = (await storeFor(key).get(key.id)) as Entry<T> | undefined;
|
|
138
|
+
if (!entry || typeof entry.writtenAt !== "number") return undefined;
|
|
139
|
+
return now() - entry.writtenAt < staleOnErrorMs ? entry : undefined;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
const load = (key: WorkspaceCacheKey, loader: () => Promise<T>): Promise<Entry<T>> => {
|
|
143
|
+
const store = storeFor(key);
|
|
144
|
+
const state = stateFor(store);
|
|
145
|
+
const existing = state.inflight.get(key.id);
|
|
146
|
+
if (existing) return existing as Promise<Entry<T>>;
|
|
147
|
+
const pending = (async () => {
|
|
148
|
+
try {
|
|
149
|
+
const entry: Entry<T> = { value: await loader(), writtenAt: now() };
|
|
150
|
+
await store.set(key.id, entry, staleOnErrorMs);
|
|
151
|
+
state.failures.delete(key.id);
|
|
152
|
+
return entry;
|
|
153
|
+
} catch (error) {
|
|
154
|
+
state.failures.set(key.id, { error, at: now() });
|
|
155
|
+
throw error;
|
|
156
|
+
} finally {
|
|
157
|
+
state.inflight.delete(key.id);
|
|
158
|
+
}
|
|
159
|
+
})();
|
|
160
|
+
state.inflight.set(key.id, pending);
|
|
161
|
+
return pending;
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
const result = (
|
|
165
|
+
key: WorkspaceCacheKey,
|
|
166
|
+
entry: Entry<T>,
|
|
167
|
+
status: WorkspaceCacheStatus,
|
|
168
|
+
error?: unknown,
|
|
169
|
+
): WorkspaceCacheResult<T> => ({
|
|
170
|
+
value: entry.value,
|
|
171
|
+
status,
|
|
172
|
+
writtenAt: entry.writtenAt,
|
|
173
|
+
ageMs: Math.max(0, now() - entry.writtenAt),
|
|
174
|
+
shared: key.shared,
|
|
175
|
+
...(status === "stale" ? { error } : {}),
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
return {
|
|
179
|
+
async get(key, loader) {
|
|
180
|
+
const entry = await read(key);
|
|
181
|
+
if (!entry) return result(key, await load(key, loader), "fresh");
|
|
182
|
+
if (now() - entry.writtenAt < refreshAfterMs) return result(key, entry, "fresh");
|
|
183
|
+
const failure = stateFor(storeFor(key)).failures.get(key.id);
|
|
184
|
+
const failed = failure !== undefined && failure.at >= entry.writtenAt;
|
|
185
|
+
// After a failed refresh, retry at most once per refresh interval.
|
|
186
|
+
if (!failed || now() - failure.at >= refreshAfterMs) {
|
|
187
|
+
const refresh = load(key, loader).catch(() => undefined);
|
|
188
|
+
background.add(refresh);
|
|
189
|
+
void refresh.finally(() => background.delete(refresh));
|
|
190
|
+
}
|
|
191
|
+
return failed ? result(key, entry, "stale", failure.error) : result(key, entry, "refreshing");
|
|
192
|
+
},
|
|
193
|
+
|
|
194
|
+
async refresh(key, loader) {
|
|
195
|
+
try {
|
|
196
|
+
return result(key, await load(key, loader), "fresh");
|
|
197
|
+
} catch (error) {
|
|
198
|
+
const entry = await read(key);
|
|
199
|
+
if (!entry) throw error;
|
|
200
|
+
return result(key, entry, "stale", error);
|
|
201
|
+
}
|
|
202
|
+
},
|
|
203
|
+
|
|
204
|
+
async evict(key) {
|
|
205
|
+
const store = storeFor(key);
|
|
206
|
+
stateFor(store).failures.delete(key.id);
|
|
207
|
+
return store.delete(key.id);
|
|
208
|
+
},
|
|
209
|
+
|
|
210
|
+
async clear() {
|
|
211
|
+
stateFor(shared).failures.clear();
|
|
212
|
+
stateFor(session).failures.clear();
|
|
213
|
+
await Promise.all([shared.clear(), session.clear()]);
|
|
214
|
+
},
|
|
215
|
+
|
|
216
|
+
async settle() {
|
|
217
|
+
while (background.size > 0) await Promise.all([...background]);
|
|
218
|
+
},
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function stateFor(store: WorkspaceCacheStore): StoreState {
|
|
223
|
+
let state = storeStates.get(store);
|
|
224
|
+
if (!state) {
|
|
225
|
+
state = { inflight: new Map(), failures: new Map() };
|
|
226
|
+
storeStates.set(store, state);
|
|
227
|
+
}
|
|
228
|
+
return state;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async function sha256(value: string): Promise<string> {
|
|
232
|
+
const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
|
|
233
|
+
return Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, "0")).join("");
|
|
234
|
+
}
|