@dbx-tools/dbx-model-catalog 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +294 -57
  2. package/dist/_generated/channels.d.ts +4 -3
  3. package/dist/_generated/json-schema.d.ts +6527 -175
  4. package/dist/_generated/schemas.d.ts +154 -0
  5. package/dist/_generated/workspace-rules.d.ts +133 -0
  6. package/dist/browser.d.ts +34 -17
  7. package/dist/browser.js +1192 -149
  8. package/dist/catalog-index.d.ts +15 -2
  9. package/dist/chunk-engbh7tj.js +39 -0
  10. package/dist/chunk-gzjer0mc.js +1797 -0
  11. package/dist/chunk-pp7fw379.js +51 -0
  12. package/dist/chunk-pwssxaq0.js +39 -0
  13. package/dist/cli.js +9 -654
  14. package/dist/effective.d.ts +31 -0
  15. package/dist/index.d.ts +33 -16
  16. package/dist/index.js +60 -660
  17. package/dist/local-client.d.ts +16 -3
  18. package/dist/pynect.d.ts +6 -3
  19. package/dist/search.d.ts +7 -1
  20. package/dist/serving-endpoints.d.ts +15 -0
  21. package/dist/sources.d.ts +30 -0
  22. package/dist/types.d.ts +31 -3
  23. package/dist/validation.d.ts +15 -1
  24. package/dist/workspace-cache.d.ts +68 -0
  25. package/dist/workspace-client.d.ts +49 -0
  26. package/dist/workspace-connection.d.ts +67 -0
  27. package/dist/workspace-file-cache.d.ts +11 -0
  28. package/dist/workspace-identity.d.ts +27 -0
  29. package/dist/workspace-overlay.d.ts +71 -0
  30. package/package.json +5 -6
  31. package/src/_generated/channels.ts +5 -2
  32. package/src/_generated/json-schema.ts +4 -2
  33. package/src/_generated/schemas.ts +177 -0
  34. package/src/_generated/workspace-rules.ts +285 -0
  35. package/src/browser.ts +105 -54
  36. package/src/catalog-index.ts +46 -19
  37. package/src/cli.ts +8 -11
  38. package/src/effective.ts +200 -0
  39. package/src/identity.ts +3 -26
  40. package/src/index.ts +155 -82
  41. package/src/local-client.ts +94 -18
  42. package/src/pynect.ts +28 -65
  43. package/src/search.ts +48 -0
  44. package/src/serving-endpoints.ts +157 -0
  45. package/src/sources.ts +107 -0
  46. package/src/types.ts +32 -2
  47. package/src/validation.ts +33 -0
  48. package/src/workspace-cache.ts +234 -0
  49. package/src/workspace-client.ts +134 -0
  50. package/src/workspace-connection.ts +160 -0
  51. package/src/workspace-file-cache.ts +45 -0
  52. package/src/workspace-identity.ts +77 -0
  53. package/src/workspace-overlay.ts +200 -0
  54. package/dist/pynect.js +0 -557
@@ -2,50 +2,126 @@ import type {
2
2
  CatalogFilters,
3
3
  CatalogModelRecord,
4
4
  CatalogSearchIndexPayload,
5
+ EffectiveModelCatalog,
5
6
  ModelCatalog,
7
+ WorkspaceRefresh,
6
8
  } from "./_generated/schemas.js";
7
- import type { CatalogClient } from "./types.js";
8
- import { createModelCatalogIndex } from "./catalog-index.js";
9
- import { filterCatalogRecords } from "./filter.js";
9
+ import type { ModelCatalogClient, ModelCatalogSource } from "./types.js";
10
+ import { ModelCatalogIndex } from "./catalog-index.js";
11
+ import { buildEffectiveCatalog, buildEffectiveSearchIndex, isEffectiveModelAccessible } from "./effective.js";
12
+ import type { ModelServingConnector } from "./workspace-connection.js";
13
+ import {
14
+ type WorkspaceCacheOptions,
15
+ type WorkspaceOverlayState,
16
+ WorkspaceOverlaySession,
17
+ } from "./workspace-overlay.js";
10
18
 
