@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
@@ -18,11 +18,46 @@ export interface EnrichedLiveModel<T> {
18
18
  readonly published?: CatalogIdentityMatch;
19
19
  }
20
20
 
21
+ /**
22
+ * Exact (case-insensitive) then normalized identity lookup; never fuzzy. A normalized key is
23
+ * ambiguous, and resolves to nothing, only when identities of two different records normalize
24
+ * to it; identities of one record that normalize alike keep the first identity's match.
25
+ */
26
+ export class CatalogIdentityIndex {
27
+ private readonly exact = new Map<string, CatalogIdentityMatch>();
28
+ private readonly normalized = new Map<string, CatalogIdentityMatch | null>();
29
+
30
+ constructor(records: Iterable<CatalogModelRecord>) {
31
+ for (const record of records) {
32
+ for (const identity of modelIdentities(record)) {
33
+ this.exact.set(identity.value.toLowerCase(), { identity, record });
34
+ const key = normalizeModelIdentity(identity.value);
35
+ const current = this.normalized.get(key);
36
+ if (current === undefined) this.normalized.set(key, { identity, record });
37
+ else if (current !== null && current.record.id !== record.id) this.normalized.set(key, null);
38
+ }
39
+ }
40
+ }
41
+
42
+ resolve(value: string): CatalogIdentityMatch | undefined {
43
+ const exact = this.exact.get(value.trim().toLowerCase());
44
+ if (exact) return exact;
45
+ return this.normalized.get(normalizeModelIdentity(value)) ?? undefined;
46
+ }
47
+
48
+ matchAny(values: readonly string[]): CatalogIdentityMatch | undefined {
49
+ for (const value of values) {
50
+ const match = this.resolve(value);
51
+ if (match) return match;
52
+ }
53
+ return undefined;
54
+ }
55
+ }
56
+
21
57
  /** Immutable identity and search index over one catalog snapshot. */
