@brainbox-labs/sdk 0.0.0-stage → 0.23.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.
@@ -0,0 +1,260 @@
1
+ import {
2
+ lookupIds,
3
+ performIngest,
4
+ resolveIds
5
+ } from "./chunk-XFLBPF4A.js";
6
+ import {
7
+ deriveSourceKey,
8
+ frontmatterSourceKey,
9
+ loadDocFile,
10
+ normalizeNamespace,
11
+ validateSourceKey
12
+ } from "./chunk-4J77FNJJ.js";
13
+ import {
14
+ createBrainExecutor
15
+ } from "./chunk-GVWDS5TG.js";
16
+ import "./chunk-MLKGABMK.js";
17
+
18
+ // src/sync/index.ts
19
+ import * as nodePath2 from "path";
20
+ import { glob } from "glob";
21
+ import { BrainBoxApiClient } from "@brainbox-labs/api";
22
+
23
+ // src/sync/transform.ts
24
+ import { createHash } from "crypto";
25
+ import * as fs from "fs/promises";
26
+ import * as nodePath from "path";
27
+ import { pathToFileURL } from "url";
28
+ var EXTENSIONS = [".ts", ".mjs", ".js"];
29
+ var sha256Hex = (data) => createHash("sha256").update(data).digest("hex");
30
+ async function resolveTransformPath(ref, baseDir) {
31
+ const isPath = ref.includes("/") || ref.includes("\\") || EXTENSIONS.includes(nodePath.extname(ref));
32
+ const candidates = isPath ? [nodePath.resolve(baseDir, ref)] : EXTENSIONS.map((ext) => nodePath.resolve(baseDir, ".brainbox", "transforms", ref + ext));
33
+ for (const c of candidates) {
34
+ try {
35
+ await fs.access(c);
36
+ return c;
37
+ } catch {
38
+ }
39
+ }
40
+ throw new Error(`[BrainBox] transform "${ref}" not found (looked for ${candidates.join(", ")})`);
41
+ }
42
+ async function loadTransform(ref, baseDir) {
43
+ const file = await resolveTransformPath(ref, baseDir);
44
+ const bytes = await fs.readFile(file);
45
+ let mod;
46
+ try {
47
+ mod = await import(pathToFileURL(file).href);
48
+ } catch (err) {
49
+ const hint = file.endsWith(".ts") ? " (.ts transforms need Node 22.6+ or a loader such as tsx; a .mjs works everywhere)" : "";
50
+ throw new Error(`[BrainBox] could not load transform ${file}: ${err instanceof Error ? err.message : String(err)}${hint}`);
51
+ }
52
+ if (typeof mod.default !== "function") throw new Error(`[BrainBox] transform ${file} must default-export a function`);
53
+ return { id: nodePath.basename(file, nodePath.extname(file)), hash: sha256Hex(bytes), fn: mod.default };
54
+ }
55
+ async function applyTransform(t, input) {
56
+ const out = await t.fn(input);
57
+ if (out === null || out === void 0) return null;
58
+ const res = typeof out === "string" ? { content: out } : out;
59
+ if (typeof res.content !== "string") throw new Error(`[BrainBox] transform "${t.id}" returned no string content for ${input.path}`);
60
+ return { content: res.content, metadata: { ...input.metadata, ...res.metadata ?? {}, transform: `${t.id}@${t.hash.slice(0, 12)}` } };
61
+ }
62
+ function computeSourceVersion(content, transform) {
63
+ const contentHash = sha256Hex(content);
64
+ if (!transform) return `sha256:${contentHash}`;
65
+ return `sha256:${sha256Hex(`${contentHash}
66
+ transform:${transform.id}:${transform.hash}`)}`;
67
+ }
68
+
69
+ // src/sync/diff.ts
70
+ function diffSources(local, remote) {
71
+ const byKey = new Map(remote.map((r) => [r.sourceKey, r]));
72
+ const localKeys = new Set(local.map((l) => l.sourceKey));
73
+ const diff = { added: [], changed: [], unchanged: [], deleted: [] };
74
+ for (const doc of local) {
75
+ const r = byKey.get(doc.sourceKey);
76
+ if (!r) diff.added.push(doc);
77
+ else if (r.sourceVersion !== doc.sourceVersion || normalizeNamespace(r.namespace) !== normalizeNamespace(doc.namespace) || r.analysisDepth !== void 0 && doc.analysisDepth !== void 0 && r.analysisDepth !== doc.analysisDepth) diff.changed.push(doc);
78
+ else diff.unchanged.push(doc);
79
+ }
80
+ diff.deleted = remote.filter((r) => !localKeys.has(r.sourceKey));
81
+ return diff;
82
+ }
83
+ var MAX_LIST_PAGES = 500;
84
+ var LIST_PAGE_LIMIT = 50;
85
+ var SERVER_SCAN_WINDOW = 1e3;
86
+ function executorLister(exec) {
87
+ return {
88
+ async listSources(namespace) {
89
+ const want = normalizeNamespace(namespace);
90
+ const out = [];
91
+ let seen = 0;
92
+ let cursor;
93
+ for (let i = 0; i < MAX_LIST_PAGES; i++) {
94
+ const args = { kind: "raw-source", limit: LIST_PAGE_LIMIT, ...want !== "" ? { namespace: want } : {}, ...cursor ? { cursor } : {} };
95
+ const res = await exec("list_wiki_pages", args);
96
+ seen += res.pages?.length ?? 0;
97
+ for (const p of res.pages ?? []) {
98
+ if (!p.sourceKey || normalizeNamespace(p.namespace) !== want) continue;
99
+ out.push({ sourceKey: p.sourceKey, title: p.title, pageId: p.pageId, sourceVersion: p.sourceVersion, namespace: p.namespace, analysisDepth: p.analysisDepth });
100
+ }
101
+ if (!res.nextCursor) return { sources: out, truncated: seen >= SERVER_SCAN_WINDOW };
102
+ cursor = res.nextCursor;
103
+ }
104
+ throw new Error("[BrainBox] sync: too many raw-source pages to list; narrow with a namespace");
105
+ }
106
+ };
107
+ }
108
+
109
+ // src/sync/index.ts
110
+ var DOC_GLOB = "**/*.{md,markdown,txt,html,htm,pdf,docx}";
111
+ var noopLogger = { isVerbose: false, debug: () => {
112
+ }, info: () => {
113
+ }, warn: () => {
114
+ }, error: () => {
115
+ } };
116
+ async function collect(opts, transform) {
117
+ const raw = [];
118
+ if (opts.dir) {
119
+ const root = nodePath2.resolve(opts.dir);
120
+ const files = (await glob(DOC_GLOB, { cwd: root, nodir: true, ignore: ["**/node_modules/**"] })).sort();
121
+ for (const rel of files) {
122
+ const loaded = await loadDocFile(nodePath2.join(root, rel));
123
+ raw.push({ rel: rel.split(nodePath2.sep).join("/"), content: loaded.content, type: loaded.type, entry: { name: rel } });
124
+ }
125
+ }
126
+ for (const e of opts.sources ?? []) {
127
+ let content = e.content;
128
+ let name = e.name;
129
+ let type = e.type;
130
+ if (content === void 0) {
131
+ if (!e.path) throw new Error("[BrainBox] sync: a source needs `path` or `content`");
132
+ const loaded = await loadDocFile(e.path);
133
+ content = loaded.content;
134
+ name ??= loaded.name;
135
+ type ??= loaded.type;
136
+ }
137
+ const rel = name ?? e.sourceKey;
138
+ if (!rel) throw new Error("[BrainBox] sync: a source needs a `name` or `sourceKey`");
139
+ raw.push({ rel, content, type, entry: { ...e, name: rel } });
140
+ }
141
+ const docs = [];
142
+ const skippedByTransform = [];
143
+ const seen = /* @__PURE__ */ new Map();
144
+ for (const r of raw) {
145
+ const originalKey = frontmatterSourceKey(r.content);
146
+ let content = r.content;
147
+ let metadata = { ...r.entry.metadata ?? {} };
148
+ if (transform) {
149
+ const out = await applyTransform(transform, { path: r.rel, content, metadata });
150
+ if (out === null) {
151
+ skippedByTransform.push(r.rel);
152
+ continue;
153
+ }
154
+ content = out.content;
155
+ metadata = out.metadata;
156
+ }
157
+ const sourceKey = r.entry.sourceKey !== void 0 ? validateSourceKey(r.entry.sourceKey) : originalKey ?? deriveSourceKey(r.rel, opts.namespace);
158
+ const prior = seen.get(sourceKey);
159
+ if (prior !== void 0) throw new Error(`[BrainBox] sync: "${prior}" and "${r.rel}" both map to sourceKey "${sourceKey}"`);
160
+ seen.set(sourceKey, r.rel);
161
+ const sourceVersion = r.entry.sourceVersion ?? computeSourceVersion(content, transform);
162
+ const namespace = r.entry.namespace ?? opts.namespace;
163
+ const analysisDepth = r.entry.analysisDepth ?? opts.analysisDepth;
164
+ docs.push({
165
+ // Server's resolveDepth: per-source ?? request default ?? 'shallow'; the diff compares against this.
166
+ local: { sourceKey, name: r.rel, sourceVersion, namespace, analysisDepth: analysisDepth ?? "shallow" },
167
+ entry: {
168
+ content,
169
+ name: r.entry.name ?? r.rel,
170
+ ...r.type !== void 0 && { type: r.type },
171
+ sourceKey,
172
+ sourceVersion,
173
+ ...namespace !== void 0 && { namespace },
174
+ ...Object.keys(metadata).length > 0 && { metadata },
175
+ ...analysisDepth !== void 0 && { analysisDepth }
176
+ }
177
+ });
178
+ }
179
+ return { docs, skippedByTransform };
180
+ }
181
+ var toEntry = (d) => ({ sourceKey: d.sourceKey, name: d.name });
182
+ function resolveNamespace(opts) {
183
+ const ns = normalizeNamespace(opts.namespace ?? (opts.dir ? nodePath2.basename(nodePath2.resolve(opts.dir)) : void 0));
184
+ if (ns === "") {
185
+ throw new Error("[BrainBox] brain.sync needs a non-empty `namespace` (it defaults to the synced dir's name; pass one for `sources` or a root dir). A namespace is owned by one sync root.");
186
+ }
187
+ return ns;
188
+ }
189
+ async function performSync(ctx, syncOpts, deps = {}) {
190
+ if (!syncOpts.dir && !syncOpts.sources) throw new Error("[BrainBox] brain.sync requires `dir` or `sources`.");
191
+ const opts = { ...syncOpts, namespace: resolveNamespace(syncOpts) };
192
+ const transform = opts.transform ? await loadTransform(opts.transform, process.cwd()) : void 0;
193
+ const { docs, skippedByTransform } = await collect(opts, transform);
194
+ const api = new BrainBoxApiClient(ctx.apiUrl, ctx.apiKey, noopLogger);
195
+ const { orgId, projectId } = opts.dryRun ? await lookupIds(api, ctx) : await resolveIds(api, ctx);
196
+ const projectMissing = projectId === void 0;
197
+ const listing = projectId === void 0 ? { sources: [], truncated: false } : await (deps.remote ?? executorLister(createBrainExecutor(ctx.apiUrl, ctx.apiKey, projectId))).listSources(opts.namespace);
198
+ const diff = diffSources(docs.map((d) => d.local), listing.sources);
199
+ if (listing.truncated) diff.deleted = [];
200
+ const result = {
201
+ dryRun: opts.dryRun ?? false,
202
+ namespace: opts.namespace,
203
+ ...projectMissing && { projectMissing: true },
204
+ ...listing.truncated && { listingTruncated: true },
205
+ added: diff.added.map(toEntry),
206
+ changed: diff.changed.map(toEntry),
207
+ unchanged: diff.unchanged.map(toEntry),
208
+ deleted: diff.deleted.map((d) => ({ sourceKey: d.sourceKey, title: d.title })),
209
+ pendingDeletes: [],
210
+ archived: [],
211
+ skippedByServer: [],
212
+ skippedByTransform
213
+ };
214
+ result.pendingDeletes = [...result.deleted];
215
+ if (opts.dryRun) return result;
216
+ if (projectId === void 0) throw new Error("[BrainBox] sync: project was not resolved");
217
+ const sendKeys = new Set([...diff.added, ...diff.changed, ...opts.force ? diff.unchanged : []].map((d) => d.sourceKey));
218
+ const toSend = docs.filter((d) => sendKeys.has(d.local.sourceKey)).map((d) => d.entry);
219
+ if (toSend.length > 0) {
220
+ result.ingest = await performIngest(ctx, {
221
+ docs: toSend,
222
+ ...opts.force ? { forceDocs: true } : {},
223
+ ...opts.timeoutMs !== void 0 ? { timeoutMs: opts.timeoutMs } : {},
224
+ ...opts.reviewOnly ? { reviewOnly: true } : {}
225
+ }, { orgId, projectId });
226
+ result.skippedByServer = result.ingest.stages.flatMap((s) => s.unchanged ?? []);
227
+ }
228
+ if (opts.prune && result.pendingDeletes.length > 0) {
229
+ const pruned = await prune(api, orgId, projectId, result.pendingDeletes.map((d) => d.sourceKey));
230
+ result.archived = pruned.archived;
231
+ const gone = /* @__PURE__ */ new Set([...pruned.archived, ...pruned.notFound]);
232
+ result.pendingDeletes = result.pendingDeletes.filter((d) => !gone.has(d.sourceKey));
233
+ }
234
+ return result;
235
+ }
236
+ async function prune(api, orgId, projectId, keys) {
237
+ const out = { archived: [], notFound: [] };
238
+ for (const key of keys) {
239
+ const r = await api.archiveWikiSource(orgId, projectId, validateSourceKey(key));
240
+ (r === "archived" ? out.archived : out.notFound).push(key);
241
+ }
242
+ return out;
243
+ }
244
+ async function performPrune(ctx, sourceKeys, ids) {
245
+ const api = new BrainBoxApiClient(ctx.apiUrl, ctx.apiKey, noopLogger);
246
+ const { orgId, projectId } = ids ?? await resolveIds(api, ctx);
247
+ return prune(api, orgId, projectId, sourceKeys);
248
+ }
249
+ export {
250
+ applyTransform,
251
+ computeSourceVersion,
252
+ deriveSourceKey,
253
+ diffSources,
254
+ executorLister,
255
+ frontmatterSourceKey,
256
+ loadTransform,
257
+ performPrune,
258
+ performSync,
259
+ validateSourceKey
260
+ };
@@ -0,0 +1,13 @@
1
+ import {
2
+ introspectTrinoSchema,
3
+ introspectTrinoSchemaWithConnection,
4
+ openTrinoConnection,
5
+ parseTrinoUrl
6
+ } from "./chunk-43LDD7YT.js";
7
+ import "./chunk-MLKGABMK.js";
8
+ export {
9
+ introspectTrinoSchema,
10
+ introspectTrinoSchemaWithConnection,
11
+ openTrinoConnection,
12
+ parseTrinoUrl
13
+ };
package/package.json CHANGED
@@ -1,6 +1,81 @@
1
1
  {
2
2
  "name": "@brainbox-labs/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.23.0",
4
+ "description": "BrainBox JavaScript/TypeScript SDK — MCP server + API client",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "bin": {
9
+ "brainbox-mcp": "./dist/bin.js"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "import": "./dist/index.js",
14
+ "types": "./dist/index.d.ts"
15
+ },
16
+ "./serve": {
17
+ "import": "./dist/serve/index.js",
18
+ "types": "./dist/serve/index.d.ts"
19
+ },
20
+ "./ingest": {
21
+ "import": "./dist/ingest/public.js",
22
+ "types": "./dist/ingest/public.d.ts"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "scripts": {
29
+ "build": "tsup",
30
+ "lint": "tsc --noEmit",
31
+ "test": "vitest run"
32
+ },
33
+ "dependencies": {
34
+ "@brainbox-labs/api": "^0.11.0",
35
+ "@brainbox-labs/types": "^1.34.0",
36
+ "@modelcontextprotocol/sdk": "^1.27.1",
37
+ "dotenv": "^16.4.5",
38
+ "express": "^5.0.0",
39
+ "glob": "^11.0.0",
40
+ "pg": "^8.13.3",
41
+ "pgsql-ast-parser": "^12.0.2"
42
+ },
43
+ "optionalDependencies": {
44
+ "@aws-sdk/client-athena": "^3.1088.0",
45
+ "@duckdb/node-api": "^1.5.3-r.3",
46
+ "better-sqlite3": "^12.10.0",
47
+ "mammoth": "^1.12.0",
48
+ "mysql2": "^3.11.3",
49
+ "pdf-parse": "^2.4.5",
50
+ "trino-client": "^0.2.9",
51
+ "turndown": "^7.2.4"
52
+ },
53
+ "devDependencies": {
54
+ "@types/better-sqlite3": "^7.6.13",
55
+ "@types/express": "^5.0.0",
56
+ "@types/pg": "^8.11.10",
57
+ "@types/turndown": "^5.0.6",
58
+ "tsup": "^8.1.0",
59
+ "typescript": "^5.4.5",
60
+ "vitest": "^2.0.0"
61
+ },
62
+ "engines": {
63
+ "node": ">=18"
64
+ },
65
+ "keywords": [
66
+ "brainbox",
67
+ "semantic-layer",
68
+ "sdk",
69
+ "mcp"
70
+ ],
71
+ "license": "Apache-2.0",
72
+ "repository": {
73
+ "type": "git",
74
+ "url": "git+https://github.com/brainbox-labs/ctx-layer-clients.git",
75
+ "directory": "packages/sdk"
76
+ },
77
+ "publishConfig": {
78
+ "registry": "https://registry.npmjs.org",
79
+ "access": "public"
80
+ }
81
+ }