11
- export function createModelCatalogClient(
12
- catalog: ModelCatalog,
13
- searchIndex: CatalogSearchIndexPayload,
14
- ): CatalogClient {
15
- const index = createModelCatalogIndex(catalog, searchIndex);
16
- const records: CatalogModelRecord[] = [...index.records];
19
+ interface CatalogView {
20
+ readonly effective: EffectiveModelCatalog;
21
+ readonly index: ModelCatalogIndex;
22
+ }
23
+
24
+ /** Overlay session for a normalized connector, or `undefined` for a public-only client. Internal. */
25
+ export function workspaceOverlay(
26
+ connector: ModelServingConnector | undefined,
27
+ cache?: WorkspaceCacheOptions,
28
+ ): WorkspaceOverlaySession | undefined {
29
+ return connector && new WorkspaceOverlaySession(connector, cache);
30
+ }
31
+
32
+ /** A loaded public catalog, its search index, and where they came from. */
33
+ export interface LoadedCatalog {
34
+ readonly catalog: ModelCatalog;
35
+ readonly searchIndex: CatalogSearchIndexPayload;
36
+ readonly source: ModelCatalogSource;
37
+ }
38
+
39
+ /**
40
+ * The effective catalog client over a loaded public catalog and an optional overlay session. Every
41
+ * source builds this same client, so workspace enrichment works the same for each. Internal.
42
+ */
43
+ export function createCatalogClient(
44
+ { catalog, searchIndex, source }: LoadedCatalog,
45
+ overlay: WorkspaceOverlaySession | undefined,
46
+ ): ModelCatalogClient {
47
+ const publicView = catalogView(buildEffectiveCatalog(catalog), searchIndex);
48
+ let view = publicView;
49
+ let state: WorkspaceOverlayState | undefined;
50
+
51
+ const current = async (force = false): Promise<CatalogView> => {
52
+ if (!overlay) return publicView;
53
+ const next = await overlay.load({ force });
54
+ if (next !== state) {
55
+ state = next;
56
+ view = catalogView(buildEffectiveCatalog(catalog, next.endpoints ?? [], next.refresh), searchIndex);
57
+ }
58
+ return view;
59
+ };
60
+
61
+ const close = async (): Promise<void> => {
62
+ await overlay?.settle();
63
+ };
17
64
 
18
65
  return {
66
+ source,
67
+
19
68
  async catalog(): Promise<ModelCatalog> {
20
- return catalog;
69
+ return (await current()).effective.catalog;
21
70
  },
22
71
 
23
72
  async searchIndex(): Promise<CatalogSearchIndexPayload> {
24
- return searchIndex;
73
+ return (await current()).index.searchIndex;
25
74
  },
26
75
 
27
76
  async list(filters: CatalogFilters = {}): Promise<CatalogModelRecord[]> {
28
- return filterCatalogRecords(records, searchIndex, filters);
77
+ return (await current()).index.list(filters);
29
78
  },
30
79
 
31
80
  async get(identity: string): Promise<CatalogModelRecord | undefined> {
32
- return index.resolve(identity)?.record;
81
+ return (await current()).index.resolve(identity)?.record;
33
82
  },
34
83
 
35
84
  async resolve(identity: string) {
36
- return index.resolve(identity);
85
+ return (await current()).index.resolve(identity);
37
86
  },
38
87
 
39
88
  async search(query: string, limit: number | null = 50) {
40
- return index.search(query, limit);
89
+ return (await current()).index.search(query, limit);
41
90
  },
42
91
 
43
92
  async *stream(filters: CatalogFilters = {}): AsyncGenerator<CatalogModelRecord> {
44
- for (const record of filterCatalogRecords(records, searchIndex, filters)) yield record;
93
+ for (const record of (await current()).index.list(filters)) yield record;
45
94
  },
46
95
 
47
- close(): void {},
96
+ async effectiveCatalog(): Promise<EffectiveModelCatalog> {
97
+ return (await current()).effective;
98
+ },
99
+
100
+ async workspaceStatus(): Promise<WorkspaceRefresh> {
101
+ return (await current()).effective.workspace;
102
+ },
103
+
104
+ async isAccessible(id: string): Promise<boolean> {
105
+ return isEffectiveModelAccessible((await current()).effective, id);
106
+ },
107
+
108
+ async refreshWorkspace(): Promise<WorkspaceRefresh> {
109
+ return (await current(true)).effective.workspace;
110
+ },
111
+
112
+ async evictWorkspace(evict: { all?: boolean } = {}): Promise<void> {
113
+ await overlay?.evict(evict);
114
+ },
115
+
116
+ close,
117
+
118
+ [Symbol.asyncDispose]: close,
48
119
  };
49
120
  }
50
121
 
51
- export { filterCatalogRecords } from "./filter.js";
122
+ function catalogView(effective: EffectiveModelCatalog, publicIndex: CatalogSearchIndexPayload): CatalogView {
123
+ const searchIndex = Object.keys(effective.endpoints).length
124
+ ? buildEffectiveSearchIndex(effective, publicIndex)
125
+ : publicIndex;
126
+ return { effective, index: new ModelCatalogIndex(effective.catalog, searchIndex) };
127
+ }
package/src/pynect.ts CHANGED
@@ -1,68 +1,31 @@
1
- import type { ClientOptions } from "@chanx-js/client";
1
+ /**
2
+ * WebSocket catalog transport over the Python server. Internal: `createModelCatalogClient`
3
+ * imports this module dynamically for `ws://` and `wss://` sources, so the optional `pynect`
4
+ * and `@chanx-js/client` peers load only then.
5
+ */
2
6
  import { createPynectClient } from "pynect";
3
7
  import { models } from "./_generated/channels.js";
4
- import type {
5
- CatalogFilters,
6
- CatalogModelRecord,
7
- CatalogSearchIndexPayload,
8
- ModelCatalog,
9
- } from "./_generated/schemas.js";
10
- import type { CatalogClient } from "./types.js";
11
- import { createModelCatalogIndex, type ModelCatalogIndex } from "./catalog-index.js";
12
-
13
- export function createPynectCatalogClient(options: ClientOptions): CatalogClient {
14
- const connection = createPynectClient(options).connect(models);
15
- const requestCatalog = async (): Promise<ModelCatalog> => {
16
- await connection.ready({ timeout: 10_000 });
17
- return (await connection.request({ action: "get_catalog", payload: {} })).payload;
18
- };
19
- const requestSearchIndex = async (): Promise<CatalogSearchIndexPayload> => {
20
- await connection.ready({ timeout: 10_000 });
21
- return (await connection.request({ action: "get_search_index", payload: {} })).payload;
22
- };
23
- let index: Promise<ModelCatalogIndex> | undefined;
24
- const catalogIndex = (): Promise<ModelCatalogIndex> => {
25
- index ??= Promise.all([
26
- requestCatalog(),
27
- requestSearchIndex(),
28
- ]).then(([catalog, searchIndex]) => createModelCatalogIndex(catalog, searchIndex));
29
- return index;
30
- };
31
- return {
32
- async catalog(): Promise<ModelCatalog> {
33
- return requestCatalog();
34
- },
35
-
36
- async searchIndex(): Promise<CatalogSearchIndexPayload> {
37
- return requestSearchIndex();
38
- },
39
-
40
- async list(filters: CatalogFilters = {}): Promise<CatalogModelRecord[]> {
41
- await connection.ready({ timeout: 10_000 });
42
- return (await connection.request({ action: "list_models", payload: filters })).payload;
43
- },
44
-
45
- async get(identity: string): Promise<CatalogModelRecord | undefined> {
46
- return (await catalogIndex()).resolve(identity)?.record;
47
- },
48
-
49
- async resolve(identity: string) {
50
- return (await catalogIndex()).resolve(identity);
51
- },
52
-
53
- async search(query: string, limit: number | null = 50) {
54
- return (await catalogIndex()).search(query, limit);
55
- },
56
-
57
- async *stream(filters: CatalogFilters = {}): AsyncGenerator<CatalogModelRecord> {
58
- await connection.ready({ timeout: 10_000 });
59
- for await (const response of connection.request({ action: "stream_models", payload: filters })) {
60
- yield response.payload;
61
- }
62
- },
63
-
64
- close(): void {
65
- connection.close();
66
- },
67
- };
8
+ import type { CatalogSearchIndexPayload, ModelCatalog } from "./_generated/schemas.js";
9
+ import { parseCatalogSearchIndex, parseModelCatalog } from "./validation.js";
10
+
11
+ const READY_TIMEOUT_MS = 10_000;
12
+
13
+ /** Pull the catalog and its search index from the server, then close the connection. */
14
+ export async function downloadWebSocketCatalog(
15
+ baseUrl: string,
16
+ ): Promise<{ catalog: ModelCatalog; searchIndex: CatalogSearchIndexPayload }> {
17
+ const connection = createPynectClient({ baseUrl }).connect(models);
18
+ try {
19
+ await connection.ready({ timeout: READY_TIMEOUT_MS });
20
+ const [catalog, searchIndex] = await Promise.all([
21
+ connection.request({ action: "get_catalog", payload: {} }),
22
+ connection.request({ action: "get_search_index", payload: {} }),
23
+ ]);
24
+ return {
25
+ catalog: parseModelCatalog(catalog.payload),
26
+ searchIndex: parseCatalogSearchIndex(searchIndex.payload),
27
+ };
28
+ } finally {
29
+ connection.close();
30
+ }
68
31
  }
package/src/search.ts CHANGED
@@ -2,6 +2,8 @@ import type {
2
2
  CatalogModelRecord,
3
3
  CatalogSearchIndexDocument,
4
4
  CatalogSearchIndexPayload,
5
+ CatalogSearchQualityScores,
6
+ CatalogSearchWeights,
5
7
  } from "./_generated/schemas.js";
6
8
 
7
9
  // The fuzzy string scoring formulas follow RapidFuzz's MIT-licensed behavior.
@@ -90,6 +92,52 @@ export function searchCatalogMatches<T extends CatalogModelRecord>(
90
92
  return limit === null ? results : results.slice(0, limit);
91
93
  }
92
94
 
95
+ /** Query-independent quality signals carried by one search document. */
96
+ export type CatalogSearchQuality = Pick<CatalogSearchIndexDocument, "quality_score" | "scores">;
97
+
98
+ const qualityFields = ["leaderboard", "benchmark", "version", "freshness", "lifecycle"] as const;
99
+ const documentDescriptionFields = new Set(["description", "notice"]);
100
+ const documentExactFields = new Set(["id", "name", "alias"]);
101
+
102
+ /** Quality signals for precomputed scores, weighted like the published search index. */
103
+ export function catalogSearchQuality(
104
+ scores: CatalogSearchQualityScores,
105
+ weights: CatalogSearchWeights,
106
+ ): CatalogSearchQuality {
107
+ let weighted = 0;
108
+ let total = 0;
109
+ for (const name of qualityFields) {
110
+ weighted += scores[name] * weights[name];
111
+ total += weights[name];
112
+ }
113
+ return {
114
+ quality_score: round3(weighted / total),
115
+ scores: Object.fromEntries(qualityFields.map(name => [name, round3(scores[name])])) as unknown as CatalogSearchQualityScores,
116
+ };
117
+ }
118
+
119
+ /** Search document for one record, with text fields derived exactly as the published index does. */
120
+ export function catalogSearchDocument(
121
+ record: CatalogModelRecord,
122
+ quality: CatalogSearchQuality,
123
+ ): CatalogSearchIndexDocument {
124
+ const fields = searchFields(record);
125
+ const unique = (values: string[]) => [...new Set(values)];
126
+ const recordVersion = version(record.name);
127
+ return {
128
+ id: record.id,
129
+ exact_identities: unique(fields.filter(item => documentExactFields.has(item.name)).map(item => item.value)),
130
+ identities: unique(fields.filter(item => item.identity).map(item => item.value)),
131
+ keywords: unique(fields.filter(item => !documentDescriptionFields.has(item.name)).map(item => item.value)).join(" "),
132
+ description: unique(fields.filter(item => documentDescriptionFields.has(item.name)).map(item => item.value)).join(" "),
133
+ tokens: [...new Set(fields.flatMap(item => tokens(item.value)))].sort(),
134
+ ...(record.family == null ? {} : { family: record.family }),
135
+ version: recordVersion.length ? recordVersion : version(record.id),
136
+ quality_score: quality.quality_score,
137
+ scores: { ...quality.scores },
138
+ };
139
+ }
140
+
93
141
  function scoreRecord(
94
142
  record: CatalogModelRecord,
95
143
  document: CatalogSearchIndexDocument,
@@ -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 CHANGED
@@ -2,12 +2,31 @@ import type {
2
2
  CatalogFilters,
3
3
  CatalogModelRecord,
4
4
  CatalogSearchIndexPayload,
5
+ EffectiveModelCatalog,
5
6
  ModelCatalog,
7
+ WorkspaceRefresh,
6
8
  } from "./_generated/schemas.js";
7
9
  import type { CatalogIdentityMatch } from "./catalog-index.js";
8
10
  import type { CatalogSearchMatch } from "./search.js";
9
11
 
10
- export interface CatalogClient {
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;
11
30
  catalog(): Promise<ModelCatalog>;
12
31
  searchIndex(): Promise<CatalogSearchIndexPayload>;
13
32
  list(filters?: CatalogFilters): Promise<CatalogModelRecord[]>;
@@ -15,5 +34,16 @@ export interface CatalogClient {
15
34
  resolve(identity: string): Promise<CatalogIdentityMatch | undefined>;
16
35
  search(query: string, limit?: number | null): Promise<CatalogSearchMatch[]>;
17
36
  stream(filters?: CatalogFilters): AsyncGenerator<CatalogModelRecord>;
18
- close(): void;
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>;
19
49
  }
package/src/validation.ts CHANGED
@@ -9,13 +9,17 @@ import type {
9
9
  CatalogModel,
10
10
  CatalogModelRecord,
11
11
  CatalogSearchIndexPayload,
12
+ EffectiveModelCatalog,
12
13
  Latency,
13
14
  ModelCatalog,
14
15
  Price,
15
16
  Rankings,
16
17
  Rankings1,
17
18
  RateLimits,
19
+ ServingEndpoint,
20
+ ServingEndpointsResponse,
18
21
  Status,
22
+ WorkspaceRefresh,
19
23
  } from "./_generated/schemas.js";
20
24
 
21
25
  type JsonSchemaInput = Parameters<typeof z.fromJSONSchema>[0];
@@ -78,6 +82,20 @@ export const CatalogRankingSchema = z.union([
78
82
  /** Runtime schema for a catalog model lifecycle status. */
79
83
  export const CatalogStatusSchema = modelCatalogDefinitionSchema<Status>("Status");
80
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
+
81
99
  /** Validate an untrusted catalog payload against the Python-owned contract. */
82
100
  export function parseModelCatalog(value: unknown): ModelCatalog {
83
101
  return ModelCatalogSchema.parse(value);
@@ -92,3 +110,18 @@ export function parseCatalogSearchIndex(value: unknown): CatalogSearchIndexPaylo
92
110
  export function parseCatalogModelRecord(value: unknown): CatalogModelRecord {
93
111
  return CatalogModelRecordSchema.parse(value);
94
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
+ }