22
58
  export class ModelCatalogIndex {
23
59
  readonly records: readonly CatalogModelRecord[];
24
- private readonly exact = new Map<string, CatalogIdentityMatch>();
25
- private readonly normalized = new Map<string, CatalogIdentityMatch | null>();
60
+ private readonly identities: CatalogIdentityIndex;
26
61
 
27
62
  constructor(
28
63
  readonly catalog: ModelCatalog,
@@ -36,15 +71,8 @@ export class ModelCatalogIndex {
36
71
  if (catalog.updated_at !== searchIndex.updated_at) {
37
72
  throw new Error("Catalog and search index timestamps do not match");
38
73
  }
39
- this.records = Object.entries(catalog.models).map(([id, model]) => ({ ...model, id }));
40
- for (const record of this.records) {
41
- for (const identity of modelIdentities(record)) {
42
- this.exact.set(identity.value.toLowerCase(), { identity, record });
43
- const key = normalizeModelIdentity(identity.value);
44
- const current = this.normalized.get(key);
45
- this.normalized.set(key, current === undefined ? { identity, record } : null);
46
- }
47
- }
74
+ this.records = catalogRecords(catalog);
75
+ this.identities = new CatalogIdentityIndex(this.records);
48
76
  }
49
77
 
50
78
  get(id: string): CatalogModelRecord | undefined {
@@ -52,17 +80,11 @@ export class ModelCatalogIndex {
52
80
  }
53
81
 
54
82
  resolve(value: string): CatalogIdentityMatch | undefined {
55
- const exact = this.exact.get(value.trim().toLowerCase());
56
- if (exact) return exact;
57
- return this.normalized.get(normalizeModelIdentity(value)) ?? undefined;
83
+ return this.identities.resolve(value);
58
84
  }
59
85
 
60
86
  matchAny(values: readonly string[]): CatalogIdentityMatch | undefined {
61
- for (const value of values) {
62
- const match = this.resolve(value);
63
- if (match) return match;
64
- }
65
- return undefined;
87
+ return this.identities.matchAny(values);
66
88
  }
67
89
 
68
90
  list(filters: CatalogFilters = {}): CatalogModelRecord[] {
@@ -74,6 +96,11 @@ export class ModelCatalogIndex {
74
96
  }
75
97
  }
76
98
 
99
+ /** Catalog records with their map keys as ids, in catalog order. */
100
+ export function catalogRecords(catalog: ModelCatalog): CatalogModelRecord[] {
101
+ return Object.entries(catalog.models).map(([id, model]) => ({ ...model, id }));
102
+ }
103
+
77
104
  export function createModelCatalogIndex(
78
105
  catalog: ModelCatalog,
79
106
  searchIndex: CatalogSearchIndexPayload,
package/src/cli.ts CHANGED
@@ -1,9 +1,6 @@
1
1
  #!/usr/bin/env bun
2
2
 
3
- import type {
4
- CatalogFilters,
5
- } from './browser.js';
6
- import { connectModelCatalog } from './index.js';
3
+ import { type CatalogFilters, createModelCatalogClient } from './index.js';
7
4
 
8
5
  type Command = 'catalog' | 'models' | 'model-feed';
9
6
 
@@ -26,10 +23,10 @@ function parseArgs(args: string[]): CliOptions {
26
23
  const command = args.shift();
27
24
  if (command === undefined || command === '--help' || command === '-h') {
28
25
  throw new Error(
29
- 'Usage: bun run chanx-model-catalog <catalog|models|model-feed> [query] '
26
+ 'Usage: bun run dbx-model-catalog <catalog|models|model-feed> [query] '
30
27
  + '[--status VALUE] [--type VALUE] [--publisher VALUE] [--task VALUE] '
31
28
  + '[--capability VALUE] [--limit NUMBER] '
32
- + '[--url https://HOST/catalog.json]',
29
+ + '[--url https://HOST/catalog.json | ws://HOST:PORT | PATH/catalog.json]',
33
30
  );
34
31
  }
35
32
  if (!['catalog', 'models', 'model-feed'].includes(command)) {
@@ -82,15 +79,15 @@ function numberOption(values: Map<string, string[]>, name: string): number | und
82
79
 
83
80
  async function main(): Promise<void> {
84
81
  const options = parseArgs(process.argv.slice(2));
85
- await using session = await connectModelCatalog(options.url);
86
- process.stderr.write(`Using ${session.mode} catalog ${session.source}\n`);
82
+ await using client = await createModelCatalogClient(options.url);
83
+ process.stderr.write(`Using ${client.source.kind} catalog ${client.source.location ?? ''}\n`);
87
84
 
88
85
  if (options.command === 'catalog') {
89
- process.stdout.write(`${JSON.stringify(await session.client.catalog())}\n`);
86
+ process.stdout.write(`${JSON.stringify(await client.catalog())}\n`);
90
87
  } else if (options.command === 'models') {
91
- process.stdout.write(`${JSON.stringify(await session.client.list(options.filters), null, 2)}\n`);
88
+ process.stdout.write(`${JSON.stringify(await client.list(options.filters), null, 2)}\n`);
92
89
  } else {
93
- for await (const model of session.client.stream(options.filters)) {
90
+ for await (const model of client.stream(options.filters)) {
94
91
  process.stdout.write(`${JSON.stringify(model)}\n`);
95
92
  }
96
93
  }
@@ -0,0 +1,200 @@
1
+ import type {
2
+ CatalogModel,
3
+ CatalogSearchIndexDocument,
4
+ CatalogSearchIndexPayload,
5
+ EffectiveEndpoint,
6
+ EffectiveModelCatalog,
7
+ FieldOrigin,
8
+ MatchedPublicIdentity,
9
+ ModelCatalog,
10
+ WorkspaceRefresh,
11
+ } from "./_generated/schemas.js";
12
+ import { WORKSPACE_OVERLAY_RULES } from "./_generated/workspace-rules.js";
13
+ import { CatalogIdentityIndex, catalogRecords } from "./catalog-index.js";
14
+ import { catalogSearchDocument, catalogSearchQuality, type CatalogSearchQuality } from "./search.js";
15
+ import { compareCodePoints, type WorkspaceEndpoint } from "./serving-endpoints.js";
16
+ import { CatalogModelSchema } from "./validation.js";
17
+
18
+ /** Version of the effective-catalog contract; part of every workspace cache key. */
19
+ export const EFFECTIVE_CATALOG_CONTRACT_VERSION: number = WORKSPACE_OVERLAY_RULES.contract_version;
20
+
21
+ const RULES = WORKSPACE_OVERLAY_RULES;
22
+ type Json = Record<string, unknown>;
23
+
24
+ /**
25
+ * Merge normalized endpoints over `publicCatalog` with live-over-public precedence, following
26
+ * the Python reference (`build_effective_catalog`) and the shared `WORKSPACE_OVERLAY_RULES`:
27
+ *
28
+ * - A repeated endpoint name keeps its first entry.
29
+ * - An endpoint matches the first identity candidate the public index resolves exactly
30
+ * (case-insensitive) or by normalized identity; never fuzzy.
31
+ * - Each overlay field the endpoint supplies replaces the public value (origin `workspace`) and
32
+ * drops `sources[target]`; omitted fields keep the public value and sources (origin `public`).
33
+ * Unmatched endpoints start from schema-required placeholders (origin `placeholder`).
34
+ * - An unmatched endpoint whose task maps to no type gets no record or search document: it is
35
+ * listed in `endpoints` only, with no field origins, because any type would be invented.
36
+ * - The record id is the endpoint name. Public order is kept, an endpoint named like a public id
37
+ * replaces it in place, and other endpoint records follow sorted by name.
38
+ * - Endpoint identities other than the name become aliases only when the public index does not
39
+ * resolve them and no public record or earlier endpoint already claims them.
40
+ */
41
+ export function buildEffectiveCatalog(
42
+ publicCatalog: ModelCatalog,
43
+ endpoints: Iterable<WorkspaceEndpoint> = [],
44
+ workspace: WorkspaceRefresh = { status: "disabled" },
45
+ ): EffectiveModelCatalog {
46
+ const index = new CatalogIdentityIndex(catalogRecords(publicCatalog));
47
+ const unique = new Map<string, WorkspaceEndpoint>();
48
+ for (const endpoint of endpoints) if (!unique.has(endpoint.name)) unique.set(endpoint.name, endpoint);
49
+ const claimed = new Set<string>([
50
+ ...Object.entries(publicCatalog.models).flatMap(([id, model]) => [id, ...model.aliases]),
51
+ ...unique.keys(),
52
+ ].map(value => value.toLowerCase()));
53
+
54
+ const overlays: Record<string, EffectiveEndpoint> = {};
55
+ const endpointModels = new Map<string, CatalogModel>();
56
+ for (const name of [...unique.keys()].sort(compareCodePoints)) {
57
+ const endpoint = unique.get(name)!;
58
+ const match = matchEndpoint(endpoint, index);
59
+ if (!match && endpoint.type == null) {
60
+ overlays[name] = { ...structuredClone(endpoint), fields: {} };
61
+ continue;
62
+ }
63
+ const matched = match ? publicCatalog.models[match.id] : undefined;
64
+ const { data, fields } = overlay(endpoint, matched);
65
+ const extra: string[] = [];
66
+ for (const candidate of endpoint.identities) {
67
+ const key = candidate.value.toLowerCase();
68
+ if (candidate.value !== name && !claimed.has(key) && !index.resolve(candidate.value)) {
69
+ claimed.add(key);
70
+ extra.push(candidate.value);
71
+ }
72
+ }
73
+ data.aliases = [...(match?.id === name ? (data.aliases as string[]) : []), ...extra];
74
+ endpointModels.set(name, CatalogModelSchema.parse(data));
75
+ overlays[name] = { ...structuredClone(endpoint), ...(match ? { match } : {}), fields };
76
+ }
77
+
78
+ if (!endpointModels.size) {
79
+ return { contract_version: EFFECTIVE_CATALOG_CONTRACT_VERSION, catalog: publicCatalog, workspace: refreshState(workspace), endpoints: overlays };
80
+ }
81
+ const models: Record<string, CatalogModel> = {};
82
+ for (const [id, model] of Object.entries(publicCatalog.models)) models[id] = endpointModels.get(id) ?? model;
83
+ for (const name of [...endpointModels.keys()].sort(compareCodePoints)) models[name] ??= endpointModels.get(name)!;
84
+ return {
85
+ contract_version: EFFECTIVE_CATALOG_CONTRACT_VERSION,
86
+ catalog: { schema_version: publicCatalog.schema_version, updated_at: publicCatalog.updated_at, models },
87
+ workspace: refreshState(workspace),
88
+ endpoints: overlays,
89
+ };
90
+ }
91
+
92
+ /** True when the workspace listed `id` as an invocable endpoint. */
93
+ export function isEffectiveModelAccessible(effective: EffectiveModelCatalog, id: string): boolean {
94
+ return Object.hasOwn(effective.endpoints, id);
95
+ }
96
+
97
+ /**
98
+ * Search documents for every effective record. Text fields come from the effective record;
99
+ * quality comes from the public search index: an unchanged public record reuses its own document,
100
+ * an endpoint record inherits its matched public record's quality, and an unmatched endpoint uses
101
+ * `runtime_search_quality`.
102
+ */
103
+ export function buildEffectiveSearchIndex(
104
+ effective: EffectiveModelCatalog,
105
+ publicIndex: CatalogSearchIndexPayload,
106
+ ): CatalogSearchIndexPayload {
107
+ const publicDocuments = new Map(publicIndex.documents.map(document => [document.id, document]));
108
+ const runtime = catalogSearchQuality(RULES.runtime_search_quality, publicIndex.weights);
109
+ const documents: CatalogSearchIndexDocument[] = catalogRecords(effective.catalog).map(record => {
110
+ const endpoint = effective.endpoints[record.id];
111
+ const own = endpoint ? undefined : publicDocuments.get(record.id);
112
+ if (own) return own;
113
+ const source = endpoint?.match ? publicDocuments.get(endpoint.match.id) : undefined;
114
+ const quality: CatalogSearchQuality = source ?? runtime;
115
+ return catalogSearchDocument(record, quality);
116
+ });
117
+ return {
118
+ schema_version: publicIndex.schema_version,
119
+ catalog_schema_version: effective.catalog.schema_version,
120
+ updated_at: effective.catalog.updated_at,
121
+ weights: publicIndex.weights,
122
+ documents,
123
+ };
124
+ }
125
+
126
+ function refreshState(workspace: WorkspaceRefresh): WorkspaceRefresh {
127
+ return { persistent: false, ...workspace };
128
+ }
129
+
130
+ function matchEndpoint(endpoint: WorkspaceEndpoint, index: CatalogIdentityIndex): MatchedPublicIdentity | undefined {
131
+ for (const candidate of endpoint.identities) {
132
+ const resolved = index.resolve(candidate.value);
133
+ if (resolved) return { id: resolved.record.id, kind: candidate.kind, value: candidate.value };
134
+ }
135
+ return undefined;
136
+ }
137
+
138
+ function overlay(
139
+ endpoint: WorkspaceEndpoint,
140
+ matched: CatalogModel | undefined,
141
+ ): { data: Json; fields: Record<string, FieldOrigin> } {
142
+ const fields: Record<string, FieldOrigin> = {};
143
+ let data: Json;
144
+ if (matched) {
145
+ data = structuredClone(matched) as unknown as Json;
146
+ } else {
147
+ data = {
148
+ name: endpoint.name,
149
+ aliases: [],
150
+ capabilities: {},
151
+ tasks: [],
152
+ use_cases: [],
153
+ availability: {},
154
+ price: {},
155
+ average_price: {},
156
+ sources: {},
157
+ notices: [],
158
+ rankings: [],
159
+ benchmarks: [],
160
+ };
161
+ fields.name = "workspace";
162
+ for (const [target, value] of Object.entries(RULES.placeholders)) {
163
+ setPath(data, target, structuredClone(value));
164
+ fields[target] = "placeholder";
165
+ }
166
+ }
167
+ const sources = data.sources as Json;
168
+ for (const rule of RULES.overlay_fields) {
169
+ if ("unmatched_only" in rule && rule.unmatched_only && matched) continue;
170
+ const value = getPath(endpoint, rule.source);
171
+ if (value != null) {
172
+ setPath(data, rule.target, structuredClone(value));
173
+ delete sources[rule.target];
174
+ fields[rule.target] = "workspace";
175
+ } else if (matched && getPath(data, rule.target) != null) {
176
+ fields[rule.target] = "public";
177
+ }
178
+ }
179
+ return {
180
+ data,
181
+ fields: Object.fromEntries(Object.entries(fields).sort(([left], [right]) => compareCodePoints(left, right))),
182
+ };
183
+ }
184
+
185
+ function getPath(data: unknown, path: string): unknown {
186
+ let node = data;
187
+ for (const part of path.split(".")) {
188
+ if (typeof node !== "object" || node === null || Array.isArray(node)) return undefined;
189
+ node = (node as Json)[part];
190
+ }
191
+ return node;
192
+ }
193
+
194
+ function setPath(data: Json, path: string, value: unknown): void {
195
+ const parts = path.split(".");
196
+ const leaf = parts.pop()!;
197
+ let node = data;
198
+ for (const part of parts) node = (node[part] ??= {}) as Json;
199
+ node[leaf] = value;
200
+ }
package/src/identity.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { CatalogModelRecord } from "./_generated/schemas.js";
2
+ import { WORKSPACE_OVERLAY_RULES } from "./_generated/workspace-rules.js";
2
3
 
3
4
  export type ModelIdentityKind = "endpoint" | "model-service" | "provider" | "alias";
4
5
 
@@ -8,32 +9,8 @@ export interface ModelIdentity {
8
9
  readonly value: string;
9
10
  }
10
11
 
11
- const providerPrefixes = new Set([
12
- "alibaba",
13
- "anthropic",
14
- "deepseek",
15
- "google",
16
- "meta",
17
- "moonshot",
18
- "openai",
19
- "xai",
20
- "zhipu",
21
- ]);
22
-
23
- const providerFamilies = [
24
- "claude",
25
- "deepseek",
26
- "gemini",
27
- "gemma",
28
- "glm",
29
- "gpt",
30
- "grok",
31
- "gte",
32
- "bge",
33
- "kimi",
34
- "llama",
35
- "qwen",
36
- ] as const;
12
+ const providerPrefixes: ReadonlySet<string> = new Set(WORKSPACE_OVERLAY_RULES.provider_prefixes);
13
+ const providerFamilies: readonly string[] = WORKSPACE_OVERLAY_RULES.provider_families;
37
14
 
38
15
  /** Normalize endpoint, system-service, and provider identities for exact joins. */
39
16
  export function normalizeModelIdentity(value: string): string {
package/src/index.ts CHANGED
@@ -1,104 +1,177 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { dirname, resolve } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
- import type { CatalogClient } from "./types.js";
5
- import type { CatalogSearchIndexPayload, ModelCatalog } from "./_generated/schemas.js";
4
+ import type { CatalogSearchIndexPayload } from "./_generated/schemas.js";
5
+ import { type LoadedCatalog, createCatalogClient, workspaceOverlay } from "./local-client.js";
6
6
  import {
7
- PUBLISHED_CATALOG_SEARCH_INDEX_URL,
8
- PUBLISHED_CATALOG_URL,
9
- } from "./_generated/published.js";
10
- import { createModelCatalogClient } from "./local-client.js";
7
+ type CatalogSourceOptions,
8
+ type ModelCatalogSourceInput,
9
+ isHttpUrl,
10
+ isWebSocketUrl,
11
+ loadBrowserSource,
12
+ loadMemory,
13
+ loadPublished,
14
+ } from "./sources.js";
15
+ import type { ModelCatalogClient } from "./types.js";
11
16
  import { parseCatalogSearchIndex, parseModelCatalog } from "./validation.js";
17
+ import { type ModelServingClientOption, connectModelServing } from "./workspace-client.js";
18
+ import { createPersistentWorkspaceCatalogCache } from "./workspace-file-cache.js";
19
+ import type { CachedWorkspaceOverlay, WorkspaceCacheOptions } from "./workspace-overlay.js";
12
20
 
13
- const packageRootUrl = new URL("..", import.meta.url);
14
- const packageRoot = fileURLToPath(packageRootUrl);
21
+ /** Options for the Node `createModelCatalogClient`, which also accepts SDK clients. */
22
+ export interface ModelCatalogClientOptions extends CatalogSourceOptions {
23
+ /**
24
+ * Workspace connection: a `@databricks/sdk-experimental` `WorkspaceClient`, a
25
+ * `@databricks/sdk-modelserving` `ModelServingClient`, a `{ host, headers }` connection, or a sync
26
+ * or async function returning one. Validated before any request.
27
+ */
28
+ modelServingClient?: ModelServingClientOption;
29
+ /** Workspace overlay refresh and cache settings. */
30
+ workspaceCache?: NodeWorkspaceCacheOptions;
31
+ }
15
32
 
16
- export interface ConnectModelCatalogOptions {
17
- catalogPath?: string;
18
- catalogUrl?: string;
19
- fetch?: typeof globalThis.fetch;
20
- searchIndexPath?: string;
21
- searchIndexUrl?: string;
33
+ /**
34
+ * Node workspace cache settings. By default principal-scoped overlays persist to a `keyv-file`
35
+ * store under the user cache directory; `persistent: false` keeps them in process memory.
36
+ */
37
+ export interface NodeWorkspaceCacheOptions extends WorkspaceCacheOptions {
38
+ /** Cache file for the default persistent store. */
39
+ filename?: string;
22
40
  }
23
41
 
24
- export interface ModelCatalogSession extends AsyncDisposable {
25
- readonly client: CatalogClient;
26
- readonly mode: "file" | "published" | "url";
27
- readonly root: string;
28
- readonly source: string;
29
- close(): Promise<void>;
42
+ /**
43
+ * Create a catalog client from any source: the published catalog by default (or the files named by
44
+ * `DBX_MODEL_CATALOG_PATH`), an `http(s)` catalog URL, a `ws(s)` URL of the Python catalog server
45
+ * (needs the optional `pynect` and `@chanx-js/client` peers), a catalog file path or `file:` URL
46
+ * (`search-index.json` beside it), or an in-memory catalog with `options.searchIndex`. With
47
+ * `modelServingClient` every read serves the workspace-effective catalog, whatever the source.
48
+ */
49
+ export async function createModelCatalogClient(
50
+ source?: ModelCatalogSourceInput,
51
+ options: ModelCatalogClientOptions = {},
52
+ ): Promise<ModelCatalogClient> {
53
+ // Validate the optional workspace connection before any request.
54
+ const connector = options.modelServingClient === undefined
55
+ ? undefined
56
+ : connectModelServing(options.modelServingClient, { fetch: options.fetch });
57
+ const loaded = await loadSource(source, options);
58
+ return createCatalogClient(loaded, workspaceOverlay(connector, nodeWorkspaceCache(options.workspaceCache)));
30
59
  }
31
60
 
32
- export async function connectModelCatalog(
33
- input?: string | ConnectModelCatalogOptions,
34
- ): Promise<ModelCatalogSession> {
35
- const options = typeof input === "string" ? { catalogUrl: input } : (input ?? {});
36
- const configuredPath = options.catalogPath ?? process.env.DBX_MODEL_CATALOG_PATH;
37
- const configuredUrl = options.catalogUrl?.trim() || undefined;
38
- if (configuredUrl?.startsWith("ws:") || configuredUrl?.startsWith("wss:")) {
39
- throw new Error("WebSocket connections use @dbx-tools/dbx-model-catalog/pynect");
61
+ function loadSource(source: ModelCatalogSourceInput | undefined, options: CatalogSourceOptions): Promise<LoadedCatalog> {
62
+ if (source === undefined) {
63
+ const configured = process.env.DBX_MODEL_CATALOG_PATH?.trim();
64
+ return configured ? loadFiles(configured, options.searchIndex) : loadPublished(options);
40
65
  }
41
- const loaded = configuredPath
42
- ? await loadFiles(configuredPath, options.searchIndexPath)
43
- : await loadUrls(configuredUrl, options.searchIndexUrl, options.fetch);
44
- const client = createModelCatalogClient(loaded.catalog, loaded.searchIndex);
45
- const close = async (): Promise<void> => {
46
- client.close();
47
- };
48
-
49
- return {
50
- client,
51
- mode: configuredPath ? "file" : configuredUrl ? "url" : "published",
52
- root: packageRoot,
53
- source: loaded.source,
54
- close,
55
- async [Symbol.asyncDispose](): Promise<void> {
56
- await close();
57
- },
58
- };
66
+ if (typeof source !== "string" && !(source instanceof URL)) return Promise.resolve(loadMemory(source, options));
67
+ const location = source.toString();
68
+ if (isHttpUrl(location) || isWebSocketUrl(location)) return loadBrowserSource(location, options);
69
+ return loadFiles(location.startsWith("file:") ? fileURLToPath(location) : location, options.searchIndex);
59
70
  }
60
71
 
61
72
  async function loadFiles(
62
73
  catalogPath: string,
63
- searchIndexPath?: string,
64
- ): Promise<{ catalog: ModelCatalog; searchIndex: CatalogSearchIndexPayload; source: string }> {
65
- const resolvedCatalogPath = resolve(catalogPath);
66
- const resolvedSearchIndexPath = resolve(
67
- searchIndexPath ?? resolve(dirname(resolvedCatalogPath), "search-index.json"),
68
- );
69
- const [catalog, searchIndex] = await Promise.all([
70
- readFile(resolvedCatalogPath, "utf8").then(value => parseModelCatalog(JSON.parse(value))),
71
- readFile(resolvedSearchIndexPath, "utf8").then(value => parseCatalogSearchIndex(JSON.parse(value))),
74
+ searchIndex: CatalogSearchIndexPayload | string | undefined,
75
+ ): Promise<LoadedCatalog> {
76
+ const location = resolve(catalogPath);
77
+ const indexPath = typeof searchIndex === "string" ? resolve(searchIndex) : resolve(dirname(location), "search-index.json");
78
+ const [catalog, index] = await Promise.all([
79
+ readFile(location, "utf8").then(value => parseModelCatalog(JSON.parse(value))),
80
+ typeof searchIndex === "object"
81
+ ? searchIndex
82
+ : readFile(indexPath, "utf8").then(value => parseCatalogSearchIndex(JSON.parse(value))),
72
83
  ]);
73
- return { catalog, searchIndex, source: resolvedCatalogPath };
84
+ return { catalog, searchIndex: index, source: { kind: "file", location } };
74
85
  }
75
86
 
76
- async function loadUrls(
77
- catalogUrl?: string,
78
- searchIndexUrl?: string,
79
- fetcher: typeof globalThis.fetch = globalThis.fetch,
80
- ): Promise<{ catalog: ModelCatalog; searchIndex: CatalogSearchIndexPayload; source: string }> {
81
- const source = catalogUrl ?? PUBLISHED_CATALOG_URL;
82
- const indexSource = searchIndexUrl ?? (
83
- catalogUrl ? new URL("search-index.json", catalogUrl).toString() : PUBLISHED_CATALOG_SEARCH_INDEX_URL
84
- );
85
- const [catalogResponse, searchIndexResponse] = await Promise.all([
86
- fetcher(source),
87
- fetcher(indexSource),
88
- ]);
89
- if (!catalogResponse.ok) throw new Error(`Catalog request failed with ${catalogResponse.status}`);
90
- if (!searchIndexResponse.ok) {
91
- throw new Error(`Search index request failed with ${searchIndexResponse.status}`);
92
- }
87
+ function nodeWorkspaceCache(options: NodeWorkspaceCacheOptions = {}): WorkspaceCacheOptions {
88
+ const { filename, ...cache } = options;
89
+ if (cache.cache !== undefined || cache.store !== undefined || cache.persistent === false) return cache;
93
90
  return {
94
- catalog: parseModelCatalog(await catalogResponse.json()),
95
- searchIndex: parseCatalogSearchIndex(await searchIndexResponse.json()),
96
- source,
91
+ ...cache,
92
+ persistent: true,
93
+ cache: createPersistentWorkspaceCatalogCache<CachedWorkspaceOverlay>({
94
+ ...(cache.refreshAfterMs === undefined ? {} : { refreshAfterMs: cache.refreshAfterMs }),
95
+ ...(cache.staleOnErrorMs === undefined ? {} : { staleOnErrorMs: cache.staleOnErrorMs }),
96
+ ...(cache.now === undefined ? {} : { now: cache.now }),
97
+ ...(filename === undefined ? {} : { filename }),
98
+ }),
97
99
  };
98
100
  }
99
101
 
100
- export type * from "./browser.js";
102
+ export { createPersistentWorkspaceCatalogCache } from "./workspace-file-cache.js";
103
+ export type {
104
+ ModelServingClientOption,
105
+ ModelServingSdkClientLike,
106
+ WorkspaceClientLike,
107
+ WorkspaceClientRequest,
108
+ } from "./workspace-client.js";
109
+ export type {
110
+ Availability,
111
+ AveragePrice,
112
+ Benchmark,
113
+ BrowserModelServingClientOption,
114
+ CachedWorkspaceOverlay,
115
+ Capabilities,
116
+ CatalogFilters,
117
+ CatalogIdentityMatch,
118
+ CatalogModel,
119
+ CatalogModelRecord,
120
+ CatalogSearchIndexDocument,
121
+ CatalogSearchIndexPayload,
122
+ CatalogSearchMatch,
123
+ CatalogSearchQualityScores,
124
+ EffectiveEndpoint,
125
+ EffectiveModelCatalog,
126
+ FieldOrigin,
127
+ IdentityCandidate,
128
+ Latency,
129
+ Limits,
130
+ MatchedPublicIdentity,
131
+ Modalities,
132
+ ModelCatalog,
133
+ ModelCatalogClient,
134
+ ModelCatalogSource,
135
+ ModelCatalogSourceInput,
136
+ ModelCatalogSourceKind,
137
+ ModelIdentity,
138
+ ModelIdentityKind,
139
+ ModelServingConnection,
140
+ ModelServingConnectionGenerator,
141
+ Notice,
142
+ Price,
143
+ Rankings,
144
+ RateLimits,
145
+ Reasoning,
146
+ Retirement,
147
+ SourceLink,
148
+ Status,
149
+ Type,
150
+ WorkspaceCacheOptions,
151
+ WorkspaceCacheStore,
152
+ WorkspaceCatalogCache,
153
+ WorkspaceEndpointCapabilities,
154
+ WorkspaceEndpointSource,
155
+ WorkspaceModelProfile,
156
+ WorkspaceRefresh,
157
+ WorkspaceRefreshStatus,
158
+ } from "./browser.js";
101
159
  export {
160
+ CatalogAveragePriceSchema,
161
+ CatalogCapabilitiesSchema,
162
+ CatalogLatencySchema,
163
+ CatalogModelRecordSchema,
164
+ CatalogModelSchema,
165
+ CatalogPreferenceRankingSchema,
166
+ CatalogPriceSchema,
167
+ CatalogRankingSchema,
168
+ CatalogRateLimitsSchema,
169
+ CatalogScoreRankingSchema,
170
+ CatalogSearchIndexSchema,
171
+ CatalogStatusSchema,
172
+ EFFECTIVE_CATALOG_CONTRACT_VERSION,
173
+ EffectiveModelCatalogSchema,
174
+ ModelCatalogSchema,
102
175
  PUBLISHED_CATALOG_DATABASE_URL,
103
176
  PUBLISHED_CATALOG_INDEX_URL,
104
177
  PUBLISHED_CATALOG_ROOT_URL,
@@ -106,9 +179,9 @@ export {
106
179
  PUBLISHED_CATALOG_SCHEMA_VERSION,
107
180
  PUBLISHED_CATALOG_SEARCH_INDEX_URL,
108
181
  PUBLISHED_CATALOG_URL,
109
- createModelCatalogClient,
110
- filterCatalogRecords,
111
- loadModelCatalog,
112
- loadModelCatalogIndex,
113
- searchCatalogRecords,
182
+ WorkspaceRefreshSchema,
183
+ parseCatalogModelRecord,
184
+ parseCatalogSearchIndex,
185
+ parseEffectiveModelCatalog,
186
+ parseModelCatalog,
114
187
  } from "./browser.js";