@littlebigbrain/client 0.1.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/dist/client.js ADDED
@@ -0,0 +1,878 @@
1
+ /**
2
+ * Parse a {@link Schemas.SparqlTextResponse} (whose `results` field carries the
3
+ * SPARQL Results document as a JSON *string*) into typed bindings plus flat
4
+ * `{ variable: lexicalValue }` rows — the form most callers want, so they never
5
+ * have to `JSON.parse` and zip `head.vars` with binding values by hand.
6
+ */
7
+ export function parseSparqlResults(response) {
8
+ const doc = JSON.parse(response.results);
9
+ const vars = doc.head?.vars ?? [];
10
+ if (typeof doc.boolean === "boolean") {
11
+ return { vars, boolean: doc.boolean, bindings: [], rows: [] };
12
+ }
13
+ const bindings = doc.results?.bindings ?? [];
14
+ const rows = bindings.map((binding) => Object.fromEntries(Object.entries(binding).map(([name, term]) => [name, term.value])));
15
+ return { vars, boolean: null, bindings, rows };
16
+ }
17
+ function firstPatternVariable(patterns) {
18
+ for (const pattern of patterns) {
19
+ if ("var" in pattern.subject)
20
+ return pattern.subject.var;
21
+ if ("var" in pattern.object)
22
+ return pattern.object.var;
23
+ }
24
+ return "entity";
25
+ }
26
+ function attributeFilterValue(value) {
27
+ if (typeof value === "boolean")
28
+ return { bool: value };
29
+ if (typeof value === "number")
30
+ return Number.isInteger(value) ? { i64: value } : { f64: value };
31
+ if (typeof value === "string")
32
+ return { str: value };
33
+ if ("dateTime" in value)
34
+ return { date_time: value.dateTime };
35
+ return { entity: value.entity };
36
+ }
37
+ function attributeFilter(filter, defaultVar) {
38
+ return {
39
+ compare: {
40
+ op: filter.op ?? "eq",
41
+ left: { property: { var: filter.var ?? defaultVar, field: filter.field } },
42
+ right: { value: attributeFilterValue(filter.value) },
43
+ },
44
+ };
45
+ }
46
+ /** Thrown when the server responds with a non-2xx status. */
47
+ export class LbbError extends Error {
48
+ status;
49
+ body;
50
+ error;
51
+ type;
52
+ code;
53
+ param;
54
+ requestId;
55
+ docUrl;
56
+ constructor(status, body, error) {
57
+ super(error?.message ?? `Little Big Brain ${status}: ${body}`);
58
+ this.status = status;
59
+ this.body = body;
60
+ this.error = error;
61
+ this.name = "LbbError";
62
+ this.type = error?.type;
63
+ this.code = error?.code;
64
+ this.param = error?.param;
65
+ this.requestId = error?.request_id;
66
+ this.docUrl = error?.doc_url;
67
+ }
68
+ }
69
+ function sleep(ms) {
70
+ if (ms <= 0)
71
+ return Promise.resolve();
72
+ const timer = globalThis
73
+ .setTimeout;
74
+ return new Promise((resolve) => {
75
+ if (timer) {
76
+ timer(resolve, ms);
77
+ }
78
+ else {
79
+ resolve();
80
+ }
81
+ });
82
+ }
83
+ function retryableStatus(status) {
84
+ return status === 429 || status >= 500;
85
+ }
86
+ function retryAllowed(method, idempotencyKey) {
87
+ const upper = method.toUpperCase();
88
+ return upper === "GET" || upper === "HEAD" || upper === "OPTIONS" || idempotencyKey !== undefined;
89
+ }
90
+ function parseLbbError(status, body, fallbackRequestId) {
91
+ try {
92
+ const parsed = JSON.parse(body);
93
+ if (parsed.error) {
94
+ return new LbbError(status, body, {
95
+ ...parsed.error,
96
+ request_id: parsed.error.request_id ?? fallbackRequestId ?? null,
97
+ });
98
+ }
99
+ }
100
+ catch {
101
+ // Fall through to an unstructured error.
102
+ }
103
+ return new LbbError(status, body, {
104
+ type: "api_error",
105
+ code: "unstructured_error",
106
+ message: body || `Little Big Brain ${status}`,
107
+ request_id: fallbackRequestId ?? null,
108
+ });
109
+ }
110
+ /**
111
+ * A typed HTTP client for a Little Big Brain graph server. One instance is scoped to a
112
+ * single graph/branch; construct another for a different scope. All methods
113
+ * return the parsed JSON response and throw {@link LbbError} on failure.
114
+ */
115
+ export class LbbClient {
116
+ baseUrl;
117
+ apiKey;
118
+ graphName;
119
+ branchName;
120
+ stack;
121
+ fetchImpl;
122
+ apiVersion;
123
+ maxRetries;
124
+ retryDelayMs;
125
+ search;
126
+ indexes;
127
+ entities;
128
+ schema;
129
+ constructor(options) {
130
+ this.baseUrl = options.baseUrl.replace(/\/+$/, "");
131
+ this.apiKey = options.apiKey;
132
+ this.graphName = options.graph;
133
+ this.branchName = options.branch;
134
+ this.stack = options.stack;
135
+ this.apiVersion = options.apiVersion ?? "2026-06-22";
136
+ this.maxRetries = options.maxRetries ?? 2;
137
+ this.retryDelayMs = options.retryDelayMs ?? 100;
138
+ const fallback = globalThis.fetch;
139
+ const chosen = options.fetch ?? (fallback ? fallback.bind(globalThis) : undefined);
140
+ if (!chosen) {
141
+ throw new Error("no fetch implementation available; pass options.fetch");
142
+ }
143
+ this.fetchImpl = chosen;
144
+ this.search = new SearchNamespace(this);
145
+ this.indexes = new IndexNamespace(this);
146
+ this.entities = new EntityNamespace(this);
147
+ this.schema = new SchemaNamespace(this);
148
+ }
149
+ graph(name, opts = {}) {
150
+ return new GraphNamespace(this.withScope({
151
+ graph: name,
152
+ branch: opts.branch ?? this.branchName,
153
+ stack: opts.stack ?? this.stack,
154
+ }));
155
+ }
156
+ /**
157
+ * A new client for a different graph/branch on the same server and credential.
158
+ * Each instance is scoped to one graph/branch, so use this to target another
159
+ * scope (e.g. creating a fresh graph) without mutating the current client.
160
+ */
161
+ withScope(scope) {
162
+ return new LbbClient({
163
+ baseUrl: this.baseUrl,
164
+ apiKey: this.apiKey,
165
+ graph: scope.graph ?? this.graphName,
166
+ branch: scope.branch ?? this.branchName,
167
+ stack: scope.stack ?? this.stack,
168
+ fetch: this.fetchImpl,
169
+ apiVersion: this.apiVersion,
170
+ maxRetries: this.maxRetries,
171
+ retryDelayMs: this.retryDelayMs,
172
+ });
173
+ }
174
+ buildUrl(path, query) {
175
+ const params = [];
176
+ const push = (key, value) => params.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
177
+ if (this.graphName !== undefined)
178
+ push("graph", this.graphName);
179
+ if (this.branchName !== undefined)
180
+ push("branch", this.branchName);
181
+ if (this.stack !== undefined)
182
+ push("stack", this.stack);
183
+ for (const [key, value] of Object.entries(query ?? {})) {
184
+ if (value !== undefined)
185
+ push(key, value);
186
+ }
187
+ const qs = params.length > 0 ? `?${params.join("&")}` : "";
188
+ return `${this.baseUrl}${path}${qs}`;
189
+ }
190
+ async rawRequest(method, path, opts = {}) {
191
+ const headers = {
192
+ "content-type": opts.contentType ?? "application/json",
193
+ "lbb-version": this.apiVersion,
194
+ };
195
+ if (this.apiKey !== undefined)
196
+ headers["authorization"] = `Bearer ${this.apiKey}`;
197
+ if (opts.idempotencyKey !== undefined)
198
+ headers["idempotency-key"] = opts.idempotencyKey;
199
+ const canRetry = retryAllowed(method, opts.idempotencyKey);
200
+ const body = opts.rawBody !== undefined
201
+ ? opts.rawBody
202
+ : opts.body !== undefined
203
+ ? JSON.stringify(opts.body)
204
+ : undefined;
205
+ const init = {
206
+ method,
207
+ headers,
208
+ body,
209
+ };
210
+ let response;
211
+ let text = "";
212
+ for (let attempt = 0; attempt <= this.maxRetries; attempt += 1) {
213
+ try {
214
+ response = await this.fetchImpl(this.buildUrl(path, opts.query), init);
215
+ text = await response.text();
216
+ }
217
+ catch (error) {
218
+ if (canRetry && attempt < this.maxRetries) {
219
+ await sleep(this.retryDelayMs * (attempt + 1));
220
+ continue;
221
+ }
222
+ throw error;
223
+ }
224
+ if (response.ok || !retryableStatus(response.status) || attempt === this.maxRetries) {
225
+ break;
226
+ }
227
+ if (!canRetry) {
228
+ break;
229
+ }
230
+ await sleep(this.retryDelayMs * (attempt + 1));
231
+ }
232
+ if (response === undefined)
233
+ throw new Error("request did not produce a response");
234
+ const requestId = response.headers?.get("x-request-id") ?? undefined;
235
+ const version = response.headers?.get("lbb-version") ?? undefined;
236
+ if (!response.ok)
237
+ throw parseLbbError(response.status, text.trim(), requestId);
238
+ return {
239
+ data: (text ? JSON.parse(text) : undefined),
240
+ status: response.status,
241
+ requestId,
242
+ version,
243
+ headers: response.headers,
244
+ };
245
+ }
246
+ async request(method, path, opts = {}) {
247
+ const response = await this.rawRequest(method, path, opts);
248
+ return response.data;
249
+ }
250
+ mutationKey(prefix) {
251
+ const random = Math.random().toString(36).slice(2);
252
+ return `${prefix}:${Date.now()}:${random}`;
253
+ }
254
+ idempotencyKey(prefix = "request") {
255
+ return this.mutationKey(prefix);
256
+ }
257
+ // --- writes ---
258
+ /** Commit triplets and optional entity embeddings. Prefer `client.graph("main").facts.create(...)`. */
259
+ commit(body, opts = {}) {
260
+ return this.request("POST", "/v1/graph/commit", {
261
+ body,
262
+ idempotencyKey: opts.idempotencyKey ?? this.idempotencyKey("facts.create"),
263
+ });
264
+ }
265
+ /**
266
+ * Validate-only preflight: run the same ontology/schema validation a real
267
+ * commit would and report the would-be effect (`op_count`, `written_properties`,
268
+ * `schema_validation`) without writing. A rejected request fails exactly as a
269
+ * real commit would, so this is a safe check before mutating. No idempotency
270
+ * key needed — nothing is persisted.
271
+ */
272
+ commitDryRun(body) {
273
+ return this.request("POST", "/v1/graph/commit", {
274
+ body,
275
+ query: { dry_run: true },
276
+ });
277
+ }
278
+ /**
279
+ * Bulk-ingest a dataset as NDJSON. Each line is either a triplet or an
280
+ * `{type,name,properties}` entity-properties record; lines are batched into
281
+ * bounded internal commits server-side, so a whole dataset loads in one
282
+ * streamed request without a single oversized commit. Pass `lines` as an array
283
+ * (serialized to NDJSON here) or a pre-built NDJSON string.
284
+ */
285
+ import(lines, opts = {}) {
286
+ const ndjson = typeof lines === "string"
287
+ ? lines
288
+ : lines.map((line) => JSON.stringify(line)).join("\n");
289
+ return this.request("POST", "/v1/graph/import", {
290
+ rawBody: ndjson,
291
+ contentType: "application/x-ndjson",
292
+ query: { batch: opts.batch, strict: opts.strict, observed_at: opts.observedAt },
293
+ idempotencyKey: opts.idempotencyKey,
294
+ });
295
+ }
296
+ /**
297
+ * Bulk-ingest N-Triples without client-side conversion. Resource-object
298
+ * triples become keyed Resource edges; literal-object triples become text
299
+ * properties on the subject Resource.
300
+ */
301
+ importRdf(ntriples, opts = {}) {
302
+ return this.request("POST", "/v1/graph/import/rdf", {
303
+ rawBody: ntriples,
304
+ contentType: "application/n-triples",
305
+ query: {
306
+ batch: opts.batch,
307
+ strict: opts.strict,
308
+ observed_at: opts.observedAt,
309
+ format: "ntriples",
310
+ resource_type: opts.resourceType,
311
+ edge_idempotency: opts.edgeIdempotency,
312
+ },
313
+ idempotencyKey: opts.idempotencyKey,
314
+ });
315
+ }
316
+ /**
317
+ * Retract specific edges and/or every edge touching given entities. Appends
318
+ * superseding retract events rather than deleting — history stays visible in an
319
+ * `as_of` read before the retraction, but the edges drop out of current state.
320
+ * The surgical alternative to {@link deleteGraph}.
321
+ */
322
+ retract(body, opts = {}) {
323
+ return this.request("POST", "/v1/graph/retract", {
324
+ body,
325
+ idempotencyKey: opts.idempotencyKey ?? this.idempotencyKey("retract"),
326
+ });
327
+ }
328
+ /** Create the scoped graph/branch. Construct the client with the desired graph/branch first. */
329
+ createGraph() {
330
+ return this.request("POST", "/v1/graph/create");
331
+ }
332
+ /** Fork the scoped branch from an existing branch in the same graph. */
333
+ createBranch(body) {
334
+ return this.request("POST", "/v1/graph/branch", { body });
335
+ }
336
+ /**
337
+ * Delete every object under the scoped graph/branch — a destructive reset.
338
+ * `confirm` must equal the scoped graph id; the next commit re-initializes the
339
+ * graph. Branch-scoped: sibling branches are untouched.
340
+ */
341
+ deleteGraph(opts) {
342
+ return this.request("POST", "/v1/graph/delete", { query: { confirm: opts.confirm } });
343
+ }
344
+ // --- search ---
345
+ /** Full semantic hybrid search from a request body (`POST /v1/graph/search`). */
346
+ graphSearch(body) {
347
+ return this.request("POST", "/v1/graph/search", { body });
348
+ }
349
+ /** Reciprocal-rank-fusion across sub-queries. */
350
+ multiSearch(body) {
351
+ return this.request("POST", "/v1/search/multi", { body });
352
+ }
353
+ /**
354
+ * Append relevance labels for a set of search results — how Little Big Brain
355
+ * gathers customer-specific qrels. Grade results (3 ideal/good, 1 partial,
356
+ * 0 bad), referencing the search response's `search_id` so labels tie back to
357
+ * that ranking. Stored apart from customer facts and exported via
358
+ * {@link searchFeedbackExport} as training/eval data for embedding fine-tuning.
359
+ */
360
+ searchFeedback(body, opts = {}) {
361
+ return this.request("POST", "/v1/search/feedback", {
362
+ body,
363
+ idempotencyKey: opts.idempotencyKey,
364
+ });
365
+ }
366
+ /** Export the stored relevance labels as qrels-style rows for training. */
367
+ searchFeedbackExport() {
368
+ return this.request("GET", "/v1/search/feedback/export");
369
+ }
370
+ /** BM25 search. */
371
+ fullTextSearch(body) {
372
+ return this.request("POST", "/v1/search/full-text", { body });
373
+ }
374
+ /** ANN/vector search. */
375
+ embeddingSearch(body) {
376
+ return this.request("POST", "/v1/search/embedding", { body });
377
+ }
378
+ // --- traversal ---
379
+ /** Bounded k-hop graph traversal. */
380
+ traverse(body) {
381
+ return this.request("POST", "/v1/graph/traverse", { body });
382
+ }
383
+ /** Resolve a query to seed entities, then return bounded paths. */
384
+ semanticTraverse(body) {
385
+ return this.request("POST", "/v1/graph/semantic-traverse", { body });
386
+ }
387
+ /** Ranked incoming/outgoing neighborhood for a graph entity. */
388
+ entityNeighborhood(opts) {
389
+ return this.request("GET", "/v1/graph/entity/neighborhood", {
390
+ query: {
391
+ id: opts.id,
392
+ type: opts.type,
393
+ name: opts.name,
394
+ relations: opts.relations?.join(","),
395
+ as_of: opts.asOf,
396
+ },
397
+ });
398
+ }
399
+ /** Stored entity object-ref status and index-coverage metadata (no
400
+ * attributes — read those from `entityDetail`'s top-level `attributes`). */
401
+ entityMetadata(opts) {
402
+ return this.request("GET", "/v1/graph/entity/metadata", {
403
+ query: {
404
+ id: opts.id,
405
+ type: opts.type,
406
+ name: opts.name,
407
+ as_of: opts.asOf,
408
+ },
409
+ });
410
+ }
411
+ /**
412
+ * Entity detail: metadata, attributes, current state, edge history, and
413
+ * observations. Pass `asOf` / `asOfCommitSeq` to reproduce the node as of a
414
+ * past instant / commit (the state, edges, and history are pinned to it).
415
+ */
416
+ entityDetail(opts) {
417
+ return this.request("GET", "/v1/graph/entity", {
418
+ query: {
419
+ id: opts.id,
420
+ type: opts.type,
421
+ name: opts.name,
422
+ as_of: opts.asOf,
423
+ as_of_commit_seq: opts.asOfCommitSeq,
424
+ },
425
+ });
426
+ }
427
+ /**
428
+ * Paged edge listing. Scope to one node with `id` (or `type`+`name`) and a
429
+ * `direction` (`out`/`in`/`both`) to walk **every** edge of a high-degree node
430
+ * — `entityDetail` returns the full set but is awkward to page; this carries
431
+ * `offset`/`limit` and reports `total_count`. Optional `relation`/`q` filters
432
+ * and an `asOf`/`asOfCommitSeq` snapshot pin. Each row carries `valid_time`, so
433
+ * the page is enough to reconstruct a per-edge timeline.
434
+ */
435
+ graphEdges(opts = {}) {
436
+ return this.request("GET", "/v1/graph/edges", {
437
+ query: {
438
+ id: opts.id,
439
+ type: opts.type,
440
+ name: opts.name,
441
+ direction: opts.direction,
442
+ relation: opts.relation,
443
+ q: opts.q,
444
+ limit: opts.limit,
445
+ cursor: opts.cursor,
446
+ offset: opts.offset,
447
+ as_of: opts.asOf,
448
+ as_of_commit_seq: opts.asOfCommitSeq,
449
+ },
450
+ });
451
+ }
452
+ /**
453
+ * Page through every row of a list endpoint, following `next_cursor` until
454
+ * exhausted. Pass a fetcher that takes a cursor and returns a
455
+ * {@link ListResponse}:
456
+ * ```ts
457
+ * for await (const e of client.listAll((cursor) =>
458
+ * client.entities.list({ cursor, fields: "title" }))) { … }
459
+ * ```
460
+ */
461
+ async *listAll(fetchPage) {
462
+ let cursor;
463
+ for (;;) {
464
+ const page = await fetchPage(cursor);
465
+ for (const row of page.data)
466
+ yield row;
467
+ if (!page.has_more || page.next_cursor == null)
468
+ return;
469
+ cursor = page.next_cursor;
470
+ }
471
+ }
472
+ // --- temporal / lineage / shapes ---
473
+ /** Current state of an entity's relations, optionally as-of a timestamp. */
474
+ currentState(body) {
475
+ return this.request("POST", "/v1/query/state", { body });
476
+ }
477
+ /** Full edge-event history for a relationship. */
478
+ history(body) {
479
+ return this.request("POST", "/v1/query/history", { body });
480
+ }
481
+ /** Ordered state-transition log for an entity's relation, with dwell time. */
482
+ transitions(body) {
483
+ return this.request("POST", "/v1/query/transitions", { body });
484
+ }
485
+ /** Lineage and evidence for a single edge. */
486
+ why(body) {
487
+ return this.request("POST", "/v1/query/why", { body });
488
+ }
489
+ /** SHACL-style shape/pattern query. */
490
+ shacl(body) {
491
+ return this.request("POST", "/v1/query/shacl", { body });
492
+ }
493
+ /**
494
+ * SPARQL-subset SELECT/ASK/aggregate query (FILTER, HAVING, ORDER BY, ASK,
495
+ * COUNT/SUM/AVG/MIN/MAX). GROUP BY is not limited to entity identity:
496
+ * `group_by` keys on a variable's entity, and `group_keys` adds typed scalar
497
+ * keys — a `property` value, or a `date_bucket` calendar truncation
498
+ * (`year`/`month`/`week`/`day`/`hour`) of a datetime property — so a
499
+ * per-category breakdown or a time series is one server-side query. Scalar
500
+ * keys come back per group in `groups[].value_keys[<as>]`, entity keys in
501
+ * `groups[].keys`.
502
+ */
503
+ sparql(body) {
504
+ return this.request("POST", "/v1/query/sparql", { body });
505
+ }
506
+ /** SPARQL 1.1 query from text (SELECT/ASK) over the live graph; `results` is SPARQL 1.1 Query Results JSON. */
507
+ sparqlText(body) {
508
+ return this.request("POST", "/v1/query/sparql-text", { body });
509
+ }
510
+ /**
511
+ * Run a SPARQL 1.1 text query and return parsed results — the ergonomic
512
+ * complement to {@link sparqlText} (which hands back the raw results string).
513
+ * Returns `{ vars, boolean, bindings, rows }` via {@link parseSparqlResults}:
514
+ * `rows` is the bindings flattened to `{ variable: lexicalValue }`, `boolean`
515
+ * is the ASK answer (or `null` for a SELECT).
516
+ */
517
+ async sparqlRows(body) {
518
+ return parseSparqlResults(await this.sparqlText(body));
519
+ }
520
+ /**
521
+ * Basic-graph-pattern query with group-graph-pattern combinators
522
+ * (UNION / OPTIONAL / MINUS / EXISTS / NOT EXISTS) folded over the base
523
+ * patterns. The complement to {@link sparql}: this route carries the
524
+ * combinators (but not FILTER/aggregation), so use it when a query needs an
525
+ * optional/union/negated leg rather than a grouped aggregate.
526
+ */
527
+ analytics(body) {
528
+ return this.request("POST", "/v1/query/analytics", { body });
529
+ }
530
+ /**
531
+ * Run inference rules (SHACL-AF `sh:TripleRule` shape) to a bounded fixpoint
532
+ * and return the derived edges as a **preview** — derived facts are never
533
+ * written to the asserted graph. Each rule is a BGP `body`/`where` plus a
534
+ * `head` triple template instantiated per binding.
535
+ */
536
+ infer(body) {
537
+ return this.request("POST", "/v1/inference/run", { body });
538
+ }
539
+ /**
540
+ * Define (replace) the versioned rule set stored on the scoped graph branch.
541
+ * The stored set is what SHACL `include_derived` and `infer` use when a
542
+ * request carries no inline rules. Returns the new `rules_version`.
543
+ */
544
+ defineRules(body) {
545
+ return this.request("POST", "/v1/inference/rules", { body });
546
+ }
547
+ /** The rule set stored on the scoped graph branch (version + rules). */
548
+ graphRules() {
549
+ return this.request("GET", "/v1/inference/rules");
550
+ }
551
+ /**
552
+ * Stage G — derive edges from calibrated retrieval matches (preview): each
553
+ * candidate scored `P >= threshold` becomes a derived edge `(anchor, relation,
554
+ * matched)` with a typed `Retrieval` provenance leaf. Pass either explicit
555
+ * `candidates` or a `query` the server runs as BM25 entity retrieval.
556
+ */
557
+ retrievalPremises(body) {
558
+ return this.request("POST", "/v1/inference/retrieval-premises", { body });
559
+ }
560
+ // --- ontology ---
561
+ /**
562
+ * The active ontology (entity types and relations) for the scoped graph.
563
+ * Pass `{ counts: true }` to include a per-relation current-edge count
564
+ * (`OntologyRelationView.edge_count`) so a caller can see which declared
565
+ * relations are actually populated — at the cost of a snapshot load.
566
+ */
567
+ ontologyView(opts = {}) {
568
+ return this.request("GET", "/v1/ontology", {
569
+ query: opts.counts ? { counts: true } : undefined,
570
+ });
571
+ }
572
+ /**
573
+ * Audit the current snapshot against the ontology's *implied* constraints —
574
+ * capped `cardinality` derived as `sh:maxCount` — returning a SHACL-shaped
575
+ * report. Whole-snapshot and never blocks a write. Unlike
576
+ * {@link SchemaNamespace.audit}, this needs no published shape bundle: the
577
+ * shapes come from the ontology itself. See the `decoration_status` catalog on
578
+ * {@link ontologyView} for which decorations are enforced.
579
+ */
580
+ ontologyConformance() {
581
+ return this.request("GET", "/v1/ontology/conformance");
582
+ }
583
+ /** Discover ontology concepts, terms, and relations. */
584
+ ontologySearch(body) {
585
+ return this.request("POST", "/v1/ontology/search", { body });
586
+ }
587
+ /** Resolve mentions to concepts/entities. */
588
+ ontologyResolve(body) {
589
+ return this.request("POST", "/v1/ontology/resolve", { body });
590
+ }
591
+ /** Define the active ontology before the scoped graph's first commit. */
592
+ ontologyDefine(body) {
593
+ return this.request("POST", "/v1/ontology/define", { body });
594
+ }
595
+ /**
596
+ * Additively evolve the active ontology of an existing graph: widen relation
597
+ * domains/ranges and declare new entity types (all by name), bumping the
598
+ * ontology version. Additive-only — every existing record stays valid, so no
599
+ * migration is needed — and a request that changes nothing is a no-op.
600
+ */
601
+ evolveOntology(body) {
602
+ return this.request("POST", "/v1/ontology/evolve", { body });
603
+ }
604
+ // --- index lifecycle ---
605
+ /**
606
+ * Build default ANN + BM25 indexes. With `{ background: true }` the build
607
+ * runs detached on the server and the call returns immediately — use it for
608
+ * large corpora whose synchronous build would exceed a fronting gateway's
609
+ * timeout (a 504), then poll `metadata()` for completion.
610
+ */
611
+ indexBuild(opts = {}) {
612
+ return this.request("POST", "/v1/index/build", { query: { background: opts.background || undefined } });
613
+ }
614
+ /**
615
+ * Build BM25, ANN/vector, and adjacency index families. With
616
+ * `{ background: true }` the build runs detached on the server and the call
617
+ * returns immediately — use it for large corpora whose synchronous build would
618
+ * exceed a fronting gateway's timeout, then poll `metadata()` for completion.
619
+ */
620
+ indexRun(opts = {}) {
621
+ return this.request("POST", "/v1/index/run", { query: { background: opts.background || undefined } });
622
+ }
623
+ /** Append a BM25 delta segment for the unindexed WAL tail. */
624
+ indexDelta() {
625
+ return this.request("POST", "/v1/index/delta");
626
+ }
627
+ /** Preview or delete superseded persisted index runs. */
628
+ indexGc(opts = {}) {
629
+ return this.request("POST", "/v1/index/gc", {
630
+ query: { keep_runs: opts.keepRuns, dry_run: opts.dryRun },
631
+ });
632
+ }
633
+ /** Fold the WAL tail into snapshot segments. */
634
+ compact(opts = {}) {
635
+ return this.request("POST", "/v1/graph/compact", {
636
+ query: { min_tail_commits: opts.minTailCommits, max_segments: opts.maxSegments },
637
+ });
638
+ }
639
+ // --- inspection ---
640
+ /** Server, graph, and persisted-index status. */
641
+ status() {
642
+ return this.request("GET", "/v1/status");
643
+ }
644
+ /** Graph footprint, WAL tail, and index coverage. */
645
+ metadata() {
646
+ return this.request("GET", "/v1/graph/metadata");
647
+ }
648
+ /** Graph counts and type/relation buckets. */
649
+ summary() {
650
+ return this.request("GET", "/v1/graph/summary");
651
+ }
652
+ /** List the graphs (and branches) under the scoped tenant. */
653
+ listGraphs() {
654
+ return this.request("GET", "/v1/graphs");
655
+ }
656
+ // --- database admin ---
657
+ /** Create a database stack and return its one-time stack API key. */
658
+ adminCreateStack(body) {
659
+ return this.request("POST", "/api/admin/stacks", { body });
660
+ }
661
+ /** Inspect a database stack without returning secret key material. */
662
+ adminStack(slug) {
663
+ return this.request("GET", "/api/admin/stacks", { query: { stack: slug } });
664
+ }
665
+ /** Rotate a database stack key and return the new one-time API key. */
666
+ adminRotateStackKey(slug) {
667
+ return this.request("POST", "/api/admin/stacks/rotate-key", { query: { stack: slug } });
668
+ }
669
+ /** Delete a database stack after confirming the slug. */
670
+ adminDeleteStack(slug) {
671
+ return this.request("DELETE", "/api/admin/stacks", { query: { stack: slug, confirm: slug } });
672
+ }
673
+ /**
674
+ * Mint a short-lived `lbb_ses_…` session token for an account. A trusted
675
+ * co-located service uses it (with `?stack=<slug>`) to call the data plane on
676
+ * the account's behalf without handling the stack's mode-bearing stack key.
677
+ */
678
+ adminMintSession(accountId) {
679
+ return this.request("POST", "/api/admin/sessions", { body: { account_id: accountId } });
680
+ }
681
+ /** Customer-visible activity for one database stack. */
682
+ adminStackActivity(slug, window = "24h") {
683
+ return this.request("GET", "/api/admin/stacks/activity", { query: { stack: slug, window } });
684
+ }
685
+ /** Activity for the stack selected by the bearer stack key or session. */
686
+ stackActivity(window = "24h") {
687
+ return this.request("GET", "/v1/stack/activity", { query: { window } });
688
+ }
689
+ }
690
+ export class GraphNamespace {
691
+ client;
692
+ facts;
693
+ constructor(client) {
694
+ this.client = client;
695
+ this.facts = new FactsNamespace(client);
696
+ }
697
+ branch(name) {
698
+ return new GraphNamespace(this.client.withScope({ branch: name }));
699
+ }
700
+ create() {
701
+ return this.client.createGraph();
702
+ }
703
+ delete(opts) {
704
+ return this.client.deleteGraph(opts);
705
+ }
706
+ /** Retract edges/entities from the scoped graph. See {@link LbbClient.retract}. */
707
+ retract(body, opts = {}) {
708
+ return this.client.retract(body, opts);
709
+ }
710
+ }
711
+ export class FactsNamespace {
712
+ client;
713
+ constructor(client) {
714
+ this.client = client;
715
+ }
716
+ create(body, opts = {}) {
717
+ return this.client.request("POST", "/v1/graph/commit", {
718
+ body,
719
+ idempotencyKey: opts.idempotencyKey ?? this.client.idempotencyKey("facts.create"),
720
+ });
721
+ }
722
+ /** Bulk-load a dataset as NDJSON. See {@link LbbClient.import}. */
723
+ import(lines, opts = {}) {
724
+ return this.client.import(lines, opts);
725
+ }
726
+ /**
727
+ * Bulk-load N-Triples through the native RDF import endpoint.
728
+ *
729
+ * Statements are committed through the fixed RDF_TRIPLE relation; source RDF
730
+ * predicates and literal term details are preserved as edge metadata.
731
+ */
732
+ importRdf(ntriples, opts = {}) {
733
+ return this.client.importRdf(ntriples, opts);
734
+ }
735
+ }
736
+ export class SearchNamespace {
737
+ client;
738
+ constructor(client) {
739
+ this.client = client;
740
+ }
741
+ hybrid(input, opts = {}) {
742
+ if (typeof input !== "string") {
743
+ return this.client.request("POST", "/v1/graph/search", { body: input });
744
+ }
745
+ return this.client.request("GET", "/v1/search", {
746
+ query: {
747
+ query: input,
748
+ top_k: opts.topK,
749
+ source: opts.source,
750
+ consistency: opts.consistency,
751
+ lexical: opts.lexical,
752
+ bm25: opts.bm25,
753
+ vector: opts.vector,
754
+ targets: opts.targets?.join(","),
755
+ profile: opts.profile,
756
+ log_impression: opts.logImpression,
757
+ },
758
+ });
759
+ }
760
+ multi(body) {
761
+ return this.client.multiSearch(body);
762
+ }
763
+ feedback(body, opts = {}) {
764
+ return this.client.searchFeedback(body, opts);
765
+ }
766
+ feedbackExport() {
767
+ return this.client.searchFeedbackExport();
768
+ }
769
+ fullText(body) {
770
+ return this.client.fullTextSearch(body);
771
+ }
772
+ vector(body) {
773
+ return this.client.embeddingSearch(body);
774
+ }
775
+ }
776
+ export class SchemaNamespace {
777
+ client;
778
+ constructor(client) {
779
+ this.client = client;
780
+ }
781
+ /** Active graph schema bundle: ontology plus activated SHACL shapes. */
782
+ view(opts = {}) {
783
+ return this.client.request("GET", "/v1/schema", {
784
+ query: { audit: opts.audit || undefined },
785
+ });
786
+ }
787
+ /** Preview a proposed RDF/SHACL schema bundle and audit current data. */
788
+ preview(body) {
789
+ return this.client.request("POST", "/v1/schema/preview", { body });
790
+ }
791
+ /** Activate a previewed SHACL schema bundle for this graph branch. */
792
+ publish(body) {
793
+ return this.client.request("POST", "/v1/schema/publish", { body });
794
+ }
795
+ /** Audit current data against the active SHACL schema bundle. */
796
+ audit() {
797
+ return this.client.request("POST", "/v1/schema/audit");
798
+ }
799
+ }
800
+ export class IndexNamespace {
801
+ client;
802
+ constructor(client) {
803
+ this.client = client;
804
+ }
805
+ run(opts = {}) {
806
+ const background = opts.background ?? (opts.wait === false ? true : undefined);
807
+ return this.client.request("POST", "/v1/index/run", {
808
+ query: { background },
809
+ body: opts.body,
810
+ });
811
+ }
812
+ build() {
813
+ return this.client.indexBuild();
814
+ }
815
+ delta() {
816
+ return this.client.indexDelta();
817
+ }
818
+ gc(opts = {}) {
819
+ return this.client.indexGc(opts);
820
+ }
821
+ }
822
+ export class EntityNamespace {
823
+ client;
824
+ constructor(client) {
825
+ this.client = client;
826
+ }
827
+ /**
828
+ * Browse entities as the unified list envelope. Pass `fields` (names or `*`)
829
+ * to inline each row's typed attributes as native JSON (under `attributes`) —
830
+ * "list entities and their titles" in one call instead of a list plus N point
831
+ * lookups — or `ids`
832
+ * to fetch a specific set. Page with `cursor` from the previous `next_cursor`.
833
+ */
834
+ list(opts = {}) {
835
+ const csv = (v) => Array.isArray(v) ? v.join(",") : v;
836
+ return this.client.request("GET", "/v1/graph/entities", {
837
+ query: {
838
+ type: opts.type,
839
+ limit: opts.limit,
840
+ cursor: opts.cursor,
841
+ offset: opts.offset,
842
+ q: opts.query,
843
+ fields: csv(opts.fields),
844
+ ids: csv(opts.ids),
845
+ },
846
+ });
847
+ }
848
+ get(opts) {
849
+ return this.client.entityMetadata(opts);
850
+ }
851
+ detail(opts) {
852
+ return this.client.entityDetail(opts);
853
+ }
854
+ /**
855
+ * Filter entities already bound by relation patterns using typed attributes,
856
+ * without writing RDF property IRIs by hand. This is a convenience wrapper over
857
+ * the structured SPARQL route: relation `patterns` bind variables, and `where`
858
+ * compares ontology property fields on those bound variables.
859
+ */
860
+ filterByAttributes(opts) {
861
+ const defaultVar = firstPatternVariable(opts.patterns);
862
+ const where = Array.isArray(opts.where) ? opts.where : [opts.where];
863
+ return this.client.sparql({
864
+ patterns: opts.patterns,
865
+ filters: [...(opts.filters ?? []), ...where.map((filter) => attributeFilter(filter, defaultVar))],
866
+ select: opts.select,
867
+ limit: opts.limit,
868
+ offset: opts.offset,
869
+ as_of_valid_time: opts.asOfValidTime,
870
+ as_of_commit_seq: opts.asOfCommitSeq,
871
+ order_by: opts.orderBy,
872
+ reason: opts.reason,
873
+ max_solutions: opts.maxSolutions,
874
+ max_object_reads: opts.maxObjectReads,
875
+ max_fetched_bytes: opts.maxFetchedBytes,
876
+ });
877
+ }
878
+ }