@brainbox-labs/sdk 0.0.0-stage → 0.22.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.
package/dist/index.js ADDED
@@ -0,0 +1,507 @@
1
+ import {
2
+ IngestPartialFailureError
3
+ } from "./chunk-OOHPBQXX.js";
4
+ import {
5
+ BrainBoxClient,
6
+ BrainDispatchError,
7
+ MCP,
8
+ WRITE_TOOL_NAMES,
9
+ createBrainExecutor,
10
+ createTenantBrainExecutor,
11
+ discoverProjectsView,
12
+ isTenantKey,
13
+ serve_exports,
14
+ tenantViewFrom
15
+ } from "./chunk-YWH6IOQG.js";
16
+ import "./chunk-MLKGABMK.js";
17
+
18
+ // src/brain.ts
19
+ import {
20
+ BRAIN_TOOL_DEFS
21
+ } from "@brainbox-labs/types";
22
+ import { declaredKeyScope } from "@brainbox-labs/api";
23
+
24
+ // src/local-grep.ts
25
+ var WIKI_KINDS = ["entity-brief", "pattern", "person", "role", "account", "raw-source", "synthesis"];
26
+ var LIST_PAGE_SIZE = 20;
27
+ var MAX_PAGES_PER_KIND = 1e3;
28
+ var FETCH_CONCURRENCY = 8;
29
+ var DEFAULT_LIMIT = 20;
30
+ var MAX_LIMIT = 50;
31
+ var DEFAULT_CONTEXT = 2;
32
+ var MAX_CONTEXT = 10;
33
+ function clampInt(v, fallback, min, max) {
34
+ return typeof v === "number" && Number.isFinite(v) && v >= min ? Math.min(Math.floor(v), max) : fallback;
35
+ }
36
+ function buildMatcher(args) {
37
+ const source = args.regex === true ? args.pattern : args.pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
38
+ try {
39
+ return new RegExp(source, args.caseSensitive === true ? "" : "i");
40
+ } catch (err) {
41
+ throw new Error(`[BrainBox] grep_wiki: invalid regex: ${err instanceof Error ? err.message : String(err)}`);
42
+ }
43
+ }
44
+ function grepBody(body, matcher, contextLines) {
45
+ const lines = body.split(/\r?\n/);
46
+ const out = [];
47
+ const headings = [];
48
+ let fence = null;
49
+ for (let i = 0; i < lines.length; i++) {
50
+ const text = lines[i];
51
+ const marker = /^\s*(`{3,}|~{3,})/.exec(text)?.[1]?.[0];
52
+ if (marker !== void 0) {
53
+ if (fence === null) fence = marker;
54
+ else if (fence === marker) fence = null;
55
+ } else if (fence === null) {
56
+ const h = /^(#{1,6})\s+(.*?)(?:\s+#+)?\s*$/.exec(text);
57
+ if (h) {
58
+ headings.length = Math.min(headings.length, h[1].length - 1);
59
+ headings.push(h[2]);
60
+ }
61
+ }
62
+ if (!matcher.test(text)) continue;
63
+ out.push({
64
+ line: i + 1,
65
+ headingPath: [...headings],
66
+ snippet: lines.slice(Math.max(0, i - contextLines), i + contextLines + 1).join("\n")
67
+ });
68
+ }
69
+ return out;
70
+ }
71
+ async function inPool(items, size, fn) {
72
+ const results = new Array(items.length);
73
+ let next = 0;
74
+ const worker = async () => {
75
+ while (next < items.length) {
76
+ const i = next++;
77
+ results[i] = await fn(items[i]);
78
+ }
79
+ };
80
+ await Promise.all(Array.from({ length: Math.min(size, items.length) }, worker));
81
+ return results;
82
+ }
83
+ async function grepWikiLocal(args, exec, callOpts) {
84
+ if (typeof args?.pattern !== "string" || args.pattern.trim() === "") {
85
+ throw new Error("[BrainBox] grep_wiki: `pattern` is required");
86
+ }
87
+ const matcher = buildMatcher(args);
88
+ const limit = clampInt(args.limit, DEFAULT_LIMIT, 1, MAX_LIMIT);
89
+ const contextLines = clampInt(args.contextLines, DEFAULT_CONTEXT, 0, MAX_CONTEXT);
90
+ const grepKind = async (kind) => {
91
+ const found = [];
92
+ let kept = 0;
93
+ let total = 0;
94
+ let searched = 0;
95
+ let listed = 0;
96
+ let unpaged = false;
97
+ let cursor;
98
+ do {
99
+ const listArgs = { kind, limit: LIST_PAGE_SIZE, includeBody: true };
100
+ if (args.tag !== void 0) listArgs["tag"] = args.tag;
101
+ if (args.namespace !== void 0) listArgs["namespace"] = args.namespace;
102
+ if (cursor !== void 0) listArgs["cursor"] = cursor;
103
+ const res = await exec("list_wiki_pages", listArgs, callOpts);
104
+ listed += res.pages.length;
105
+ const bodies = await inPool(res.pages, FETCH_CONCURRENCY, async (page) => {
106
+ if (typeof page.body === "string") return page.body;
107
+ if (page.bodyUnavailable) return null;
108
+ try {
109
+ const got = await exec("get_wiki_page", { pageId: page.pageId }, callOpts);
110
+ return typeof got.body === "string" ? got.body : null;
111
+ } catch {
112
+ return null;
113
+ }
114
+ });
115
+ res.pages.forEach((page, i) => {
116
+ const body = bodies[i];
117
+ if (body === null || body === void 0) return;
118
+ searched++;
119
+ const hits = grepBody(body, matcher, contextLines);
120
+ total += hits.length;
121
+ if (hits.length > 0 && kept < limit) {
122
+ found.push({ pageId: page.pageId, title: page.title, updatedAt: page.updatedAt, hits });
123
+ kept += hits.length;
124
+ }
125
+ });
126
+ cursor = res.nextCursor;
127
+ if (cursor === void 0 && res.pages.length >= LIST_PAGE_SIZE && !res.pages.some((p) => typeof p.body === "string" || p.bodyUnavailable)) {
128
+ unpaged = true;
129
+ }
130
+ } while (cursor !== void 0 && listed < MAX_PAGES_PER_KIND);
131
+ return { found, total, searched, deep: unpaged || listed >= MAX_PAGES_PER_KIND };
132
+ };
133
+ const kinds = args.kind !== void 0 ? [args.kind] : [...WIKI_KINDS];
134
+ const perKind = [];
135
+ for (const kind of kinds) perKind.push(await grepKind(kind));
136
+ const ordered = perKind.flatMap((k) => k.found).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
137
+ const matches = [];
138
+ for (const page of ordered) {
139
+ for (const hit of page.hits) {
140
+ if (matches.length < limit) matches.push({ pageId: page.pageId, title: page.title, ...hit });
141
+ }
142
+ }
143
+ const totalMatches = perKind.reduce((n, k) => n + k.total, 0);
144
+ return {
145
+ matches,
146
+ totalMatches,
147
+ truncated: totalMatches > matches.length,
148
+ pagesSearched: perKind.reduce((n, k) => n + k.searched, 0),
149
+ pagesTruncated: perKind.some((k) => k.deep)
150
+ };
151
+ }
152
+
153
+ // src/verb-namespace.ts
154
+ function cloneTool(t) {
155
+ const properties = {};
156
+ for (const [k, v] of Object.entries(t.inputSchema.properties)) {
157
+ properties[k] = { type: v.type, description: v.description };
158
+ if (v.enum !== void 0) properties[k].enum = [...v.enum];
159
+ if (v.items !== void 0) properties[k].items = v.items;
160
+ }
161
+ const inputSchema = {
162
+ type: t.inputSchema.type,
163
+ // additionalProperties:true prevents @ai-sdk/google from returning undefined
164
+ // for no-param tools (isEmptyObjectSchema check), which causes Vertex AI to
165
+ // reject with "parameters schema should be of type OBJECT". Ignored by all
166
+ // other SDKs (Anthropic, OpenAI, raw MCP).
167
+ additionalProperties: true,
168
+ properties
169
+ };
170
+ if (t.inputSchema.required !== void 0) {
171
+ inputSchema.required = [...t.inputSchema.required];
172
+ }
173
+ return { name: t.name, description: t.description, inputSchema };
174
+ }
175
+ function buildVerbNamespace(tools, executor, local = {}) {
176
+ const call = (name, args, callOpts) => {
177
+ const handler = local[name];
178
+ if (handler) return handler(args, callOpts);
179
+ return callOpts !== void 0 ? executor(name, args, callOpts) : executor(name, args);
180
+ };
181
+ const ns = {
182
+ asTools: () => tools.map((t) => ({
183
+ ...cloneTool(t),
184
+ execute: (args = {}, callOpts) => call(t.name, args, callOpts)
185
+ }))
186
+ };
187
+ for (const tool of tools) {
188
+ ns[tool.name] = (args = {}, callOpts) => call(tool.name, args, callOpts);
189
+ }
190
+ return Object.freeze(ns);
191
+ }
192
+
193
+ // src/brain.ts
194
+ var DEFAULT_API_URL = "https://ctx.brainbox-ai.app";
195
+ function isDebugEnabled() {
196
+ return process.env["DEBUG"]?.split(",").some((s) => s.trim() === "brainbox") === true;
197
+ }
198
+ var CUID2_RE = /^[a-z][a-z0-9]{23}$/;
199
+ var LEGACY_DOMAIN_TOOLS = /* @__PURE__ */ new Set([
200
+ "recall_concepts",
201
+ "explain_concept",
202
+ "define_terms",
203
+ "find_governing_rules",
204
+ "explore_workflows",
205
+ "trace_workflow",
206
+ "list_metrics",
207
+ "explain_metric",
208
+ "understand_connections"
209
+ ]);
210
+ var LOCAL_VERBS = /* @__PURE__ */ new Set(["grep_wiki"]);
211
+ var SURFACED_TOOLS = BRAIN_TOOL_DEFS.filter((t) => !LEGACY_DOMAIN_TOOLS.has(t.name));
212
+ function brainToolToMcp(t) {
213
+ const properties = {};
214
+ const required = [];
215
+ for (const p of t.params) {
216
+ const prop = { type: p.type, description: p.description };
217
+ if (p.enum !== void 0) prop.enum = p.enum;
218
+ if (p.items !== void 0) prop.items = p.items;
219
+ properties[p.name] = prop;
220
+ if (p.required) required.push(p.name);
221
+ }
222
+ const inputSchema = { type: "object", properties };
223
+ if (required.length > 0) inputSchema.required = required;
224
+ return { name: t.name, description: t.description, inputSchema };
225
+ }
226
+ var SERVER_GREP_WIKI = SURFACED_TOOLS.find((t) => t.name === "grep_wiki");
227
+ var GREP_WIKI_TOOL = SERVER_GREP_WIKI && (() => {
228
+ const t = brainToolToMcp(SERVER_GREP_WIKI);
229
+ t.description = "Search wiki page bodies for a literal string (or JavaScript regex when regex=true). Runs client-side: lists pages, fetches their bodies and matches locally, so it works for every org. Pages through each kind (up to ~1000 pages per kind); check pagesTruncated in the result and narrow with kind, tag or namespace on very large wikis.";
230
+ t.inputSchema.properties["namespace"] = {
231
+ type: "string",
232
+ description: "Only search this namespace and everything nested under it. Mutually exclusive with tag."
233
+ };
234
+ return t;
235
+ })();
236
+ var RECALL_TOOLS = [
237
+ ...SURFACED_TOOLS.filter((t) => !WRITE_TOOL_NAMES.has(t.name) && t.name !== "grep_wiki").map(brainToolToMcp),
238
+ ...GREP_WIKI_TOOL ? [GREP_WIKI_TOOL] : []
239
+ ];
240
+ var UPDATE_TOOLS = SURFACED_TOOLS.filter((t) => WRITE_TOOL_NAMES.has(t.name)).map(brainToolToMcp);
241
+ function deprecatedUpdateVerbs(update) {
242
+ return {
243
+ append_wiki_page: (args = {}, callOpts) => {
244
+ const a = args;
245
+ return update["save_wiki_page"]({ mode: "append", id: a.pageId, body: a.text, baseVersion: a.baseVersion }, callOpts);
246
+ },
247
+ flag_personal_page_for_review: (args = {}, callOpts) => {
248
+ const { pageId, ...rest } = args;
249
+ return update["save_personal_page"]({ ...rest, id: pageId, flagForReview: true }, callOpts);
250
+ }
251
+ };
252
+ }
253
+ function withProjectIdParam(tool) {
254
+ tool.inputSchema.properties["projectId"] = {
255
+ type: "string",
256
+ description: "Which Brain to read; results cover only this one Brain. Omit to read this tenant's own (overlay) Brain; pass a shared Brain's projectId from list_projects for a question about its data."
257
+ };
258
+ const execute = tool.execute;
259
+ tool.execute = (args = {}, callOpts) => {
260
+ const { projectId, ...rest } = args;
261
+ const fromModel = typeof projectId === "string" && projectId.trim() !== "" ? projectId.trim() : void 0;
262
+ return execute(rest, fromModel !== void 0 && callOpts?.projectId === void 0 ? { ...callOpts, projectId: fromModel } : callOpts);
263
+ };
264
+ return tool;
265
+ }
266
+ var BrainBox = class {
267
+ constructor(options) {
268
+ this.options = options;
269
+ this.serve = new BrainBoxServe(options);
270
+ const lazyExecutor = async (toolName, args, callOpts) => {
271
+ const exec = await this.getExecutor();
272
+ try {
273
+ return await (callOpts !== void 0 ? exec(toolName, args, callOpts) : exec(toolName, args));
274
+ } catch (err) {
275
+ throw await this.explainDisabledTool(toolName, err);
276
+ }
277
+ };
278
+ const recall = buildVerbNamespace(RECALL_TOOLS, lazyExecutor, {
279
+ grep_wiki: (args, callOpts) => grepWikiLocal(args, lazyExecutor, callOpts)
280
+ });
281
+ const update = buildVerbNamespace(UPDATE_TOOLS, lazyExecutor);
282
+ const recallTools = isTenantKey(options.apiKey) ? () => [...recall.asTools().map(withProjectIdParam), this.listProjectsTool()] : () => recall.asTools();
283
+ this.recall = Object.freeze({
284
+ ...recall,
285
+ asTools: recallTools,
286
+ asEnabledTools: () => this.enabledTools(recallTools())
287
+ });
288
+ this.update = Object.freeze({
289
+ ...update,
290
+ ...deprecatedUpdateVerbs(update),
291
+ asEnabledTools: () => this.enabledTools(update.asTools())
292
+ });
293
+ this.projects = {
294
+ list: async () => (await this.getDiscovery()).projects,
295
+ create: (name) => {
296
+ this.assertNotTenantKey("projects.create");
297
+ return this.client().createProject(name, this.options.org).finally(() => {
298
+ this.discoveryPromise = void 0;
299
+ });
300
+ }
301
+ };
302
+ }
303
+ options;
304
+ serve;
305
+ recall;
306
+ update;
307
+ projects;
308
+ projectIdPromise;
309
+ tenantViewPromise;
310
+ discoveryPromise;
311
+ executor;
312
+ /**
313
+ * GET /api/projects for any key type: the addressable projects plus the tools
314
+ * this org has switched off. A successful fetch is cached; a failed one is
315
+ * cleared so the next call retries.
316
+ */
317
+ getDiscovery() {
318
+ this.discoveryPromise ??= discoverProjectsView(
319
+ this.options.apiUrl ?? DEFAULT_API_URL,
320
+ this.options.apiKey
321
+ ).catch((err) => {
322
+ this.discoveryPromise = void 0;
323
+ throw err;
324
+ });
325
+ return this.discoveryPromise;
326
+ }
327
+ /** Tenant-key agents call this first to find the base Brains they can pass as `projectId`. */
328
+ listProjectsTool() {
329
+ return {
330
+ name: "list_projects",
331
+ description: 'List the Brains visible to this tenant: its own Brain (role "overlay") plus the shared, read-only Brains it can read (role "base"). Base entries may carry a `description` and `aliases`; route on those, not just the name, when base Brains look alike. To read a shared Brain, pass its projectId to any read tool; omit projectId to read this tenant\'s own Brain. Call this first.',
332
+ inputSchema: { type: "object", additionalProperties: true, properties: {} },
333
+ execute: async () => ({ projects: await this.projects.list() })
334
+ };
335
+ }
336
+ /** Best-effort: discovery failing must never hide tools, so an error means "nothing disabled". */
337
+ async getDisabledTools() {
338
+ try {
339
+ return new Set((await this.getDiscovery()).disabledTools);
340
+ } catch {
341
+ return /* @__PURE__ */ new Set();
342
+ }
343
+ }
344
+ /** Drops tools this org has switched off. Local verbs (grep_wiki) never hit the gated server tool, so they stay. */
345
+ async enabledTools(tools) {
346
+ const disabled = await this.getDisabledTools();
347
+ return tools.filter((t) => !disabled.has(t.name) || LOCAL_VERBS.has(t.name));
348
+ }
349
+ /**
350
+ * A gated tool fails with a bare dispatch 403. Only on that failure, look up
351
+ * the org's disabled set (no extra request on the happy path) and replace the
352
+ * error with a clear one if the tool is in it.
353
+ */
354
+ async explainDisabledTool(toolName, err) {
355
+ if (!(err instanceof BrainDispatchError) || err.status !== 403) return err;
356
+ if ((await this.getDisabledTools()).has(toolName)) {
357
+ return new BrainDispatchError(err.status, err.toolName, err.body, {
358
+ message: `[BrainBox] ${toolName} is not enabled for this org. Ask an org admin to enable it.`
359
+ });
360
+ }
361
+ return err;
362
+ }
363
+ client() {
364
+ return new BrainBoxClient({
365
+ apiUrl: this.options.apiUrl ?? DEFAULT_API_URL,
366
+ apiKey: this.options.apiKey
367
+ });
368
+ }
369
+ /** Tenant keys see projects through the overlay/base view, and POST /projects returns their existing overlay instead of creating. */
370
+ assertNotTenantKey(op) {
371
+ if (isTenantKey(this.options.apiKey)) {
372
+ throw new Error(`[BrainBox] brain.${op} is not available for tenant keys \u2014 use an org or project key.`);
373
+ }
374
+ }
375
+ /**
376
+ * Ingest sources into this brain — equivalent to running `brainbox meta ingest`
377
+ * + `repo push` + `repo meta create` + `repo meta approve`. Blocks until each
378
+ * stage's context is activated and a new version is published.
379
+ *
380
+ * For tenant keys, always targets the tenant's overlay project — `project`
381
+ * on the parent {@link BrainBox} handle is ignored, since base projects are
382
+ * shared, read-only brains that a tenant must never write into. For
383
+ * project/org keys, requires `project` on the parent handle.
384
+ */
385
+ async ingest(opts) {
386
+ const apiUrl = this.options.apiUrl ?? DEFAULT_API_URL;
387
+ this.logDeclaredScope("ingest");
388
+ const { performIngest } = await import("./ingest-OA6KWJNR.js");
389
+ if (isTenantKey(this.options.apiKey)) {
390
+ const view = await this.getTenantView();
391
+ this.logConfirmedScope("ingest", "tenant", `overlay=${view.overlay.projectId}`);
392
+ return performIngest(
393
+ {
394
+ apiUrl,
395
+ apiKey: this.options.apiKey,
396
+ org: this.options.org,
397
+ project: view.overlay.projectId
398
+ },
399
+ opts
400
+ );
401
+ }
402
+ if (!this.options.project) {
403
+ throw new Error(
404
+ "[BrainBox] brain.ingest requires a project. Pass `project` to new BrainBox({...})."
405
+ );
406
+ }
407
+ return performIngest(
408
+ {
409
+ apiUrl,
410
+ apiKey: this.options.apiKey,
411
+ org: this.options.org,
412
+ project: this.options.project
413
+ },
414
+ opts
415
+ );
416
+ }
417
+ async getExecutor() {
418
+ this.logDeclaredScope("recall/update");
419
+ if (this.executor) return this.executor;
420
+ const apiUrl = this.options.apiUrl ?? DEFAULT_API_URL;
421
+ if (isTenantKey(this.options.apiKey)) {
422
+ const view = await this.getTenantView();
423
+ this.logConfirmedScope("recall/update", "tenant", `overlay=${view.overlay.projectId}, bases=${view.bases.length}`);
424
+ this.executor = createTenantBrainExecutor(apiUrl, this.options.apiKey, view);
425
+ return this.executor;
426
+ }
427
+ if (!this.options.project) {
428
+ throw new Error(
429
+ "[BrainBox] recall/update require a project. Pass `project` to new BrainBox({...})."
430
+ );
431
+ }
432
+ const projectId = await this.resolveProjectId(this.options.project);
433
+ this.logConfirmedScope("recall/update", "project", `projectId=${projectId}`);
434
+ this.executor = createBrainExecutor(apiUrl, this.options.apiKey, projectId);
435
+ return this.executor;
436
+ }
437
+ /** Best-effort scope label from the key prefix alone — logged before any network call. */
438
+ logDeclaredScope(caller) {
439
+ if (!isDebugEnabled()) return;
440
+ const scope = declaredKeyScope(this.options.apiKey) ?? "unknown";
441
+ console.log(`[BrainBox] ${caller} \u2192 org=${this.options.org} scope=${scope} (declared)`);
442
+ }
443
+ /** Backend-confirmed scope, logged once a resolving call (tenant view / project lookup) succeeds. */
444
+ logConfirmedScope(caller, scope, detail) {
445
+ if (!isDebugEnabled()) return;
446
+ console.log(`[BrainBox] ${caller} \u2192 scope=${scope} (confirmed): ${detail}`);
447
+ }
448
+ /**
449
+ * Resolves a tenant key's view (overlay + readable bases) from the cached GET /api/projects.
450
+ * A successful resolve is cached; a failed resolve is cleared so the next call
451
+ * retries instead of replaying the rejection.
452
+ */
453
+ getTenantView() {
454
+ this.tenantViewPromise ??= this.getDiscovery().then((d) => tenantViewFrom(d.projects)).catch((err) => {
455
+ this.tenantViewPromise = void 0;
456
+ throw err;
457
+ });
458
+ return this.tenantViewPromise;
459
+ }
460
+ resolveProjectId(project) {
461
+ if (CUID2_RE.test(project)) return Promise.resolve(project);
462
+ this.projectIdPromise ??= (() => {
463
+ return this.client().resolveProjectId(project, this.options.org).catch((err) => {
464
+ this.projectIdPromise = void 0;
465
+ throw err;
466
+ });
467
+ })();
468
+ return this.projectIdPromise;
469
+ }
470
+ };
471
+ var BrainBoxServe = class {
472
+ constructor(handle) {
473
+ this.handle = handle;
474
+ }
475
+ handle;
476
+ /**
477
+ * Build an MCP server bound to this brain. Returns an unstarted MCP
478
+ * instance — call `.start({ port })` to begin serving.
479
+ *
480
+ * A `project` is required on the parent {@link BrainBox} handle until
481
+ * org-level default brains are supported by the server runtime — except
482
+ * for tenant keys, which discover their overlay + base projects at
483
+ * `start()` time via GET /api/projects instead.
484
+ */
485
+ mcp(opts = {}) {
486
+ if (!this.handle.project && !isTenantKey(this.handle.apiKey)) {
487
+ throw new Error(
488
+ "[BrainBox] serve.mcp() requires a project. Pass `project` to new BrainBox({...})."
489
+ );
490
+ }
491
+ const merged = {
492
+ apiKey: this.handle.apiKey,
493
+ ...this.handle.project !== void 0 ? { project: this.handle.project } : {},
494
+ ...opts
495
+ };
496
+ if (this.handle.apiUrl !== void 0) merged.apiUrl = this.handle.apiUrl;
497
+ return new MCP(merged);
498
+ }
499
+ };
500
+ export {
501
+ BrainBox,
502
+ BrainBoxServe,
503
+ BrainDispatchError,
504
+ IngestPartialFailureError,
505
+ isTenantKey,
506
+ serve_exports as serve
507
+ };
@@ -0,0 +1,182 @@
1
+ import { RawSchema, ColumnProfile, JsonKeyEntry, AnalysisDepth, DocumentSource } from '@brainbox-labs/types';
2
+
3
+ type Dialect = 'postgres' | 'mysql' | 'sqlite' | 'duckdb' | 'trino' | 'athena';
4
+ type ProfileMode = 'cardinality' | 'full';
5
+ interface ProfileOptions {
6
+ mode: ProfileMode;
7
+ sampleRows: number;
8
+ /** "tablename.columnname" entries — columns whose profiles are excluded from output. */
9
+ skipColumns: Set<string>;
10
+ }
11
+ /** Minimal database abstraction used by ColumnProfiler. Injectable for testing. */
12
+ interface DbConnection {
13
+ queryRows<T = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<T[]>;
14
+ close(): Promise<void>;
15
+ }
16
+ declare function detectDialect(url: string): Dialect;
17
+ declare function quoteIdentifier(name: string, dialect: Dialect): string;
18
+ /**
19
+ * Detects a structural format hint from a sample of string values.
20
+ * Returns 'free-text' when fewer than 80% of values match any known pattern.
21
+ * Returns undefined only when the sample is empty.
22
+ */
23
+ declare function detectFormatHint(values: string[]): ColumnProfile['formatHint'];
24
+ /**
25
+ * Extracts a flattened key-path summary from sampled JSON values.
26
+ * `occurrence` is expressed as a fraction of `totalDocs` (rowsScanned for the column),
27
+ * matching the RFC definition: "documents-with-this-path / rowsScanned".
28
+ */
29
+ declare function extractJsonShape(jsonValues: unknown[], totalDocs: number): JsonKeyEntry[];
30
+ declare class ColumnProfiler {
31
+ private readonly conn;
32
+ private readonly dialect;
33
+ /** Injected timestamp for determinism in tests. Defaults to new Date(). */
34
+ private readonly now;
35
+ constructor(conn: DbConnection, dialect: Dialect,
36
+ /** Injected timestamp for determinism in tests. Defaults to new Date(). */
37
+ now?: () => string);
38
+ private q;
39
+ /** Returns the qualified table reference (schema-qualified except for SQLite). */
40
+ private tableRef;
41
+ /**
42
+ * Profiles each column in every table of `schema` and returns a new RawSchema
43
+ * with `profile` populated on each non-skipped column.
44
+ */
45
+ profileSchema(schema: RawSchema, opts: ProfileOptions): Promise<RawSchema>;
46
+ private profileTable;
47
+ /**
48
+ * Fetches up to `limit` rows in a deterministic order.
49
+ *
50
+ * When a PK is available, ORDER BY the PK column(s) — fully deterministic.
51
+ * Without a PK, fall back to a dialect-specific physical row identifier:
52
+ * postgres → ctid, sqlite → rowid, duckdb → rowid (system column)
53
+ * mysql → ORDER BY 1 (sort by first projected column, deterministic
54
+ * for stable data but NOT guaranteed across InnoDB page splits;
55
+ * best-effort until a schema-introspection PK is available).
56
+ * trino → ORDER BY 1 (no physical row id; Trino never reports PKs, so
57
+ * this is always the path taken — same best-effort caveat).
58
+ * athena → ORDER BY 1 (same rationale as trino; Athena's engine is
59
+ * Trino-based and reports no physical row id either).
60
+ */
61
+ private fetchSample;
62
+ private profileColumn;
63
+ }
64
+ /** Main entry point: connect, profile, close. */
65
+ declare function connectAndProfile(connectionUrl: string, schema: RawSchema, opts: ProfileOptions): Promise<RawSchema>;
66
+ /** Parses a `--profile-data [mode]` Commander option value into ProfileMode or null. */
67
+ declare function parseProfileMode(value: boolean | string | undefined): ProfileMode | null;
68
+ /** Parses a `--skip-profile-columns table.col,...` string into a Set. */
69
+ declare function parseSkipColumns(raw: string | undefined): Set<string>;
70
+
71
+ type IntrospectionDialect = 'postgres' | 'trino' | 'athena';
72
+ declare const SUPPORTED_INTROSPECTION_DIALECTS: readonly IntrospectionDialect[];
73
+ /**
74
+ * Strict URL-scheme detection — unlike the profiler's detectDialect(), this
75
+ * never falls back to postgres, because misrouting introspection produces a
76
+ * confusing driver error instead of a clear "unsupported" one.
77
+ */
78
+ declare function detectIntrospectionDialect(url: string): IntrospectionDialect | undefined;
79
+ /**
80
+ * Introspects a database schema, routing to the engine's introspector.
81
+ *
82
+ * `dialect` wins when given (callers that already know the engine — e.g.
83
+ * brain.ingest's `postgres` / `trino` / `athena` option keys — must pass it, which also
84
+ * keeps keyword/value Postgres connection strings working). Otherwise the
85
+ * engine is detected from the URL scheme.
86
+ */
87
+ declare function introspectDatabaseSchema(connectionString: string, dialect?: IntrospectionDialect): Promise<RawSchema>;
88
+
89
+ interface TrinoTarget {
90
+ /** http(s) endpoint of the Trino coordinator, e.g. "https://trino.acme.io:443". */
91
+ server: string;
92
+ catalog: string;
93
+ /** When present, introspection is restricted to this schema. */
94
+ schema?: string;
95
+ user: string;
96
+ password?: string;
97
+ }
98
+ /**
99
+ * Parses a Trino connection URL of the form
100
+ *
101
+ * trino://user[:password]@host[:port]/catalog[/schema][?ssl=true|false]
102
+ *
103
+ * TLS is used when the scheme is `trino+https://`, when `?ssl=true` is set, or
104
+ * whenever a password is present (Trino rejects password auth over plain HTTP).
105
+ * `?ssl=false` or a `trino+http://` scheme forces plain HTTP for dev setups.
106
+ * Default port: 443 with TLS, 8080 without.
107
+ *
108
+ * The URL contains credentials — like the Postgres connection string, it must
109
+ * never be logged or sent to BrainBox. Errors thrown here deliberately omit it.
110
+ */
111
+ declare function parseTrinoUrl(url: string): TrinoTarget;
112
+ declare function openTrinoConnection(url: string): Promise<DbConnection>;
113
+ /**
114
+ * Introspects the catalog's information_schema over an open connection.
115
+ * Exported separately so tests can inject a fake DbConnection.
116
+ */
117
+ declare function introspectTrinoSchemaWithConnection(conn: DbConnection, schemaFilter?: string): Promise<RawSchema>;
118
+ declare function introspectTrinoSchema(connectionString: string): Promise<RawSchema>;
119
+
120
+ interface AthenaTarget {
121
+ region: string;
122
+ /** Glue Data Catalog name. Defaults to "AwsDataCatalog". */
123
+ catalog: string;
124
+ /** Athena database — the "schema" level in Trino terms. */
125
+ database: string;
126
+ /** Workgroup to run queries under. Defaults to "primary". */
127
+ workgroup: string;
128
+ /** s3:// location for query results. Omitted when the workgroup enforces its own. */
129
+ outputLocation?: string;
130
+ /** Max time to wait for a query to reach a terminal state, in ms. Defaults to 300 000 (5 min). */
131
+ pollTimeoutMs: number;
132
+ }
133
+ /**
134
+ * Parses an Athena connection URL of the form
135
+ *
136
+ * athena://region/database[?catalog=AwsDataCatalog&workgroup=primary&output=s3://bucket/prefix&pollTimeoutMs=300000]
137
+ *
138
+ * AWS credentials are never part of the URL — they come from the standard AWS
139
+ * SDK credential chain (env vars, shared config/profile, or an IAM role), the
140
+ * same way any other AWS SDK client in this environment would resolve them.
141
+ * `jdbc:awsathena://...` connection strings are a different, unsupported
142
+ * format; convert to the `athena://` form above.
143
+ */
144
+ declare function parseAthenaUrl(url: string): AthenaTarget;
145
+ declare function openAthenaConnection(url: string): Promise<DbConnection>;
146
+ /**
147
+ * Introspects the database's information_schema over an open connection.
148
+ * Exported separately so tests can inject a fake DbConnection.
149
+ */
150
+ declare function introspectAthenaSchemaWithConnection(conn: DbConnection, database: string): Promise<RawSchema>;
151
+ declare function introspectAthenaSchema(connectionString: string): Promise<RawSchema>;
152
+
153
+ /**
154
+ * Returns true for file extensions that require conversion to markdown
155
+ * before staging (PDF, DOCX, HTML).
156
+ */
157
+ declare function needsConversion(filePath: string): boolean;
158
+ /**
159
+ * Converts an HTML string (not a file) to markdown. Exported so callers that
160
+ * already hold HTML in memory — e.g. the `collect web` crawler — reuse the exact
161
+ * same turndown configuration as file conversion instead of adding a converter.
162
+ */
163
+ declare function htmlToMarkdown(html: string): Promise<string>;
164
+ /**
165
+ * Converts a PDF, DOCX, or HTML file to a markdown string.
166
+ * DOCX: mammoth converts to HTML, then turndown converts to markdown.
167
+ * HTML: turndown converts directly to markdown.
168
+ * PDF: pdf-parse extracts plain text (valid markdown).
169
+ */
170
+ declare function convertToMarkdown(filePath: string): Promise<string>;
171
+ /**
172
+ * Returns the staging filename for a converted document.
173
+ * e.g. "report.pdf" → "report.pdf.md", "spec.docx" → "spec.docx.md"
174
+ */
175
+ declare function convertedName(filePath: string): string;
176
+
177
+ declare function expandDocPatterns(patterns: string[], outputDir?: string, analysisDepth?: AnalysisDepth): Promise<DocumentSource[]>;
178
+ /** Wrap free-form text as an inline DocumentSource. Filename is fixed — callers
179
+ * should not see their `message` reflected back as a server-visible doc name. */
180
+ declare function inlineText(text: string, analysisDepth?: AnalysisDepth): DocumentSource;
181
+
182
+ export { type AthenaTarget, ColumnProfiler, type DbConnection, type Dialect, type IntrospectionDialect, type ProfileMode, type ProfileOptions, SUPPORTED_INTROSPECTION_DIALECTS, type TrinoTarget, connectAndProfile, convertToMarkdown, convertedName, detectDialect, detectFormatHint, detectIntrospectionDialect, expandDocPatterns, extractJsonShape, htmlToMarkdown, inlineText, introspectAthenaSchema, introspectAthenaSchemaWithConnection, introspectDatabaseSchema, introspectTrinoSchema, introspectTrinoSchemaWithConnection, needsConversion, openAthenaConnection, openTrinoConnection, parseAthenaUrl, parseProfileMode, parseSkipColumns, parseTrinoUrl, quoteIdentifier };