@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.
- package/README.md +346 -2
- package/dist/athena-R67AV2DO.js +13 -0
- package/dist/bin.d.ts +1 -0
- package/dist/bin.js +57 -0
- package/dist/chunk-43LDD7YT.js +139 -0
- package/dist/chunk-4J77FNJJ.js +192 -0
- package/dist/chunk-AJR44IFE.js +47 -0
- package/dist/chunk-GVWDS5TG.js +112 -0
- package/dist/chunk-MF3BADT7.js +544 -0
- package/dist/chunk-MLKGABMK.js +9 -0
- package/dist/chunk-VEXUCOXR.js +387 -0
- package/dist/chunk-XFLBPF4A.js +169 -0
- package/dist/chunk-YRH35U57.js +178 -0
- package/dist/column-profiler-FJCAQQAS.js +23 -0
- package/dist/docs-loader-B2l0cO36.d.ts +25 -0
- package/dist/docs-loader-VA4KBG6Y.js +11 -0
- package/dist/index-qV0gq2eJ.d.ts +148 -0
- package/dist/index.d.ts +476 -0
- package/dist/index.js +523 -0
- package/dist/ingest/public.d.ts +178 -0
- package/dist/ingest/public.js +63 -0
- package/dist/ingest-DICRS7WW.js +13 -0
- package/dist/introspect-KQOOQEZM.js +11 -0
- package/dist/schema-reader-4ZVTUZIX.js +150 -0
- package/dist/serve/index.d.ts +2 -0
- package/dist/serve/index.js +8 -0
- package/dist/sql-parser-TB26PFXS.js +198 -0
- package/dist/sync-MXG4WALD.js +260 -0
- package/dist/trino-TUQ7CIRM.js +13 -0
- package/package.json +79 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,523 @@
|
|
|
1
|
+
import {
|
|
2
|
+
IngestPartialFailureError
|
|
3
|
+
} from "./chunk-XFLBPF4A.js";
|
|
4
|
+
import {
|
|
5
|
+
BrainBoxClient,
|
|
6
|
+
MCP,
|
|
7
|
+
discoverProjectsView,
|
|
8
|
+
isTenantKey,
|
|
9
|
+
serve_exports,
|
|
10
|
+
tenantViewFrom
|
|
11
|
+
} from "./chunk-MF3BADT7.js";
|
|
12
|
+
import {
|
|
13
|
+
BrainDispatchError,
|
|
14
|
+
WRITE_TOOL_NAMES,
|
|
15
|
+
createBrainExecutor,
|
|
16
|
+
createTenantBrainExecutor
|
|
17
|
+
} from "./chunk-GVWDS5TG.js";
|
|
18
|
+
import "./chunk-MLKGABMK.js";
|
|
19
|
+
|
|
20
|
+
// src/brain.ts
|
|
21
|
+
import {
|
|
22
|
+
BRAIN_TOOL_DEFS
|
|
23
|
+
} from "@brainbox-labs/types";
|
|
24
|
+
import { declaredKeyScope } from "@brainbox-labs/api";
|
|
25
|
+
|
|
26
|
+
// src/local-grep.ts
|
|
27
|
+
var WIKI_KINDS = ["entity-brief", "pattern", "person", "role", "account", "raw-source", "synthesis"];
|
|
28
|
+
var LIST_PAGE_SIZE = 20;
|
|
29
|
+
var MAX_PAGES_PER_KIND = 1e3;
|
|
30
|
+
var FETCH_CONCURRENCY = 8;
|
|
31
|
+
var DEFAULT_LIMIT = 20;
|
|
32
|
+
var MAX_LIMIT = 50;
|
|
33
|
+
var DEFAULT_CONTEXT = 2;
|
|
34
|
+
var MAX_CONTEXT = 10;
|
|
35
|
+
function clampInt(v, fallback, min, max) {
|
|
36
|
+
return typeof v === "number" && Number.isFinite(v) && v >= min ? Math.min(Math.floor(v), max) : fallback;
|
|
37
|
+
}
|
|
38
|
+
function buildMatcher(args) {
|
|
39
|
+
const source = args.regex === true ? args.pattern : args.pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
40
|
+
try {
|
|
41
|
+
return new RegExp(source, args.caseSensitive === true ? "" : "i");
|
|
42
|
+
} catch (err) {
|
|
43
|
+
throw new Error(`[BrainBox] grep_wiki: invalid regex: ${err instanceof Error ? err.message : String(err)}`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function grepBody(body, matcher, contextLines) {
|
|
47
|
+
const lines = body.split(/\r?\n/);
|
|
48
|
+
const out = [];
|
|
49
|
+
const headings = [];
|
|
50
|
+
let fence = null;
|
|
51
|
+
for (let i = 0; i < lines.length; i++) {
|
|
52
|
+
const text = lines[i];
|
|
53
|
+
const marker = /^\s*(`{3,}|~{3,})/.exec(text)?.[1]?.[0];
|
|
54
|
+
if (marker !== void 0) {
|
|
55
|
+
if (fence === null) fence = marker;
|
|
56
|
+
else if (fence === marker) fence = null;
|
|
57
|
+
} else if (fence === null) {
|
|
58
|
+
const h = /^(#{1,6})\s+(.*?)(?:\s+#+)?\s*$/.exec(text);
|
|
59
|
+
if (h) {
|
|
60
|
+
headings.length = Math.min(headings.length, h[1].length - 1);
|
|
61
|
+
headings.push(h[2]);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (!matcher.test(text)) continue;
|
|
65
|
+
out.push({
|
|
66
|
+
line: i + 1,
|
|
67
|
+
headingPath: [...headings],
|
|
68
|
+
snippet: lines.slice(Math.max(0, i - contextLines), i + contextLines + 1).join("\n")
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
async function inPool(items, size, fn) {
|
|
74
|
+
const results = new Array(items.length);
|
|
75
|
+
let next = 0;
|
|
76
|
+
const worker = async () => {
|
|
77
|
+
while (next < items.length) {
|
|
78
|
+
const i = next++;
|
|
79
|
+
results[i] = await fn(items[i]);
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
await Promise.all(Array.from({ length: Math.min(size, items.length) }, worker));
|
|
83
|
+
return results;
|
|
84
|
+
}
|
|
85
|
+
async function grepWikiLocal(args, exec, callOpts) {
|
|
86
|
+
if (typeof args?.pattern !== "string" || args.pattern.trim() === "") {
|
|
87
|
+
throw new Error("[BrainBox] grep_wiki: `pattern` is required");
|
|
88
|
+
}
|
|
89
|
+
const matcher = buildMatcher(args);
|
|
90
|
+
const limit = clampInt(args.limit, DEFAULT_LIMIT, 1, MAX_LIMIT);
|
|
91
|
+
const contextLines = clampInt(args.contextLines, DEFAULT_CONTEXT, 0, MAX_CONTEXT);
|
|
92
|
+
const grepKind = async (kind) => {
|
|
93
|
+
const found = [];
|
|
94
|
+
let kept = 0;
|
|
95
|
+
let total = 0;
|
|
96
|
+
let searched = 0;
|
|
97
|
+
let listed = 0;
|
|
98
|
+
let unpaged = false;
|
|
99
|
+
let cursor;
|
|
100
|
+
do {
|
|
101
|
+
const listArgs = { kind, limit: LIST_PAGE_SIZE, includeBody: true };
|
|
102
|
+
if (args.tag !== void 0) listArgs["tag"] = args.tag;
|
|
103
|
+
if (args.namespace !== void 0) listArgs["namespace"] = args.namespace;
|
|
104
|
+
if (cursor !== void 0) listArgs["cursor"] = cursor;
|
|
105
|
+
const res = await exec("list_wiki_pages", listArgs, callOpts);
|
|
106
|
+
listed += res.pages.length;
|
|
107
|
+
const bodies = await inPool(res.pages, FETCH_CONCURRENCY, async (page) => {
|
|
108
|
+
if (typeof page.body === "string") return page.body;
|
|
109
|
+
if (page.bodyUnavailable) return null;
|
|
110
|
+
try {
|
|
111
|
+
const got = await exec("get_wiki_page", { pageId: page.pageId }, callOpts);
|
|
112
|
+
return typeof got.body === "string" ? got.body : null;
|
|
113
|
+
} catch {
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
res.pages.forEach((page, i) => {
|
|
118
|
+
const body = bodies[i];
|
|
119
|
+
if (body === null || body === void 0) return;
|
|
120
|
+
searched++;
|
|
121
|
+
const hits = grepBody(body, matcher, contextLines);
|
|
122
|
+
total += hits.length;
|
|
123
|
+
if (hits.length > 0 && kept < limit) {
|
|
124
|
+
found.push({ pageId: page.pageId, title: page.title, updatedAt: page.updatedAt, hits });
|
|
125
|
+
kept += hits.length;
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
cursor = res.nextCursor;
|
|
129
|
+
if (cursor === void 0 && res.pages.length >= LIST_PAGE_SIZE && !res.pages.some((p) => typeof p.body === "string" || p.bodyUnavailable)) {
|
|
130
|
+
unpaged = true;
|
|
131
|
+
}
|
|
132
|
+
} while (cursor !== void 0 && listed < MAX_PAGES_PER_KIND);
|
|
133
|
+
return { found, total, searched, deep: unpaged || listed >= MAX_PAGES_PER_KIND };
|
|
134
|
+
};
|
|
135
|
+
const kinds = args.kind !== void 0 ? [args.kind] : [...WIKI_KINDS];
|
|
136
|
+
const perKind = [];
|
|
137
|
+
for (const kind of kinds) perKind.push(await grepKind(kind));
|
|
138
|
+
const ordered = perKind.flatMap((k) => k.found).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
|
139
|
+
const matches = [];
|
|
140
|
+
for (const page of ordered) {
|
|
141
|
+
for (const hit of page.hits) {
|
|
142
|
+
if (matches.length < limit) matches.push({ pageId: page.pageId, title: page.title, ...hit });
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
const totalMatches = perKind.reduce((n, k) => n + k.total, 0);
|
|
146
|
+
return {
|
|
147
|
+
matches,
|
|
148
|
+
totalMatches,
|
|
149
|
+
truncated: totalMatches > matches.length,
|
|
150
|
+
pagesSearched: perKind.reduce((n, k) => n + k.searched, 0),
|
|
151
|
+
pagesTruncated: perKind.some((k) => k.deep)
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// src/verb-namespace.ts
|
|
156
|
+
function cloneTool(t) {
|
|
157
|
+
const properties = {};
|
|
158
|
+
for (const [k, v] of Object.entries(t.inputSchema.properties)) {
|
|
159
|
+
properties[k] = { type: v.type, description: v.description };
|
|
160
|
+
if (v.enum !== void 0) properties[k].enum = [...v.enum];
|
|
161
|
+
if (v.items !== void 0) properties[k].items = v.items;
|
|
162
|
+
}
|
|
163
|
+
const inputSchema = {
|
|
164
|
+
type: t.inputSchema.type,
|
|
165
|
+
// additionalProperties:true prevents @ai-sdk/google from returning undefined
|
|
166
|
+
// for no-param tools (isEmptyObjectSchema check), which causes Vertex AI to
|
|
167
|
+
// reject with "parameters schema should be of type OBJECT". Ignored by all
|
|
168
|
+
// other SDKs (Anthropic, OpenAI, raw MCP).
|
|
169
|
+
additionalProperties: true,
|
|
170
|
+
properties
|
|
171
|
+
};
|
|
172
|
+
if (t.inputSchema.required !== void 0) {
|
|
173
|
+
inputSchema.required = [...t.inputSchema.required];
|
|
174
|
+
}
|
|
175
|
+
return { name: t.name, description: t.description, inputSchema };
|
|
176
|
+
}
|
|
177
|
+
function buildVerbNamespace(tools, executor, local = {}) {
|
|
178
|
+
const call = (name, args, callOpts) => {
|
|
179
|
+
const handler = local[name];
|
|
180
|
+
if (handler) return handler(args, callOpts);
|
|
181
|
+
return callOpts !== void 0 ? executor(name, args, callOpts) : executor(name, args);
|
|
182
|
+
};
|
|
183
|
+
const ns = {
|
|
184
|
+
asTools: () => tools.map((t) => ({
|
|
185
|
+
...cloneTool(t),
|
|
186
|
+
execute: (args = {}, callOpts) => call(t.name, args, callOpts)
|
|
187
|
+
}))
|
|
188
|
+
};
|
|
189
|
+
for (const tool of tools) {
|
|
190
|
+
ns[tool.name] = (args = {}, callOpts) => call(tool.name, args, callOpts);
|
|
191
|
+
}
|
|
192
|
+
return Object.freeze(ns);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// src/brain.ts
|
|
196
|
+
var DEFAULT_API_URL = "https://ctx.brainbox-ai.app";
|
|
197
|
+
function isDebugEnabled() {
|
|
198
|
+
return process.env["DEBUG"]?.split(",").some((s) => s.trim() === "brainbox") === true;
|
|
199
|
+
}
|
|
200
|
+
var CUID2_RE = /^[a-z][a-z0-9]{23}$/;
|
|
201
|
+
var LEGACY_DOMAIN_TOOLS = /* @__PURE__ */ new Set([
|
|
202
|
+
"recall_concepts",
|
|
203
|
+
"explain_concept",
|
|
204
|
+
"define_terms",
|
|
205
|
+
"find_governing_rules",
|
|
206
|
+
"explore_workflows",
|
|
207
|
+
"trace_workflow",
|
|
208
|
+
"list_metrics",
|
|
209
|
+
"explain_metric",
|
|
210
|
+
"understand_connections"
|
|
211
|
+
]);
|
|
212
|
+
var LOCAL_VERBS = /* @__PURE__ */ new Set(["grep_wiki"]);
|
|
213
|
+
var SURFACED_TOOLS = BRAIN_TOOL_DEFS.filter((t) => !LEGACY_DOMAIN_TOOLS.has(t.name));
|
|
214
|
+
function brainToolToMcp(t) {
|
|
215
|
+
const properties = {};
|
|
216
|
+
const required = [];
|
|
217
|
+
for (const p of t.params) {
|
|
218
|
+
const prop = { type: p.type, description: p.description };
|
|
219
|
+
if (p.enum !== void 0) prop.enum = p.enum;
|
|
220
|
+
if (p.items !== void 0) prop.items = p.items;
|
|
221
|
+
properties[p.name] = prop;
|
|
222
|
+
if (p.required) required.push(p.name);
|
|
223
|
+
}
|
|
224
|
+
const inputSchema = { type: "object", properties };
|
|
225
|
+
if (required.length > 0) inputSchema.required = required;
|
|
226
|
+
return { name: t.name, description: t.description, inputSchema };
|
|
227
|
+
}
|
|
228
|
+
var SERVER_GREP_WIKI = SURFACED_TOOLS.find((t) => t.name === "grep_wiki");
|
|
229
|
+
var GREP_WIKI_TOOL = SERVER_GREP_WIKI && (() => {
|
|
230
|
+
const t = brainToolToMcp(SERVER_GREP_WIKI);
|
|
231
|
+
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.";
|
|
232
|
+
t.inputSchema.properties["namespace"] = {
|
|
233
|
+
type: "string",
|
|
234
|
+
description: "Only search this namespace and everything nested under it. Mutually exclusive with tag."
|
|
235
|
+
};
|
|
236
|
+
return t;
|
|
237
|
+
})();
|
|
238
|
+
var RECALL_TOOLS = [
|
|
239
|
+
...SURFACED_TOOLS.filter((t) => !WRITE_TOOL_NAMES.has(t.name) && t.name !== "grep_wiki").map(brainToolToMcp),
|
|
240
|
+
...GREP_WIKI_TOOL ? [GREP_WIKI_TOOL] : []
|
|
241
|
+
];
|
|
242
|
+
var UPDATE_TOOLS = SURFACED_TOOLS.filter((t) => WRITE_TOOL_NAMES.has(t.name)).map(brainToolToMcp);
|
|
243
|
+
function deprecatedUpdateVerbs(update) {
|
|
244
|
+
return {
|
|
245
|
+
append_wiki_page: (args = {}, callOpts) => {
|
|
246
|
+
const a = args;
|
|
247
|
+
return update["save_wiki_page"]({ mode: "append", id: a.pageId, body: a.text, baseVersion: a.baseVersion }, callOpts);
|
|
248
|
+
},
|
|
249
|
+
flag_personal_page_for_review: (args = {}, callOpts) => {
|
|
250
|
+
const { pageId, ...rest } = args;
|
|
251
|
+
return update["save_personal_page"]({ ...rest, id: pageId, flagForReview: true }, callOpts);
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
function withProjectIdParam(tool) {
|
|
256
|
+
tool.inputSchema.properties["projectId"] = {
|
|
257
|
+
type: "string",
|
|
258
|
+
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."
|
|
259
|
+
};
|
|
260
|
+
const execute = tool.execute;
|
|
261
|
+
tool.execute = (args = {}, callOpts) => {
|
|
262
|
+
const { projectId, ...rest } = args;
|
|
263
|
+
const fromModel = typeof projectId === "string" && projectId.trim() !== "" ? projectId.trim() : void 0;
|
|
264
|
+
return execute(rest, fromModel !== void 0 && callOpts?.projectId === void 0 ? { ...callOpts, projectId: fromModel } : callOpts);
|
|
265
|
+
};
|
|
266
|
+
return tool;
|
|
267
|
+
}
|
|
268
|
+
var BrainBox = class {
|
|
269
|
+
constructor(options) {
|
|
270
|
+
this.options = options;
|
|
271
|
+
this.serve = new BrainBoxServe(options);
|
|
272
|
+
const lazyExecutor = async (toolName, args, callOpts) => {
|
|
273
|
+
const exec = await this.getExecutor();
|
|
274
|
+
try {
|
|
275
|
+
return await (callOpts !== void 0 ? exec(toolName, args, callOpts) : exec(toolName, args));
|
|
276
|
+
} catch (err) {
|
|
277
|
+
throw await this.explainDisabledTool(toolName, err);
|
|
278
|
+
}
|
|
279
|
+
};
|
|
280
|
+
const recall = buildVerbNamespace(RECALL_TOOLS, lazyExecutor, {
|
|
281
|
+
grep_wiki: (args, callOpts) => grepWikiLocal(args, lazyExecutor, callOpts)
|
|
282
|
+
});
|
|
283
|
+
const update = buildVerbNamespace(UPDATE_TOOLS, lazyExecutor);
|
|
284
|
+
const recallTools = isTenantKey(options.apiKey) ? () => [...recall.asTools().map(withProjectIdParam), this.listProjectsTool()] : () => recall.asTools();
|
|
285
|
+
this.recall = Object.freeze({
|
|
286
|
+
...recall,
|
|
287
|
+
asTools: recallTools,
|
|
288
|
+
asEnabledTools: () => this.enabledTools(recallTools())
|
|
289
|
+
});
|
|
290
|
+
this.update = Object.freeze({
|
|
291
|
+
...update,
|
|
292
|
+
...deprecatedUpdateVerbs(update),
|
|
293
|
+
asEnabledTools: () => this.enabledTools(update.asTools())
|
|
294
|
+
});
|
|
295
|
+
this.projects = {
|
|
296
|
+
list: async () => (await this.getDiscovery()).projects,
|
|
297
|
+
create: (name) => {
|
|
298
|
+
this.assertNotTenantKey("projects.create");
|
|
299
|
+
return this.client().createProject(name, this.options.org).finally(() => {
|
|
300
|
+
this.discoveryPromise = void 0;
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
options;
|
|
306
|
+
serve;
|
|
307
|
+
recall;
|
|
308
|
+
update;
|
|
309
|
+
projects;
|
|
310
|
+
projectIdPromise;
|
|
311
|
+
tenantViewPromise;
|
|
312
|
+
discoveryPromise;
|
|
313
|
+
executor;
|
|
314
|
+
/**
|
|
315
|
+
* GET /api/projects for any key type: the addressable projects plus the tools
|
|
316
|
+
* this org has switched off. A successful fetch is cached; a failed one is
|
|
317
|
+
* cleared so the next call retries.
|
|
318
|
+
*/
|
|
319
|
+
getDiscovery() {
|
|
320
|
+
this.discoveryPromise ??= discoverProjectsView(
|
|
321
|
+
this.options.apiUrl ?? DEFAULT_API_URL,
|
|
322
|
+
this.options.apiKey
|
|
323
|
+
).catch((err) => {
|
|
324
|
+
this.discoveryPromise = void 0;
|
|
325
|
+
throw err;
|
|
326
|
+
});
|
|
327
|
+
return this.discoveryPromise;
|
|
328
|
+
}
|
|
329
|
+
/** Tenant-key agents call this first to find the base Brains they can pass as `projectId`. */
|
|
330
|
+
listProjectsTool() {
|
|
331
|
+
return {
|
|
332
|
+
name: "list_projects",
|
|
333
|
+
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.',
|
|
334
|
+
inputSchema: { type: "object", additionalProperties: true, properties: {} },
|
|
335
|
+
execute: async () => ({ projects: await this.projects.list() })
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
/** Best-effort: discovery failing must never hide tools, so an error means "nothing disabled". */
|
|
339
|
+
async getDisabledTools() {
|
|
340
|
+
try {
|
|
341
|
+
return new Set((await this.getDiscovery()).disabledTools);
|
|
342
|
+
} catch {
|
|
343
|
+
return /* @__PURE__ */ new Set();
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
/** Drops tools this org has switched off. Local verbs (grep_wiki) never hit the gated server tool, so they stay. */
|
|
347
|
+
async enabledTools(tools) {
|
|
348
|
+
const disabled = await this.getDisabledTools();
|
|
349
|
+
return tools.filter((t) => !disabled.has(t.name) || LOCAL_VERBS.has(t.name));
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* A gated tool fails with a bare dispatch 403. Only on that failure, look up
|
|
353
|
+
* the org's disabled set (no extra request on the happy path) and replace the
|
|
354
|
+
* error with a clear one if the tool is in it.
|
|
355
|
+
*/
|
|
356
|
+
async explainDisabledTool(toolName, err) {
|
|
357
|
+
if (!(err instanceof BrainDispatchError) || err.status !== 403) return err;
|
|
358
|
+
if ((await this.getDisabledTools()).has(toolName)) {
|
|
359
|
+
return new BrainDispatchError(err.status, err.toolName, err.body, {
|
|
360
|
+
message: `[BrainBox] ${toolName} is not enabled for this org. Ask an org admin to enable it.`
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
return err;
|
|
364
|
+
}
|
|
365
|
+
client() {
|
|
366
|
+
return new BrainBoxClient({
|
|
367
|
+
apiUrl: this.options.apiUrl ?? DEFAULT_API_URL,
|
|
368
|
+
apiKey: this.options.apiKey
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
/** Tenant keys see projects through the overlay/base view, and POST /projects returns their existing overlay instead of creating. */
|
|
372
|
+
assertNotTenantKey(op) {
|
|
373
|
+
if (isTenantKey(this.options.apiKey)) {
|
|
374
|
+
throw new Error(`[BrainBox] brain.${op} is not available for tenant keys \u2014 use an org or project key.`);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Ingest sources into this brain — equivalent to running `brainbox meta ingest`
|
|
379
|
+
* + `repo push` + `repo meta create` + `repo meta approve`. Blocks until each
|
|
380
|
+
* stage's context is activated and a new version is published.
|
|
381
|
+
*
|
|
382
|
+
* For tenant keys, always targets the tenant's overlay project — `project`
|
|
383
|
+
* on the parent {@link BrainBox} handle is ignored, since base projects are
|
|
384
|
+
* shared, read-only brains that a tenant must never write into. For
|
|
385
|
+
* project/org keys, requires `project` on the parent handle.
|
|
386
|
+
*/
|
|
387
|
+
async ingest(opts) {
|
|
388
|
+
const ctx = await this.ingestContext("ingest");
|
|
389
|
+
const { performIngest } = await import("./ingest-DICRS7WW.js");
|
|
390
|
+
return performIngest(ctx, opts);
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* Sync a folder (or explicit sources) with this brain by stable `sourceKey`: list what the
|
|
394
|
+
* brain holds, ingest new and changed docs in one batch, and report docs deleted locally as
|
|
395
|
+
* `pendingDeletes`. Nothing is archived unless `prune: true`; apply a user's decision later
|
|
396
|
+
* with {@link BrainBox.prune}. Targets the handle's `project` like {@link BrainBox.ingest};
|
|
397
|
+
* tenant keys are not supported yet.
|
|
398
|
+
*
|
|
399
|
+
* `namespace` defaults to the synced dir's basename and is owned by this one sync root: deletes
|
|
400
|
+
* are computed against every keyed raw-source page in exactly that namespace, so other writers
|
|
401
|
+
* into it show up as pending deletes.
|
|
402
|
+
*/
|
|
403
|
+
async sync(opts) {
|
|
404
|
+
if (isTenantKey(this.options.apiKey)) {
|
|
405
|
+
throw new Error("[BrainBox] brain.sync does not support tenant keys yet. Use a project or org key.");
|
|
406
|
+
}
|
|
407
|
+
const ctx = await this.ingestContext("sync");
|
|
408
|
+
const { performSync } = await import("./sync-MXG4WALD.js");
|
|
409
|
+
return performSync(ctx, opts);
|
|
410
|
+
}
|
|
411
|
+
/** Archive the synced pages for these `sourceKey`s (soft, reversible server-side). Unknown keys come back in `notFound`. */
|
|
412
|
+
async prune(sourceKeys) {
|
|
413
|
+
const ctx = await this.ingestContext("prune");
|
|
414
|
+
const { performPrune } = await import("./sync-MXG4WALD.js");
|
|
415
|
+
return performPrune(ctx, sourceKeys);
|
|
416
|
+
}
|
|
417
|
+
/** Target for write-side calls: a tenant key's overlay project, else the handle's `project`. */
|
|
418
|
+
async ingestContext(op) {
|
|
419
|
+
const apiUrl = this.options.apiUrl ?? DEFAULT_API_URL;
|
|
420
|
+
this.logDeclaredScope(op);
|
|
421
|
+
if (isTenantKey(this.options.apiKey)) {
|
|
422
|
+
const view = await this.getTenantView();
|
|
423
|
+
this.logConfirmedScope(op, "tenant", `overlay=${view.overlay.projectId}`);
|
|
424
|
+
return { apiUrl, apiKey: this.options.apiKey, org: this.options.org, project: view.overlay.projectId };
|
|
425
|
+
}
|
|
426
|
+
if (!this.options.project) {
|
|
427
|
+
throw new Error(
|
|
428
|
+
`[BrainBox] brain.${op} requires a project. Pass \`project\` to new BrainBox({...}).`
|
|
429
|
+
);
|
|
430
|
+
}
|
|
431
|
+
return { apiUrl, apiKey: this.options.apiKey, org: this.options.org, project: this.options.project };
|
|
432
|
+
}
|
|
433
|
+
async getExecutor() {
|
|
434
|
+
this.logDeclaredScope("recall/update");
|
|
435
|
+
if (this.executor) return this.executor;
|
|
436
|
+
const apiUrl = this.options.apiUrl ?? DEFAULT_API_URL;
|
|
437
|
+
if (isTenantKey(this.options.apiKey)) {
|
|
438
|
+
const view = await this.getTenantView();
|
|
439
|
+
this.logConfirmedScope("recall/update", "tenant", `overlay=${view.overlay.projectId}, bases=${view.bases.length}`);
|
|
440
|
+
this.executor = createTenantBrainExecutor(apiUrl, this.options.apiKey, view);
|
|
441
|
+
return this.executor;
|
|
442
|
+
}
|
|
443
|
+
if (!this.options.project) {
|
|
444
|
+
throw new Error(
|
|
445
|
+
"[BrainBox] recall/update require a project. Pass `project` to new BrainBox({...})."
|
|
446
|
+
);
|
|
447
|
+
}
|
|
448
|
+
const projectId = await this.resolveProjectId(this.options.project);
|
|
449
|
+
this.logConfirmedScope("recall/update", "project", `projectId=${projectId}`);
|
|
450
|
+
this.executor = createBrainExecutor(apiUrl, this.options.apiKey, projectId);
|
|
451
|
+
return this.executor;
|
|
452
|
+
}
|
|
453
|
+
/** Best-effort scope label from the key prefix alone — logged before any network call. */
|
|
454
|
+
logDeclaredScope(caller) {
|
|
455
|
+
if (!isDebugEnabled()) return;
|
|
456
|
+
const scope = declaredKeyScope(this.options.apiKey) ?? "unknown";
|
|
457
|
+
console.log(`[BrainBox] ${caller} \u2192 org=${this.options.org} scope=${scope} (declared)`);
|
|
458
|
+
}
|
|
459
|
+
/** Backend-confirmed scope, logged once a resolving call (tenant view / project lookup) succeeds. */
|
|
460
|
+
logConfirmedScope(caller, scope, detail) {
|
|
461
|
+
if (!isDebugEnabled()) return;
|
|
462
|
+
console.log(`[BrainBox] ${caller} \u2192 scope=${scope} (confirmed): ${detail}`);
|
|
463
|
+
}
|
|
464
|
+
/**
|
|
465
|
+
* Resolves a tenant key's view (overlay + readable bases) from the cached GET /api/projects.
|
|
466
|
+
* A successful resolve is cached; a failed resolve is cleared so the next call
|
|
467
|
+
* retries instead of replaying the rejection.
|
|
468
|
+
*/
|
|
469
|
+
getTenantView() {
|
|
470
|
+
this.tenantViewPromise ??= this.getDiscovery().then((d) => tenantViewFrom(d.projects)).catch((err) => {
|
|
471
|
+
this.tenantViewPromise = void 0;
|
|
472
|
+
throw err;
|
|
473
|
+
});
|
|
474
|
+
return this.tenantViewPromise;
|
|
475
|
+
}
|
|
476
|
+
resolveProjectId(project) {
|
|
477
|
+
if (CUID2_RE.test(project)) return Promise.resolve(project);
|
|
478
|
+
this.projectIdPromise ??= (() => {
|
|
479
|
+
return this.client().resolveProjectId(project, this.options.org).catch((err) => {
|
|
480
|
+
this.projectIdPromise = void 0;
|
|
481
|
+
throw err;
|
|
482
|
+
});
|
|
483
|
+
})();
|
|
484
|
+
return this.projectIdPromise;
|
|
485
|
+
}
|
|
486
|
+
};
|
|
487
|
+
var BrainBoxServe = class {
|
|
488
|
+
constructor(handle) {
|
|
489
|
+
this.handle = handle;
|
|
490
|
+
}
|
|
491
|
+
handle;
|
|
492
|
+
/**
|
|
493
|
+
* Build an MCP server bound to this brain. Returns an unstarted MCP
|
|
494
|
+
* instance — call `.start({ port })` to begin serving.
|
|
495
|
+
*
|
|
496
|
+
* A `project` is required on the parent {@link BrainBox} handle until
|
|
497
|
+
* org-level default brains are supported by the server runtime — except
|
|
498
|
+
* for tenant keys, which discover their overlay + base projects at
|
|
499
|
+
* `start()` time via GET /api/projects instead.
|
|
500
|
+
*/
|
|
501
|
+
mcp(opts = {}) {
|
|
502
|
+
if (!this.handle.project && !isTenantKey(this.handle.apiKey)) {
|
|
503
|
+
throw new Error(
|
|
504
|
+
"[BrainBox] serve.mcp() requires a project. Pass `project` to new BrainBox({...})."
|
|
505
|
+
);
|
|
506
|
+
}
|
|
507
|
+
const merged = {
|
|
508
|
+
apiKey: this.handle.apiKey,
|
|
509
|
+
...this.handle.project !== void 0 ? { project: this.handle.project } : {},
|
|
510
|
+
...opts
|
|
511
|
+
};
|
|
512
|
+
if (this.handle.apiUrl !== void 0) merged.apiUrl = this.handle.apiUrl;
|
|
513
|
+
return new MCP(merged);
|
|
514
|
+
}
|
|
515
|
+
};
|
|
516
|
+
export {
|
|
517
|
+
BrainBox,
|
|
518
|
+
BrainBoxServe,
|
|
519
|
+
BrainDispatchError,
|
|
520
|
+
IngestPartialFailureError,
|
|
521
|
+
isTenantKey,
|
|
522
|
+
serve_exports as serve
|
|
523
|
+
};
|