@brainbox-labs/sdk 0.22.1 → 0.23.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/bin.js +2 -1
- package/dist/chunk-4J77FNJJ.js +192 -0
- package/dist/chunk-GVWDS5TG.js +112 -0
- package/dist/{chunk-YWH6IOQG.js → chunk-MF3BADT7.js} +4 -110
- package/dist/{chunk-OOHPBQXX.js → chunk-XFLBPF4A.js} +23 -6
- package/dist/docs-loader-B2l0cO36.d.ts +25 -0
- package/dist/{docs-loader-VMBVV44Y.js → docs-loader-VA4KBG6Y.js} +5 -3
- package/dist/index.d.ts +92 -3
- package/dist/index.js +47 -28
- package/dist/ingest/public.d.ts +3 -7
- package/dist/ingest/public.js +8 -8
- package/dist/ingest-DICRS7WW.js +13 -0
- package/dist/serve/index.js +2 -1
- package/dist/sync-K4NBZBF3.js +265 -0
- package/package.json +3 -3
- package/dist/chunk-ANGBZHCB.js +0 -120
- package/dist/ingest-OA6KWJNR.js +0 -9
package/dist/bin.js
CHANGED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// src/ingest/docs-loader.ts
|
|
2
|
+
import * as fs2 from "fs/promises";
|
|
3
|
+
import * as nodePath2 from "path";
|
|
4
|
+
import { glob } from "glob";
|
|
5
|
+
|
|
6
|
+
// src/ingest/doc-converter.ts
|
|
7
|
+
import * as fs from "fs/promises";
|
|
8
|
+
import * as nodePath from "path";
|
|
9
|
+
function needsConversion(filePath) {
|
|
10
|
+
const ext = nodePath.extname(filePath).toLowerCase();
|
|
11
|
+
return ext === ".pdf" || ext === ".docx" || ext === ".html" || ext === ".htm";
|
|
12
|
+
}
|
|
13
|
+
async function htmlToMarkdown(html) {
|
|
14
|
+
const TurndownService = (await import("turndown")).default;
|
|
15
|
+
const td = new TurndownService({ headingStyle: "atx", codeBlockStyle: "fenced" });
|
|
16
|
+
return td.turndown(html);
|
|
17
|
+
}
|
|
18
|
+
async function convertToMarkdown(filePath) {
|
|
19
|
+
const ext = nodePath.extname(filePath).toLowerCase();
|
|
20
|
+
if (ext === ".docx") {
|
|
21
|
+
const mammoth = await import("mammoth");
|
|
22
|
+
const result = await mammoth.convertToHtml({ path: filePath });
|
|
23
|
+
const warnings = result.messages.filter((m) => m.type === "warning").map((m) => m.message);
|
|
24
|
+
if (warnings.length > 0) {
|
|
25
|
+
process.stderr.write(`mammoth warnings for ${nodePath.basename(filePath)}:
|
|
26
|
+
${warnings.join("\n")}
|
|
27
|
+
`);
|
|
28
|
+
}
|
|
29
|
+
return htmlToMarkdown(result.value);
|
|
30
|
+
}
|
|
31
|
+
if (ext === ".html" || ext === ".htm") {
|
|
32
|
+
const html = await fs.readFile(filePath, "utf-8");
|
|
33
|
+
return htmlToMarkdown(html);
|
|
34
|
+
}
|
|
35
|
+
if (ext === ".pdf") {
|
|
36
|
+
const { PDFParse } = await import("pdf-parse");
|
|
37
|
+
const buffer = await fs.readFile(filePath);
|
|
38
|
+
const parser = new PDFParse({ data: buffer });
|
|
39
|
+
try {
|
|
40
|
+
const result = await parser.getText();
|
|
41
|
+
return result.text;
|
|
42
|
+
} finally {
|
|
43
|
+
await parser.destroy();
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
throw new Error(`No converter available for extension "${ext}"`);
|
|
47
|
+
}
|
|
48
|
+
function convertedName(filePath) {
|
|
49
|
+
return nodePath.basename(filePath) + ".md";
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// src/sync/keys.ts
|
|
53
|
+
import { createHash } from "crypto";
|
|
54
|
+
var MAX_KEY_LENGTH = 256;
|
|
55
|
+
function validateSourceKey(raw, where = "sourceKey") {
|
|
56
|
+
if (typeof raw !== "string") throw new Error(`[BrainBox] ${where} must be a string`);
|
|
57
|
+
const key = raw.trim();
|
|
58
|
+
if (key === "") throw new Error(`[BrainBox] ${where} must not be empty`);
|
|
59
|
+
if (key.length > MAX_KEY_LENGTH) throw new Error(`[BrainBox] ${where} "${key.slice(0, 40)}\u2026" is longer than ${MAX_KEY_LENGTH} characters`);
|
|
60
|
+
if (key.includes("/")) throw new Error(`[BrainBox] ${where} "${key}" must not contain "/"`);
|
|
61
|
+
return key;
|
|
62
|
+
}
|
|
63
|
+
function normalizeNamespace(ns) {
|
|
64
|
+
return (ns ?? "").trim().replace(/^\/+|\/+$/g, "");
|
|
65
|
+
}
|
|
66
|
+
function deriveSourceKey(relPath, namespace) {
|
|
67
|
+
const posix = relPath.split("\\").join("/").replace(/^\.\//, "").replace(/^\/+/, "");
|
|
68
|
+
const ns = normalizeNamespace(namespace);
|
|
69
|
+
const full = ns === "" ? posix : `${ns}/${posix}`;
|
|
70
|
+
const encoded = full.replace(/%/g, "%25").replace(/\//g, "%2F").trim();
|
|
71
|
+
if (encoded.length <= MAX_KEY_LENGTH) return validateSourceKey(encoded);
|
|
72
|
+
const digest = createHash("sha256").update(encoded).digest("hex").slice(0, 16);
|
|
73
|
+
return `${encoded.slice(0, 200)}~${digest}`;
|
|
74
|
+
}
|
|
75
|
+
function frontmatterSourceKey(content) {
|
|
76
|
+
const fm = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(content);
|
|
77
|
+
if (!fm) return void 0;
|
|
78
|
+
const line = /^sourceKey:[ \t]*(.*)$/m.exec(fm[1]);
|
|
79
|
+
if (!line) return void 0;
|
|
80
|
+
const value = line[1].trim().replace(/^(['"])(.*)\1$/, "$2");
|
|
81
|
+
return validateSourceKey(value, "frontmatter sourceKey");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// src/ingest/docs-loader.ts
|
|
85
|
+
var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
86
|
+
".png",
|
|
87
|
+
".jpg",
|
|
88
|
+
".jpeg",
|
|
89
|
+
".gif",
|
|
90
|
+
".bmp",
|
|
91
|
+
".zip",
|
|
92
|
+
".tar",
|
|
93
|
+
".gz",
|
|
94
|
+
".bz2",
|
|
95
|
+
".7z",
|
|
96
|
+
".exe",
|
|
97
|
+
".dll",
|
|
98
|
+
".so",
|
|
99
|
+
".bin"
|
|
100
|
+
]);
|
|
101
|
+
var CONVERT_EXTENSIONS = /* @__PURE__ */ new Set([".pdf", ".docx"]);
|
|
102
|
+
function inferType(filePath) {
|
|
103
|
+
const ext = nodePath2.extname(filePath).toLowerCase();
|
|
104
|
+
if (ext === ".md" || ext === ".markdown") return "markdown";
|
|
105
|
+
if (ext === ".html" || ext === ".htm") return "html";
|
|
106
|
+
return "text";
|
|
107
|
+
}
|
|
108
|
+
async function loadDocFile(file, outputDir) {
|
|
109
|
+
const ext = nodePath2.extname(file).toLowerCase();
|
|
110
|
+
if (BINARY_EXTENSIONS.has(ext)) {
|
|
111
|
+
throw new Error(
|
|
112
|
+
`Unsupported file type "${ext}" for "${file}". Convert to markdown/text before passing to brain.ingest.`
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
if (CONVERT_EXTENSIONS.has(ext)) {
|
|
116
|
+
const content = await convertToMarkdown(file);
|
|
117
|
+
const name = convertedName(file);
|
|
118
|
+
if (outputDir) {
|
|
119
|
+
await fs2.writeFile(nodePath2.join(outputDir, name), content, "utf-8");
|
|
120
|
+
}
|
|
121
|
+
return { name, content, type: "markdown" };
|
|
122
|
+
}
|
|
123
|
+
return { name: nodePath2.basename(file), content: await fs2.readFile(file, "utf-8"), type: inferType(file) };
|
|
124
|
+
}
|
|
125
|
+
function entryToSource(entry, loaded, defaultDepth) {
|
|
126
|
+
const key = entry.sourceKey !== void 0 ? validateSourceKey(entry.sourceKey) : void 0;
|
|
127
|
+
const depth = entry.analysisDepth ?? defaultDepth;
|
|
128
|
+
const name = entry.name ?? loaded.name;
|
|
129
|
+
return {
|
|
130
|
+
id: key ?? name,
|
|
131
|
+
name,
|
|
132
|
+
content: loaded.content,
|
|
133
|
+
type: entry.type ?? loaded.type,
|
|
134
|
+
...key !== void 0 && { sourceKey: key },
|
|
135
|
+
...entry.sourceVersion !== void 0 && { sourceVersion: entry.sourceVersion },
|
|
136
|
+
...entry.namespace !== void 0 && { namespace: entry.namespace },
|
|
137
|
+
...entry.metadata !== void 0 && { metadata: entry.metadata },
|
|
138
|
+
...depth && { analysisDepth: depth }
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
async function expandDocPatterns(patterns, outputDir, analysisDepth) {
|
|
142
|
+
if (outputDir) {
|
|
143
|
+
await fs2.mkdir(outputDir, { recursive: true });
|
|
144
|
+
}
|
|
145
|
+
const sources = [];
|
|
146
|
+
const seen = /* @__PURE__ */ new Set();
|
|
147
|
+
const keys = /* @__PURE__ */ new Set();
|
|
148
|
+
const push = (s) => {
|
|
149
|
+
if (s.sourceKey !== void 0) {
|
|
150
|
+
if (keys.has(s.sourceKey)) throw new Error(`[BrainBox] duplicate sourceKey "${s.sourceKey}" in docs`);
|
|
151
|
+
keys.add(s.sourceKey);
|
|
152
|
+
}
|
|
153
|
+
sources.push(s);
|
|
154
|
+
};
|
|
155
|
+
for (const pattern of patterns) {
|
|
156
|
+
if (typeof pattern !== "string" && pattern.content !== void 0) {
|
|
157
|
+
const name = pattern.name ?? pattern.sourceKey;
|
|
158
|
+
if (name === void 0) throw new Error("[BrainBox] a docs entry with inline `content` needs a `name` or `sourceKey`");
|
|
159
|
+
push(entryToSource(pattern, { name, content: pattern.content, type: inferType(name) }, analysisDepth));
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
const entry = typeof pattern === "string" ? { path: pattern } : pattern;
|
|
163
|
+
if (entry.path === void 0) throw new Error("[BrainBox] a docs entry needs `path` or `content`");
|
|
164
|
+
const matches = await glob(entry.path, { nodir: true, absolute: true });
|
|
165
|
+
if (entry.sourceKey !== void 0 && matches.length !== 1) {
|
|
166
|
+
throw new Error(`[BrainBox] docs entry with sourceKey "${entry.sourceKey}" must match exactly one file; "${entry.path}" matched ${matches.length}`);
|
|
167
|
+
}
|
|
168
|
+
for (const file of matches) {
|
|
169
|
+
if (seen.has(file)) continue;
|
|
170
|
+
seen.add(file);
|
|
171
|
+
push(entryToSource(entry, await loadDocFile(file, outputDir), analysisDepth));
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return sources;
|
|
175
|
+
}
|
|
176
|
+
function inlineText(text, analysisDepth) {
|
|
177
|
+
return { id: "inline.txt", name: "inline.txt", content: text, type: "text", ...analysisDepth && { analysisDepth } };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export {
|
|
181
|
+
needsConversion,
|
|
182
|
+
htmlToMarkdown,
|
|
183
|
+
convertToMarkdown,
|
|
184
|
+
convertedName,
|
|
185
|
+
validateSourceKey,
|
|
186
|
+
normalizeNamespace,
|
|
187
|
+
deriveSourceKey,
|
|
188
|
+
frontmatterSourceKey,
|
|
189
|
+
loadDocFile,
|
|
190
|
+
expandDocPatterns,
|
|
191
|
+
inlineText
|
|
192
|
+
};
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// src/serve/connectors/brain.ts
|
|
2
|
+
import { BRAIN_TOOL_DEFS } from "@brainbox-labs/types";
|
|
3
|
+
var WRITE_TOOL_NAMES = new Set(
|
|
4
|
+
BRAIN_TOOL_DEFS.filter((t) => !t.annotations.readOnlyHint).map((t) => t.name)
|
|
5
|
+
);
|
|
6
|
+
var DESTRUCTIVE_TOOL_NAMES = new Set(
|
|
7
|
+
BRAIN_TOOL_DEFS.filter((t) => t.annotations.destructiveHint).map((t) => t.name)
|
|
8
|
+
);
|
|
9
|
+
var LEGACY_WRITE_TOOL_ALIASES = /* @__PURE__ */ new Set(["append_wiki_page", "flag_personal_page_for_review"]);
|
|
10
|
+
function isWriteTool(toolName) {
|
|
11
|
+
return WRITE_TOOL_NAMES.has(toolName) || LEGACY_WRITE_TOOL_ALIASES.has(toolName);
|
|
12
|
+
}
|
|
13
|
+
var BrainDispatchError = class extends Error {
|
|
14
|
+
status;
|
|
15
|
+
toolName;
|
|
16
|
+
body;
|
|
17
|
+
code;
|
|
18
|
+
/** The JSON error body, when there is one (e.g. `currentVersion` on a VERSION_CONFLICT). */
|
|
19
|
+
details;
|
|
20
|
+
/**
|
|
21
|
+
* True when the same call can succeed later: 429, 502, 503, 504, and the process_event 409
|
|
22
|
+
* for a source.externalId that is still being processed. Other 409s (VERSION_CONFLICT, an
|
|
23
|
+
* archived skill) need the caller to change something first, so they are not retryable.
|
|
24
|
+
*/
|
|
25
|
+
retryable;
|
|
26
|
+
/** Seconds from the Retry-After header, when the server sent one. */
|
|
27
|
+
retryAfter;
|
|
28
|
+
constructor(status, toolName, body, opts = {}) {
|
|
29
|
+
super(opts.message ?? `[BrainBox] Brain dispatch ${status} (${toolName}): ${body}`);
|
|
30
|
+
this.name = "BrainDispatchError";
|
|
31
|
+
this.status = status;
|
|
32
|
+
this.toolName = toolName;
|
|
33
|
+
this.body = body;
|
|
34
|
+
this.details = parseErrorBody(body);
|
|
35
|
+
const serverCode = typeof this.details?.["code"] === "string" ? this.details["code"] : void 0;
|
|
36
|
+
this.code = serverCode ?? (status === 409 ? "CONFLICT" : `HTTP_${status}`);
|
|
37
|
+
this.retryable = [429, 502, 503, 504].includes(status) || status === 409 && toolName === "process_event" && this.code === "CONFLICT";
|
|
38
|
+
this.retryAfter = opts.retryAfter;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
function parseErrorBody(body) {
|
|
42
|
+
try {
|
|
43
|
+
const parsed = JSON.parse(body);
|
|
44
|
+
return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
45
|
+
} catch {
|
|
46
|
+
return void 0;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function parseRetryAfter(header) {
|
|
50
|
+
const seconds = header === null ? NaN : Number(header);
|
|
51
|
+
return Number.isFinite(seconds) && seconds >= 0 ? seconds : void 0;
|
|
52
|
+
}
|
|
53
|
+
async function dispatchBrainTool(apiUrl, apiKey, projectId, toolName, args) {
|
|
54
|
+
const url = `${apiUrl.replace(/\/+$/, "")}/api/projects/${encodeURIComponent(projectId)}/domain-model/dispatch`;
|
|
55
|
+
const res = await globalThis.fetch(url, {
|
|
56
|
+
method: "POST",
|
|
57
|
+
headers: {
|
|
58
|
+
Authorization: `Bearer ${apiKey}`,
|
|
59
|
+
"Content-Type": "application/json"
|
|
60
|
+
},
|
|
61
|
+
body: JSON.stringify({ tool: toolName, args })
|
|
62
|
+
});
|
|
63
|
+
if (!res.ok) {
|
|
64
|
+
throw new BrainDispatchError(res.status, toolName, await res.text(), {
|
|
65
|
+
retryAfter: parseRetryAfter(res.headers.get("retry-after"))
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
const contentType = res.headers.get("content-type") ?? "";
|
|
69
|
+
if (!contentType.includes("application/json")) {
|
|
70
|
+
throw new Error(`[BrainBox] Brain dispatch returned non-JSON response (${contentType}) for tool '${toolName}'`);
|
|
71
|
+
}
|
|
72
|
+
return res.json();
|
|
73
|
+
}
|
|
74
|
+
function createBrainExecutor(apiUrl, apiKey, projectId) {
|
|
75
|
+
return async (toolName, args, callOpts) => {
|
|
76
|
+
if (callOpts?.projectId !== void 0 && callOpts.projectId !== projectId) {
|
|
77
|
+
throw new Error(
|
|
78
|
+
`[BrainBox] Per-call projectId targeting ("${callOpts.projectId}") is only supported for tenant-key handles.`
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
return dispatchBrainTool(apiUrl, apiKey, projectId, toolName, args);
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
function createTenantBrainExecutor(apiUrl, apiKey, view) {
|
|
85
|
+
const validBaseIds = new Set(view.bases.map((b) => b.projectId));
|
|
86
|
+
return async (toolName, args, callOpts) => {
|
|
87
|
+
const requestedProjectId = callOpts?.projectId;
|
|
88
|
+
if (requestedProjectId !== void 0 && requestedProjectId !== view.overlay.projectId && !validBaseIds.has(requestedProjectId)) {
|
|
89
|
+
throw new Error(
|
|
90
|
+
`[BrainBox] projectId "${requestedProjectId}" is not a readable project for this tenant key. Readable projects: overlay (${view.overlay.projectId}), bases: ${[...validBaseIds].join(", ") || "(none)"}.`
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
if (isWriteTool(toolName)) {
|
|
94
|
+
const targetsBase = requestedProjectId !== void 0 && requestedProjectId !== view.overlay.projectId;
|
|
95
|
+
if (targetsBase && DESTRUCTIVE_TOOL_NAMES.has(toolName)) {
|
|
96
|
+
throw new Error(
|
|
97
|
+
`[BrainBox] ${toolName} cannot target base project "${requestedProjectId}": a tenant key can only archive its own overlay's content.`
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
const writeArgs = targetsBase ? { ...args, appliesTo: requestedProjectId } : args;
|
|
101
|
+
return dispatchBrainTool(apiUrl, apiKey, view.overlay.projectId, toolName, writeArgs);
|
|
102
|
+
}
|
|
103
|
+
return dispatchBrainTool(apiUrl, apiKey, requestedProjectId ?? view.overlay.projectId, toolName, args);
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export {
|
|
108
|
+
WRITE_TOOL_NAMES,
|
|
109
|
+
BrainDispatchError,
|
|
110
|
+
createBrainExecutor,
|
|
111
|
+
createTenantBrainExecutor
|
|
112
|
+
};
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createBrainExecutor,
|
|
3
|
+
createTenantBrainExecutor
|
|
4
|
+
} from "./chunk-GVWDS5TG.js";
|
|
1
5
|
import {
|
|
2
6
|
__export
|
|
3
7
|
} from "./chunk-MLKGABMK.js";
|
|
@@ -166,112 +170,6 @@ var NoopSqlClient = class {
|
|
|
166
170
|
}
|
|
167
171
|
};
|
|
168
172
|
|
|
169
|
-
// src/serve/connectors/brain.ts
|
|
170
|
-
import { BRAIN_TOOL_DEFS } from "@brainbox-labs/types";
|
|
171
|
-
var WRITE_TOOL_NAMES = new Set(
|
|
172
|
-
BRAIN_TOOL_DEFS.filter((t) => !t.annotations.readOnlyHint).map((t) => t.name)
|
|
173
|
-
);
|
|
174
|
-
var DESTRUCTIVE_TOOL_NAMES = new Set(
|
|
175
|
-
BRAIN_TOOL_DEFS.filter((t) => t.annotations.destructiveHint).map((t) => t.name)
|
|
176
|
-
);
|
|
177
|
-
var LEGACY_WRITE_TOOL_ALIASES = /* @__PURE__ */ new Set(["append_wiki_page", "flag_personal_page_for_review"]);
|
|
178
|
-
function isWriteTool(toolName) {
|
|
179
|
-
return WRITE_TOOL_NAMES.has(toolName) || LEGACY_WRITE_TOOL_ALIASES.has(toolName);
|
|
180
|
-
}
|
|
181
|
-
var BrainDispatchError = class extends Error {
|
|
182
|
-
status;
|
|
183
|
-
toolName;
|
|
184
|
-
body;
|
|
185
|
-
code;
|
|
186
|
-
/** The JSON error body, when there is one (e.g. `currentVersion` on a VERSION_CONFLICT). */
|
|
187
|
-
details;
|
|
188
|
-
/**
|
|
189
|
-
* True when the same call can succeed later: 429, 502, 503, 504, and the process_event 409
|
|
190
|
-
* for a source.externalId that is still being processed. Other 409s (VERSION_CONFLICT, an
|
|
191
|
-
* archived skill) need the caller to change something first, so they are not retryable.
|
|
192
|
-
*/
|
|
193
|
-
retryable;
|
|
194
|
-
/** Seconds from the Retry-After header, when the server sent one. */
|
|
195
|
-
retryAfter;
|
|
196
|
-
constructor(status, toolName, body, opts = {}) {
|
|
197
|
-
super(opts.message ?? `[BrainBox] Brain dispatch ${status} (${toolName}): ${body}`);
|
|
198
|
-
this.name = "BrainDispatchError";
|
|
199
|
-
this.status = status;
|
|
200
|
-
this.toolName = toolName;
|
|
201
|
-
this.body = body;
|
|
202
|
-
this.details = parseErrorBody(body);
|
|
203
|
-
const serverCode = typeof this.details?.["code"] === "string" ? this.details["code"] : void 0;
|
|
204
|
-
this.code = serverCode ?? (status === 409 ? "CONFLICT" : `HTTP_${status}`);
|
|
205
|
-
this.retryable = [429, 502, 503, 504].includes(status) || status === 409 && toolName === "process_event" && this.code === "CONFLICT";
|
|
206
|
-
this.retryAfter = opts.retryAfter;
|
|
207
|
-
}
|
|
208
|
-
};
|
|
209
|
-
function parseErrorBody(body) {
|
|
210
|
-
try {
|
|
211
|
-
const parsed = JSON.parse(body);
|
|
212
|
-
return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
213
|
-
} catch {
|
|
214
|
-
return void 0;
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
function parseRetryAfter(header) {
|
|
218
|
-
const seconds = header === null ? NaN : Number(header);
|
|
219
|
-
return Number.isFinite(seconds) && seconds >= 0 ? seconds : void 0;
|
|
220
|
-
}
|
|
221
|
-
async function dispatchBrainTool(apiUrl, apiKey, projectId, toolName, args) {
|
|
222
|
-
const url = `${apiUrl.replace(/\/+$/, "")}/api/projects/${encodeURIComponent(projectId)}/domain-model/dispatch`;
|
|
223
|
-
const res = await globalThis.fetch(url, {
|
|
224
|
-
method: "POST",
|
|
225
|
-
headers: {
|
|
226
|
-
Authorization: `Bearer ${apiKey}`,
|
|
227
|
-
"Content-Type": "application/json"
|
|
228
|
-
},
|
|
229
|
-
body: JSON.stringify({ tool: toolName, args })
|
|
230
|
-
});
|
|
231
|
-
if (!res.ok) {
|
|
232
|
-
throw new BrainDispatchError(res.status, toolName, await res.text(), {
|
|
233
|
-
retryAfter: parseRetryAfter(res.headers.get("retry-after"))
|
|
234
|
-
});
|
|
235
|
-
}
|
|
236
|
-
const contentType = res.headers.get("content-type") ?? "";
|
|
237
|
-
if (!contentType.includes("application/json")) {
|
|
238
|
-
throw new Error(`[BrainBox] Brain dispatch returned non-JSON response (${contentType}) for tool '${toolName}'`);
|
|
239
|
-
}
|
|
240
|
-
return res.json();
|
|
241
|
-
}
|
|
242
|
-
function createBrainExecutor(apiUrl, apiKey, projectId) {
|
|
243
|
-
return async (toolName, args, callOpts) => {
|
|
244
|
-
if (callOpts?.projectId !== void 0 && callOpts.projectId !== projectId) {
|
|
245
|
-
throw new Error(
|
|
246
|
-
`[BrainBox] Per-call projectId targeting ("${callOpts.projectId}") is only supported for tenant-key handles.`
|
|
247
|
-
);
|
|
248
|
-
}
|
|
249
|
-
return dispatchBrainTool(apiUrl, apiKey, projectId, toolName, args);
|
|
250
|
-
};
|
|
251
|
-
}
|
|
252
|
-
function createTenantBrainExecutor(apiUrl, apiKey, view) {
|
|
253
|
-
const validBaseIds = new Set(view.bases.map((b) => b.projectId));
|
|
254
|
-
return async (toolName, args, callOpts) => {
|
|
255
|
-
const requestedProjectId = callOpts?.projectId;
|
|
256
|
-
if (requestedProjectId !== void 0 && requestedProjectId !== view.overlay.projectId && !validBaseIds.has(requestedProjectId)) {
|
|
257
|
-
throw new Error(
|
|
258
|
-
`[BrainBox] projectId "${requestedProjectId}" is not a readable project for this tenant key. Readable projects: overlay (${view.overlay.projectId}), bases: ${[...validBaseIds].join(", ") || "(none)"}.`
|
|
259
|
-
);
|
|
260
|
-
}
|
|
261
|
-
if (isWriteTool(toolName)) {
|
|
262
|
-
const targetsBase = requestedProjectId !== void 0 && requestedProjectId !== view.overlay.projectId;
|
|
263
|
-
if (targetsBase && DESTRUCTIVE_TOOL_NAMES.has(toolName)) {
|
|
264
|
-
throw new Error(
|
|
265
|
-
`[BrainBox] ${toolName} cannot target base project "${requestedProjectId}": a tenant key can only archive its own overlay's content.`
|
|
266
|
-
);
|
|
267
|
-
}
|
|
268
|
-
const writeArgs = targetsBase ? { ...args, appliesTo: requestedProjectId } : args;
|
|
269
|
-
return dispatchBrainTool(apiUrl, apiKey, view.overlay.projectId, toolName, writeArgs);
|
|
270
|
-
}
|
|
271
|
-
return dispatchBrainTool(apiUrl, apiKey, requestedProjectId ?? view.overlay.projectId, toolName, args);
|
|
272
|
-
};
|
|
273
|
-
}
|
|
274
|
-
|
|
275
173
|
// src/serve/server.ts
|
|
276
174
|
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
277
175
|
import {
|
|
@@ -637,10 +535,6 @@ var MCP = class {
|
|
|
637
535
|
};
|
|
638
536
|
|
|
639
537
|
export {
|
|
640
|
-
WRITE_TOOL_NAMES,
|
|
641
|
-
BrainDispatchError,
|
|
642
|
-
createBrainExecutor,
|
|
643
|
-
createTenantBrainExecutor,
|
|
644
538
|
BrainBoxClient,
|
|
645
539
|
isTenantKey,
|
|
646
540
|
discoverProjectsView,
|
|
@@ -50,7 +50,13 @@ async function resolveIds(api, ctx) {
|
|
|
50
50
|
const project = await api.getOrCreateProject(org.id, ctx.project);
|
|
51
51
|
return { orgId: org.id, projectId: project.id };
|
|
52
52
|
}
|
|
53
|
-
async function
|
|
53
|
+
async function lookupIds(api, ctx) {
|
|
54
|
+
const org = await api.getOrg(ctx.org);
|
|
55
|
+
if (CUID2_RE.test(ctx.project)) return { orgId: org.id, projectId: ctx.project };
|
|
56
|
+
const project = (await api.listProjects(org.id)).find((p) => p.name === ctx.project);
|
|
57
|
+
return { orgId: org.id, projectId: project?.id };
|
|
58
|
+
}
|
|
59
|
+
async function performIngest(ctx, opts, ids) {
|
|
54
60
|
if (!opts.postgres && !opts.trino && !opts.athena && !opts.sql && !opts.docs && !opts.text && !opts.skill) {
|
|
55
61
|
throw new Error(
|
|
56
62
|
"[BrainBox] brain.ingest requires at least one source: postgres, trino, athena, sql, docs, text, or skill."
|
|
@@ -69,11 +75,11 @@ async function performIngest(ctx, opts) {
|
|
|
69
75
|
const [{ introspectDatabaseSchema }, { parseSqlInputs }, { expandDocPatterns, inlineText }, { connectAndProfile }] = await Promise.all([
|
|
70
76
|
import("./introspect-KQOOQEZM.js"),
|
|
71
77
|
import("./sql-parser-TB26PFXS.js"),
|
|
72
|
-
import("./docs-loader-
|
|
78
|
+
import("./docs-loader-VA4KBG6Y.js"),
|
|
73
79
|
import("./column-profiler-FJCAQQAS.js")
|
|
74
80
|
]);
|
|
75
81
|
const api = new BrainBoxApiClient(ctx.apiUrl, ctx.apiKey, noopLogger);
|
|
76
|
-
const { orgId, projectId } = await resolveIds(api, ctx);
|
|
82
|
+
const { orgId, projectId } = ids ?? await resolveIds(api, ctx);
|
|
77
83
|
const timeoutMs = opts.timeoutMs ?? 3e5;
|
|
78
84
|
const reviewOnly = opts.reviewOnly ?? false;
|
|
79
85
|
const force = opts.force ?? false;
|
|
@@ -131,9 +137,18 @@ async function performIngest(ctx, opts) {
|
|
|
131
137
|
}
|
|
132
138
|
if (docSources.length > 0) {
|
|
133
139
|
await runOrFail("docs", async () => {
|
|
134
|
-
const connector = await api.createDocsConnector(
|
|
135
|
-
|
|
136
|
-
|
|
140
|
+
const connector = await api.createDocsConnector(
|
|
141
|
+
orgId,
|
|
142
|
+
projectId,
|
|
143
|
+
docSources,
|
|
144
|
+
void 0,
|
|
145
|
+
opts.analysisDepth,
|
|
146
|
+
opts.forceDocs ? { force: true } : void 0
|
|
147
|
+
);
|
|
148
|
+
const unchanged = connector.unchanged && connector.unchanged.length > 0 ? { unchanged: connector.unchanged } : {};
|
|
149
|
+
if (!connector.id) return { kind: "docs", ...unchanged };
|
|
150
|
+
if (dryRun) return { kind: "docs", connectorDraftId: connector.id, ...unchanged };
|
|
151
|
+
return { ...await runStage(api, orgId, projectId, "docs", connector.id, timeoutMs, reviewOnly, [], force), ...unchanged };
|
|
137
152
|
});
|
|
138
153
|
}
|
|
139
154
|
if (opts.skill) {
|
|
@@ -148,5 +163,7 @@ async function performIngest(ctx, opts) {
|
|
|
148
163
|
|
|
149
164
|
export {
|
|
150
165
|
IngestPartialFailureError,
|
|
166
|
+
resolveIds,
|
|
167
|
+
lookupIds,
|
|
151
168
|
performIngest
|
|
152
169
|
};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { DocumentSource, AnalysisDepth } from '@brainbox-labs/types';
|
|
2
|
+
|
|
3
|
+
/** An object form of a `docs` entry: a file `path` or inline `content`, with optional sync identity. */
|
|
4
|
+
interface DocEntry {
|
|
5
|
+
/** File path or glob. With `sourceKey` it must match exactly one file. */
|
|
6
|
+
path?: string;
|
|
7
|
+
/** Inline content, used instead of `path`. */
|
|
8
|
+
content?: string;
|
|
9
|
+
/** Display name. Defaults to the file's base name; required with inline `content` unless `sourceKey` is set. */
|
|
10
|
+
name?: string;
|
|
11
|
+
type?: DocumentSource['type'];
|
|
12
|
+
/** Stable identity (1-256 chars, no '/'). Re-ingest of the same key updates the same page. */
|
|
13
|
+
sourceKey?: string;
|
|
14
|
+
/** Opaque version; the server skips an ingest whose key + version + namespace + depth are unchanged. Defaults to a content hash. */
|
|
15
|
+
sourceVersion?: string;
|
|
16
|
+
namespace?: string;
|
|
17
|
+
metadata?: Record<string, string>;
|
|
18
|
+
analysisDepth?: AnalysisDepth;
|
|
19
|
+
}
|
|
20
|
+
declare function expandDocPatterns(patterns: Array<string | DocEntry>, outputDir?: string, analysisDepth?: AnalysisDepth): Promise<DocumentSource[]>;
|
|
21
|
+
/** Wrap free-form text as an inline DocumentSource. Filename is fixed — callers
|
|
22
|
+
* should not see their `message` reflected back as a server-visible doc name. */
|
|
23
|
+
declare function inlineText(text: string, analysisDepth?: AnalysisDepth): DocumentSource;
|
|
24
|
+
|
|
25
|
+
export { type DocEntry as D, expandDocPatterns as e, inlineText as i };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { AnalysisDepth, GrepWikiArgs, GrepWikiResult, McpToolDefinition, GetIndexArgs, GetIndexResult, ListLearningsResult, ListPersonalPagesArgs, ListPersonalPagesResult, GetRecentChangesArgs, GetRecentChangesResult, RecallDomainArgs, ListTracesArgs, ListTracesResult, RecallTracesArgs, ListWikiPagesArgs, ListWikiPagesResult, RecallWikiArgs, CheckContextDraftArgs, CheckContextDraftResult, GetTraceArgs, GetWikiPageArgs, ResearchTaskArgs, ResearchTaskResult, ListSkillsResult, GetSkillArgs, GetSkillResult, CreateLearningArgs, CreateLearningResult, RetireLearningArgs, RetireLearningResult, ReportContextGapArgs, ReportContextGapResult, SaveDomainArgs, SaveDomainResult, ProcessEventArgs, CreateSkillArgs, CreateSkillResult, ArchiveWikiPageArgs, ArchiveResult, ArchiveTraceArgs, SaveWikiPageArgs, AppendWikiPageResult, SaveWikiPageResult, SavePersonalPageArgs, SavePersonalPageResult, AppendWikiPageArgs, FlagPersonalPageForReviewArgs, Project } from '@brainbox-labs/types';
|
|
2
|
+
import { D as DocEntry } from './docs-loader-B2l0cO36.js';
|
|
2
3
|
import { M as MCPOptions, a as MCP } from './index-qV0gq2eJ.js';
|
|
3
4
|
export { i as serve } from './index-qV0gq2eJ.js';
|
|
4
5
|
|
|
@@ -58,8 +59,11 @@ interface IngestOptions {
|
|
|
58
59
|
/**
|
|
59
60
|
* Glob patterns matching doc files (md, txt, html, pdf, docx).
|
|
60
61
|
* PDF and DOCX are auto-converted to markdown; html is passed as-is.
|
|
62
|
+
* An entry may instead be an object `{ path | content, sourceKey, sourceVersion, namespace, metadata }`
|
|
63
|
+
* to give the doc a stable identity: re-ingesting the same `sourceKey` updates the same page, and an
|
|
64
|
+
* unchanged key + version is skipped server-side (reported in `IngestStageResult.unchanged`).
|
|
61
65
|
*/
|
|
62
|
-
docs?: string
|
|
66
|
+
docs?: Array<string | DocEntry>;
|
|
63
67
|
/**
|
|
64
68
|
* Directory where converted markdown files (from PDF and DOCX sources) are written.
|
|
65
69
|
* Created automatically if it does not exist. Only applies when `docs` is set.
|
|
@@ -91,6 +95,9 @@ interface IngestOptions {
|
|
|
91
95
|
reviewOnly?: boolean;
|
|
92
96
|
/** Re-process the last connector draft instead of uploading sources again. */
|
|
93
97
|
force?: boolean;
|
|
98
|
+
/** Send `force: true` on the docs connector so the server does not skip keyed sources it considers
|
|
99
|
+
* unchanged (workaround for a failed extraction that left the page looking current, context-layer #469). */
|
|
100
|
+
forceDocs?: boolean;
|
|
94
101
|
/**
|
|
95
102
|
* Stop after creating the connector draft — do not create a context or activate a version.
|
|
96
103
|
* Useful for inspecting what would be submitted before committing to a full ingest.
|
|
@@ -99,7 +106,10 @@ interface IngestOptions {
|
|
|
99
106
|
}
|
|
100
107
|
interface IngestStageResult {
|
|
101
108
|
kind: 'sql' | 'docs' | 'skill';
|
|
102
|
-
|
|
109
|
+
/** Absent when the server skipped every keyed source as unchanged (no connector was created). */
|
|
110
|
+
connectorDraftId?: string;
|
|
111
|
+
/** Docs stage: sourceKeys the server skipped as unchanged. */
|
|
112
|
+
unchanged?: string[];
|
|
103
113
|
/** Absent when `dryRun: true`. */
|
|
104
114
|
contextId?: string;
|
|
105
115
|
/** Present unless `reviewOnly: true` or `dryRun: true`. */
|
|
@@ -176,6 +186,69 @@ declare class BrainDispatchError extends Error {
|
|
|
176
186
|
});
|
|
177
187
|
}
|
|
178
188
|
|
|
189
|
+
interface SyncOptions {
|
|
190
|
+
/** Directory of docs to sync (md, txt, html, pdf, docx). Dot-directories and node_modules are skipped. */
|
|
191
|
+
dir?: string;
|
|
192
|
+
/** In-memory / explicit sources, alone or on top of `dir`. Without a `sourceKey` the key is derived from `name` (or the file name). */
|
|
193
|
+
sources?: DocEntry[];
|
|
194
|
+
/**
|
|
195
|
+
* Namespace the pages live in; part of every derived key. Defaults to the basename of `dir`
|
|
196
|
+
* (`docs/kb` -> `kb`); required when syncing `sources` without a `dir`. A namespace is owned by
|
|
197
|
+
* ONE sync root: deletes are computed against every keyed raw-source page in exactly this
|
|
198
|
+
* namespace, so pages written there by anything else (brain.ingest with a sourceKey, another
|
|
199
|
+
* folder's sync) show up as pending deletes. Synced-in namespaces are read-only locally.
|
|
200
|
+
*/
|
|
201
|
+
namespace?: string;
|
|
202
|
+
/** Transform script: a name under `.brainbox/transforms/` in the current working directory, or a path relative to it. Its content hash is folded into sourceVersion. */
|
|
203
|
+
transform?: string;
|
|
204
|
+
/** Pre-approve archiving docs that no longer exist locally. Default false: they come back as `pendingDeletes`. */
|
|
205
|
+
prune?: boolean;
|
|
206
|
+
/** Send every doc and tell the server not to skip unchanged ones (workaround for context-layer #469). */
|
|
207
|
+
force?: boolean;
|
|
208
|
+
/** Diff only: no ingest, no archive, and nothing is created (a missing project just reports every doc as added). */
|
|
209
|
+
dryRun?: boolean;
|
|
210
|
+
analysisDepth?: AnalysisDepth;
|
|
211
|
+
timeoutMs?: number;
|
|
212
|
+
/** Stop before activating the new version so a reviewer can curate first. */
|
|
213
|
+
reviewOnly?: boolean;
|
|
214
|
+
}
|
|
215
|
+
interface SyncEntry {
|
|
216
|
+
sourceKey: string;
|
|
217
|
+
name: string;
|
|
218
|
+
}
|
|
219
|
+
interface PendingDelete {
|
|
220
|
+
sourceKey: string;
|
|
221
|
+
title: string;
|
|
222
|
+
}
|
|
223
|
+
interface SyncResult {
|
|
224
|
+
dryRun: boolean;
|
|
225
|
+
/** The namespace this sync owns (default: the synced dir's basename). */
|
|
226
|
+
namespace: string;
|
|
227
|
+
/** Dry run only: the project doesn't exist yet, so everything is reported as added. */
|
|
228
|
+
projectMissing?: boolean;
|
|
229
|
+
/** The server may have cut the listing short, so deletes were not computed (nothing is reported or archived). */
|
|
230
|
+
listingTruncated?: boolean;
|
|
231
|
+
added: SyncEntry[];
|
|
232
|
+
changed: SyncEntry[];
|
|
233
|
+
/** Same key + version + namespace as the Brain. Not sent unless `force`. */
|
|
234
|
+
unchanged: SyncEntry[];
|
|
235
|
+
/** In the Brain but no longer present locally. */
|
|
236
|
+
deleted: PendingDelete[];
|
|
237
|
+
/** `deleted` minus what was archived: nothing is archived without `prune` (or `brain.prune`). */
|
|
238
|
+
pendingDeletes: PendingDelete[];
|
|
239
|
+
archived: string[];
|
|
240
|
+
/** Keys the server itself reported as unchanged. */
|
|
241
|
+
skippedByServer: string[];
|
|
242
|
+
/** Files a transform dropped (returned null). */
|
|
243
|
+
skippedByTransform: string[];
|
|
244
|
+
/** Absent for a dry run or when nothing needed ingesting. */
|
|
245
|
+
ingest?: IngestResult;
|
|
246
|
+
}
|
|
247
|
+
interface PruneResult {
|
|
248
|
+
archived: string[];
|
|
249
|
+
notFound: string[];
|
|
250
|
+
}
|
|
251
|
+
|
|
179
252
|
interface LocalGrepWikiArgs extends GrepWikiArgs {
|
|
180
253
|
/** Narrow to this namespace and everything under it. Mutually exclusive with `tag`. */
|
|
181
254
|
namespace?: string;
|
|
@@ -355,6 +428,22 @@ declare class BrainBox {
|
|
|
355
428
|
* project/org keys, requires `project` on the parent handle.
|
|
356
429
|
*/
|
|
357
430
|
ingest(opts: IngestOptions): Promise<IngestResult>;
|
|
431
|
+
/**
|
|
432
|
+
* Sync a folder (or explicit sources) with this brain by stable `sourceKey`: list what the
|
|
433
|
+
* brain holds, ingest new and changed docs in one batch, and report docs deleted locally as
|
|
434
|
+
* `pendingDeletes`. Nothing is archived unless `prune: true`; apply a user's decision later
|
|
435
|
+
* with {@link BrainBox.prune}. Targets the handle's `project` like {@link BrainBox.ingest};
|
|
436
|
+
* tenant keys are not supported yet.
|
|
437
|
+
*
|
|
438
|
+
* `namespace` defaults to the synced dir's basename and is owned by this one sync root: deletes
|
|
439
|
+
* are computed against every keyed raw-source page in exactly that namespace, so other writers
|
|
440
|
+
* into it show up as pending deletes.
|
|
441
|
+
*/
|
|
442
|
+
sync(opts: SyncOptions): Promise<SyncResult>;
|
|
443
|
+
/** Archive the synced pages for these `sourceKey`s (soft, reversible server-side). Unknown keys come back in `notFound`. */
|
|
444
|
+
prune(sourceKeys: string[]): Promise<PruneResult>;
|
|
445
|
+
/** Target for write-side calls: a tenant key's overlay project, else the handle's `project`. */
|
|
446
|
+
private ingestContext;
|
|
358
447
|
private getExecutor;
|
|
359
448
|
/** Best-effort scope label from the key prefix alone — logged before any network call. */
|
|
360
449
|
private logDeclaredScope;
|
|
@@ -384,4 +473,4 @@ declare class BrainBoxServe {
|
|
|
384
473
|
mcp(opts?: Omit<MCPOptions, 'apiKey' | 'project' | 'apiUrl'>): MCP;
|
|
385
474
|
}
|
|
386
475
|
|
|
387
|
-
export { BrainBox, type BrainBoxOptions, BrainBoxServe, BrainDispatchError, type BrainProjects, type IngestOptions, IngestPartialFailureError, type IngestPostgresOptions, type IngestResult, type IngestStageResult, type LocalGrepWikiArgs, type LocalGrepWikiResult, type ProjectView, type TenantView, isTenantKey };
|
|
476
|
+
export { BrainBox, type BrainBoxOptions, BrainBoxServe, BrainDispatchError, type BrainProjects, DocEntry, type IngestOptions, IngestPartialFailureError, type IngestPostgresOptions, type IngestResult, type IngestStageResult, type LocalGrepWikiArgs, type LocalGrepWikiResult, type PendingDelete, type ProjectView, type PruneResult, type SyncEntry, type SyncOptions, type SyncResult, type TenantView, isTenantKey };
|
package/dist/index.js
CHANGED
|
@@ -1,18 +1,20 @@
|
|
|
1
1
|
import {
|
|
2
2
|
IngestPartialFailureError
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-XFLBPF4A.js";
|
|
4
4
|
import {
|
|
5
5
|
BrainBoxClient,
|
|
6
|
-
BrainDispatchError,
|
|
7
6
|
MCP,
|
|
8
|
-
WRITE_TOOL_NAMES,
|
|
9
|
-
createBrainExecutor,
|
|
10
|
-
createTenantBrainExecutor,
|
|
11
7
|
discoverProjectsView,
|
|
12
8
|
isTenantKey,
|
|
13
9
|
serve_exports,
|
|
14
10
|
tenantViewFrom
|
|
15
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-MF3BADT7.js";
|
|
12
|
+
import {
|
|
13
|
+
BrainDispatchError,
|
|
14
|
+
WRITE_TOOL_NAMES,
|
|
15
|
+
createBrainExecutor,
|
|
16
|
+
createTenantBrainExecutor
|
|
17
|
+
} from "./chunk-GVWDS5TG.js";
|
|
16
18
|
import "./chunk-MLKGABMK.js";
|
|
17
19
|
|
|
18
20
|
// src/brain.ts
|
|
@@ -383,36 +385,53 @@ var BrainBox = class {
|
|
|
383
385
|
* project/org keys, requires `project` on the parent handle.
|
|
384
386
|
*/
|
|
385
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-K4NBZBF3.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
|
+
if (isTenantKey(this.options.apiKey)) {
|
|
414
|
+
throw new Error("[BrainBox] brain.prune does not support tenant keys yet. Use a project or org key.");
|
|
415
|
+
}
|
|
416
|
+
const ctx = await this.ingestContext("prune");
|
|
417
|
+
const { performPrune } = await import("./sync-K4NBZBF3.js");
|
|
418
|
+
return performPrune(ctx, sourceKeys);
|
|
419
|
+
}
|
|
420
|
+
/** Target for write-side calls: a tenant key's overlay project, else the handle's `project`. */
|
|
421
|
+
async ingestContext(op) {
|
|
386
422
|
const apiUrl = this.options.apiUrl ?? DEFAULT_API_URL;
|
|
387
|
-
this.logDeclaredScope(
|
|
388
|
-
const { performIngest } = await import("./ingest-OA6KWJNR.js");
|
|
423
|
+
this.logDeclaredScope(op);
|
|
389
424
|
if (isTenantKey(this.options.apiKey)) {
|
|
390
425
|
const view = await this.getTenantView();
|
|
391
|
-
this.logConfirmedScope(
|
|
392
|
-
return
|
|
393
|
-
{
|
|
394
|
-
apiUrl,
|
|
395
|
-
apiKey: this.options.apiKey,
|
|
396
|
-
org: this.options.org,
|
|
397
|
-
project: view.overlay.projectId
|
|
398
|
-
},
|
|
399
|
-
opts
|
|
400
|
-
);
|
|
426
|
+
this.logConfirmedScope(op, "tenant", `overlay=${view.overlay.projectId}`);
|
|
427
|
+
return { apiUrl, apiKey: this.options.apiKey, org: this.options.org, project: view.overlay.projectId };
|
|
401
428
|
}
|
|
402
429
|
if (!this.options.project) {
|
|
403
430
|
throw new Error(
|
|
404
|
-
|
|
431
|
+
`[BrainBox] brain.${op} requires a project. Pass \`project\` to new BrainBox({...}).`
|
|
405
432
|
);
|
|
406
433
|
}
|
|
407
|
-
return
|
|
408
|
-
{
|
|
409
|
-
apiUrl,
|
|
410
|
-
apiKey: this.options.apiKey,
|
|
411
|
-
org: this.options.org,
|
|
412
|
-
project: this.options.project
|
|
413
|
-
},
|
|
414
|
-
opts
|
|
415
|
-
);
|
|
434
|
+
return { apiUrl, apiKey: this.options.apiKey, org: this.options.org, project: this.options.project };
|
|
416
435
|
}
|
|
417
436
|
async getExecutor() {
|
|
418
437
|
this.logDeclaredScope("recall/update");
|
package/dist/ingest/public.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { RawSchema, ColumnProfile, JsonKeyEntry
|
|
1
|
+
import { RawSchema, ColumnProfile, JsonKeyEntry } from '@brainbox-labs/types';
|
|
2
|
+
export { e as expandDocPatterns, i as inlineText } from '../docs-loader-B2l0cO36.js';
|
|
2
3
|
|
|
3
4
|
type Dialect = 'postgres' | 'mysql' | 'sqlite' | 'duckdb' | 'trino' | 'athena';
|
|
4
5
|
type ProfileMode = 'cardinality' | 'full';
|
|
@@ -174,9 +175,4 @@ declare function convertToMarkdown(filePath: string): Promise<string>;
|
|
|
174
175
|
*/
|
|
175
176
|
declare function convertedName(filePath: string): string;
|
|
176
177
|
|
|
177
|
-
|
|
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 };
|
|
178
|
+
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, extractJsonShape, htmlToMarkdown, introspectAthenaSchema, introspectAthenaSchemaWithConnection, introspectDatabaseSchema, introspectTrinoSchema, introspectTrinoSchemaWithConnection, needsConversion, openAthenaConnection, openTrinoConnection, parseAthenaUrl, parseProfileMode, parseSkipColumns, parseTrinoUrl, quoteIdentifier };
|
package/dist/ingest/public.js
CHANGED
|
@@ -1,11 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
convertToMarkdown,
|
|
3
|
-
convertedName,
|
|
4
|
-
expandDocPatterns,
|
|
5
|
-
htmlToMarkdown,
|
|
6
|
-
inlineText,
|
|
7
|
-
needsConversion
|
|
8
|
-
} from "../chunk-ANGBZHCB.js";
|
|
9
1
|
import {
|
|
10
2
|
ColumnProfiler,
|
|
11
3
|
connectAndProfile,
|
|
@@ -16,6 +8,14 @@ import {
|
|
|
16
8
|
parseSkipColumns,
|
|
17
9
|
quoteIdentifier
|
|
18
10
|
} from "../chunk-VEXUCOXR.js";
|
|
11
|
+
import {
|
|
12
|
+
convertToMarkdown,
|
|
13
|
+
convertedName,
|
|
14
|
+
expandDocPatterns,
|
|
15
|
+
htmlToMarkdown,
|
|
16
|
+
inlineText,
|
|
17
|
+
needsConversion
|
|
18
|
+
} from "../chunk-4J77FNJJ.js";
|
|
19
19
|
import {
|
|
20
20
|
introspectTrinoSchema,
|
|
21
21
|
introspectTrinoSchemaWithConnection,
|
package/dist/serve/index.js
CHANGED
|
@@ -0,0 +1,265 @@
|
|
|
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.18+ / 23.6+, plain typed JS only, 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) validateSourceKey(key);
|
|
239
|
+
for (const key of keys) {
|
|
240
|
+
const r = await api.archiveWikiSource(orgId, projectId, validateSourceKey(key));
|
|
241
|
+
(r === "archived" ? out.archived : out.notFound).push(key);
|
|
242
|
+
}
|
|
243
|
+
return out;
|
|
244
|
+
}
|
|
245
|
+
async function performPrune(ctx, sourceKeys, ids) {
|
|
246
|
+
const api = new BrainBoxApiClient(ctx.apiUrl, ctx.apiKey, noopLogger);
|
|
247
|
+
if (!ids) {
|
|
248
|
+
const found = await lookupIds(api, ctx);
|
|
249
|
+
if (!found.projectId) throw new Error(`[BrainBox] project "${ctx.project}" not found in org "${ctx.org}"`);
|
|
250
|
+
ids = { orgId: found.orgId, projectId: found.projectId };
|
|
251
|
+
}
|
|
252
|
+
return prune(api, ids.orgId, ids.projectId, sourceKeys);
|
|
253
|
+
}
|
|
254
|
+
export {
|
|
255
|
+
applyTransform,
|
|
256
|
+
computeSourceVersion,
|
|
257
|
+
deriveSourceKey,
|
|
258
|
+
diffSources,
|
|
259
|
+
executorLister,
|
|
260
|
+
frontmatterSourceKey,
|
|
261
|
+
loadTransform,
|
|
262
|
+
performPrune,
|
|
263
|
+
performSync,
|
|
264
|
+
validateSourceKey
|
|
265
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@brainbox-labs/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.23.1",
|
|
4
4
|
"description": "BrainBox JavaScript/TypeScript SDK — MCP server + API client",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -31,8 +31,8 @@
|
|
|
31
31
|
"test": "vitest run"
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@brainbox-labs/api": "
|
|
35
|
-
"@brainbox-labs/types": "^1.
|
|
34
|
+
"@brainbox-labs/api": "^0.11.0",
|
|
35
|
+
"@brainbox-labs/types": "^1.34.0",
|
|
36
36
|
"@modelcontextprotocol/sdk": "^1.27.1",
|
|
37
37
|
"dotenv": "^16.4.5",
|
|
38
38
|
"express": "^5.0.0",
|
package/dist/chunk-ANGBZHCB.js
DELETED
|
@@ -1,120 +0,0 @@
|
|
|
1
|
-
// src/ingest/docs-loader.ts
|
|
2
|
-
import * as fs2 from "fs/promises";
|
|
3
|
-
import * as nodePath2 from "path";
|
|
4
|
-
import { glob } from "glob";
|
|
5
|
-
|
|
6
|
-
// src/ingest/doc-converter.ts
|
|
7
|
-
import * as fs from "fs/promises";
|
|
8
|
-
import * as nodePath from "path";
|
|
9
|
-
function needsConversion(filePath) {
|
|
10
|
-
const ext = nodePath.extname(filePath).toLowerCase();
|
|
11
|
-
return ext === ".pdf" || ext === ".docx" || ext === ".html" || ext === ".htm";
|
|
12
|
-
}
|
|
13
|
-
async function htmlToMarkdown(html) {
|
|
14
|
-
const TurndownService = (await import("turndown")).default;
|
|
15
|
-
const td = new TurndownService({ headingStyle: "atx", codeBlockStyle: "fenced" });
|
|
16
|
-
return td.turndown(html);
|
|
17
|
-
}
|
|
18
|
-
async function convertToMarkdown(filePath) {
|
|
19
|
-
const ext = nodePath.extname(filePath).toLowerCase();
|
|
20
|
-
if (ext === ".docx") {
|
|
21
|
-
const mammoth = await import("mammoth");
|
|
22
|
-
const result = await mammoth.convertToHtml({ path: filePath });
|
|
23
|
-
const warnings = result.messages.filter((m) => m.type === "warning").map((m) => m.message);
|
|
24
|
-
if (warnings.length > 0) {
|
|
25
|
-
process.stderr.write(`mammoth warnings for ${nodePath.basename(filePath)}:
|
|
26
|
-
${warnings.join("\n")}
|
|
27
|
-
`);
|
|
28
|
-
}
|
|
29
|
-
return htmlToMarkdown(result.value);
|
|
30
|
-
}
|
|
31
|
-
if (ext === ".html" || ext === ".htm") {
|
|
32
|
-
const html = await fs.readFile(filePath, "utf-8");
|
|
33
|
-
return htmlToMarkdown(html);
|
|
34
|
-
}
|
|
35
|
-
if (ext === ".pdf") {
|
|
36
|
-
const { PDFParse } = await import("pdf-parse");
|
|
37
|
-
const buffer = await fs.readFile(filePath);
|
|
38
|
-
const parser = new PDFParse({ data: buffer });
|
|
39
|
-
try {
|
|
40
|
-
const result = await parser.getText();
|
|
41
|
-
return result.text;
|
|
42
|
-
} finally {
|
|
43
|
-
await parser.destroy();
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
throw new Error(`No converter available for extension "${ext}"`);
|
|
47
|
-
}
|
|
48
|
-
function convertedName(filePath) {
|
|
49
|
-
return nodePath.basename(filePath) + ".md";
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
// src/ingest/docs-loader.ts
|
|
53
|
-
var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
54
|
-
".png",
|
|
55
|
-
".jpg",
|
|
56
|
-
".jpeg",
|
|
57
|
-
".gif",
|
|
58
|
-
".bmp",
|
|
59
|
-
".zip",
|
|
60
|
-
".tar",
|
|
61
|
-
".gz",
|
|
62
|
-
".bz2",
|
|
63
|
-
".7z",
|
|
64
|
-
".exe",
|
|
65
|
-
".dll",
|
|
66
|
-
".so",
|
|
67
|
-
".bin"
|
|
68
|
-
]);
|
|
69
|
-
var CONVERT_EXTENSIONS = /* @__PURE__ */ new Set([".pdf", ".docx"]);
|
|
70
|
-
function inferType(filePath) {
|
|
71
|
-
const ext = nodePath2.extname(filePath).toLowerCase();
|
|
72
|
-
if (ext === ".md" || ext === ".markdown") return "markdown";
|
|
73
|
-
if (ext === ".html" || ext === ".htm") return "html";
|
|
74
|
-
return "text";
|
|
75
|
-
}
|
|
76
|
-
async function expandDocPatterns(patterns, outputDir, analysisDepth) {
|
|
77
|
-
if (outputDir) {
|
|
78
|
-
await fs2.mkdir(outputDir, { recursive: true });
|
|
79
|
-
}
|
|
80
|
-
const sources = [];
|
|
81
|
-
const seen = /* @__PURE__ */ new Set();
|
|
82
|
-
for (const pattern of patterns) {
|
|
83
|
-
const matches = await glob(pattern, { nodir: true, absolute: true });
|
|
84
|
-
for (const file of matches) {
|
|
85
|
-
if (seen.has(file)) continue;
|
|
86
|
-
seen.add(file);
|
|
87
|
-
const ext = nodePath2.extname(file).toLowerCase();
|
|
88
|
-
if (BINARY_EXTENSIONS.has(ext)) {
|
|
89
|
-
throw new Error(
|
|
90
|
-
`Unsupported file type "${ext}" for "${file}". Convert to markdown/text before passing to brain.ingest.`
|
|
91
|
-
);
|
|
92
|
-
}
|
|
93
|
-
if (CONVERT_EXTENSIONS.has(ext)) {
|
|
94
|
-
const content = await convertToMarkdown(file);
|
|
95
|
-
const name = convertedName(file);
|
|
96
|
-
if (outputDir) {
|
|
97
|
-
await fs2.writeFile(nodePath2.join(outputDir, name), content, "utf-8");
|
|
98
|
-
}
|
|
99
|
-
sources.push({ id: name, name, content, type: "markdown", ...analysisDepth && { analysisDepth } });
|
|
100
|
-
} else {
|
|
101
|
-
const content = await fs2.readFile(file, "utf-8");
|
|
102
|
-
const name = nodePath2.basename(file);
|
|
103
|
-
sources.push({ id: name, name, content, type: inferType(file), ...analysisDepth && { analysisDepth } });
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
return sources;
|
|
108
|
-
}
|
|
109
|
-
function inlineText(text, analysisDepth) {
|
|
110
|
-
return { id: "inline.txt", name: "inline.txt", content: text, type: "text", ...analysisDepth && { analysisDepth } };
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
export {
|
|
114
|
-
needsConversion,
|
|
115
|
-
htmlToMarkdown,
|
|
116
|
-
convertToMarkdown,
|
|
117
|
-
convertedName,
|
|
118
|
-
expandDocPatterns,
|
|
119
|
-
inlineText
|
|
120
|
-
};
|